PowerShell 技能连载 - 持续监视脚本的运行

以下是一段演示如何在 Windows 注册表中存储私人信息的代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
# store settings here
$Path = "HKCU:\software\powertips\settings"

# check whether key exists
$exists = Test-Path -Path $Path
if ($exists -eq $false)
{
# if this is first run, initialize registry key
$null = New-Item -Path $Path -Force
}

# read existing value
$currentValue = Get-ItemProperty -Path $path
$lastRun = $currentValue.LastRun
if ($lastRun -eq $null)
{
[PSCustomObject]@{
FirstRun = $true
LastRun = $null
Interval = $null
}
}
else
{
$lastRunDate = Get-Date -Date $lastRun
$today = Get-Date
$timeSpan = $today - $lastRunDate

[PSCustomObject]@{
FirstRun = $true
LastRun = $lastRunDate
Interval = $timeSpan
}
}

# write current date and time to registry
$date = Get-Date -Format 'yyyy-MM-dd HH:mm:ss'
$null = New-ItemProperty -Path $Path -Name LastRun -PropertyType String -Value $date -Force

当运行这段代码时,它将返回一个对象,该对象告诉您上次运行此脚本是什么时候,以及从那以后运行了多长时间。

PowerShell 技能连载 - 持续监视脚本的运行

http://blog.vichamp.com/2018/10/16/keeping-track-of-script-execution/

作者

吴波

发布于

2018-10-16

更新于

2022-07-06

许可协议

评论