Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 916
kelloti Avatar asked Dec 26 '22 20:12

kelloti


2 Answers

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

like image 111
kelloti Avatar answered Jan 31 '23 01:01

kelloti


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

  • Customizing the PowerShell command prompt
  • Perfect prompt for Windows PowerShell
  • Setting the console title to be your current working directory
like image 41
David Pokluda Avatar answered Jan 30 '23 23:01

David Pokluda