How to detect how long a user stays in one location in powershell How to detect how long a user stays in one location in powershell powershell powershell

How to detect how long a user stays in one location in powershell


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):


You can achieve it with ValidateScript attribute (proposed by @oising) :

$n = 0; (Get-Variable pwd).attributes.Add((new-object ValidateScript { $global:n++; $true }))

Scriptblock { $global:n++; $true } will be executed on every 'set' for $pwd variable. It similar to breakpoint approach, but doesn't have performance downside.