I'm trying to log how long a user stays in a directory. Is there any way to intercept an event whenever someone calls Set-Location
?
I also posted to the powershell technet forumn and got a great answer. The short story is, you can set a breakpoint on any object in powershell. With a breakpoint, you can associate a block of code (or leave out the block to pause execution). The even cooler part is that powershell provides a pwd
global object that represents the present working directory. You can set a breakpoint on all "write" actions on this global object.
It's basically an observer pattern or AOP. The best part is this will work for anything that changes the current directory - cd
, pushd
, popd
, etc. Here's my C# cmdlet code:
InvokeCommand.InvokeScript(@"Set-PSBreakpoint -Variable pwd -Mode Write -Action {
[Jump.Location.JumpLocationCommand]::UpdateTime($($(Get-Item -Path $(Get-Location))).PSPath);
}");
I'm calling a static method to track the timings. I guess I just prefer C# when possible :(
I would recommend to use Prompt function (used to display prompt message). In there I would call get-location to get the current location and compare it to a global variable where I stored the previous location. Based on this you can calculate the time and do whatever processing with it.
For more information about the prompt function see the following pages (for example):
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With