【发布时间】:2018-11-29 13:09:57
【问题描述】:
Powershell 使用 $profile 文件,我想知道每次发生时我在 powershell 上花费了多少时间,将其打印到文件中。
例如
24.11.2018, 13:41 - 1 hour 23 minute 12 second
11.11.2018, 13:41 - 2 hour 3 minute 2 second
11.11.2018, 13:41 - 1 hour 43 minute 42 second
...
...
名为 ps_time_history.txt 的文件的内容如上所示。 我打开powershell屏幕3次,它显示它打开了多长时间。
我已经编写了如下脚本,但我无法得到我想要的解决方案。
我在 $profile 文件中编写了一个脚本,如下所示,但我无法按照我想要的方式获得解决方案。
Start-Job -scriptblock
{
$StopWatch = New-Object -TypeName System.Diagnostics.Stopwatch
$StopWatch.Start();
$date=((Get-Process -Name powershell | Sort-Object StartTime | where { $_ }).StartTime | Select -Last 1);
$id=((Get-Process -Name powershell | Sort-Object StartTime | where { $_ }).id | select -Last 1 );
while ($StopWatch.IsRunning)
{
Start-Sleep -Seconds 1
if((Get-Process -id $id -ErrorAction SilentlyContinue))
{
$time=[string]$StopWatch.Elapsed.Hours+":"+[string]$StopWatch.Elapsed.Minutes+":"+[string]$StopWatch.Elapsed.Seconds;
echo ([string]$date+" - "+$time) >> ~\Desktop\ps_time_history.txt;
}
else
{
$StopWatch.Stop();
}
}
}
我得到了最近打开的 powershell 应用程序的日期和 ID 号。 只要 powershell 屏幕打开,计时器就会运行。 当powershell屏幕关闭时,计时器需要停止。
我正在编写的脚本每秒都在执行 ps_time_history.txt 文件。 但我不想那样。 让Powershell记下我关闭它时花了多少时间。
11/29/2018 02:23:17 - 0: 0: 1
11/29/2018 02:23:17 - 0: 0: 2
11/29/2018 02:23:17 - 0: 0: 3
11/29/2018 02:23:17 - 0: 0: 4
11/29/2018 02:23:17 - 0: 0: 5
11/29/2018 02:23:17 - 0: 0: 6
11/29/2018 02:23:17 - 0: 0: 7
11/29/2018 02:23:17 - 0: 0: 8
11/29/2018 02:23:17 - 0: 0: 9
11/29/2018 02:23:17 - 0: 0: 10
11/29/2018 02:23:17 - 0: 0: 11
11/29/2018 02:23:17 - 0: 0: 12
11/29/2018 02:23:17 - 0: 0: 13
这个问题似乎有点复杂。 我该如何解决这个问题或有更短的方法?
【问题讨论】:
-
“PowerShell 屏幕”“打开”或“关闭”是什么意思?似乎您想要跟踪交互式 PowerShell 会话/进程的持续时间,但您的意思是更具体地说是窗口处于活动状态/聚焦的时间量(甚至更难跟踪)?另外,我认为脚本开头的
$processStartTime = Get-Date之类的内容足以计算持续时间,而不是与Stopwatch混淆。还要记住,Get-Process -Name powershell可能会返回当前进程以外的 PowerShell 进程。
标签: powershell stopwatch