PowerShell 技能连载 - 自动记录命令输出

在前一个技能中我们介绍了自 PowerShell 3 以上版本支持的 PreCommandLookupAction。今天我们将介绍一个特别的实现。

当您运行一下代码时,PowerShell 将会接受所有以 “*” 开头的命令并将命令的输出记录到一个文本文件中。当命令执行完毕,将会打开该文本文件。

现在您可以运行 *dir 来代替 dir,来保存结果,或用 *Get-Process 代替 Get-Process

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
$ExecutionContext.SessionState.InvokeCommand.PreCommandLookupAction = {
# is called whenever a command is ready to execute
param($command, $eventArgs)

# check commands that start with "*" and were not
# executed internally by PowerShell
if ($command.StartsWith('*') -and $eventArgs.CommandOrigin -eq 'Runspace')
{
# save command output here
$debugPath = "$env:temp\debugOutput.txt"
# clear text file if it exists
$exists = Test-Path $debugPath
if ($exists) { Remove-Item -Path $debugPath }
# remove leading "*" from a command name
$command = $command.Substring(1)
# tell PowerShell what to do instead of
# running the original command
$eventArgs.CommandScriptBlock = {
# run the original command without "*", and
# submit original arguments if there have been any
$(
if ($args.Count -eq 0)
{ & $command }
else
{ & $command $args }
) |
# log output to file
Tee-Object -FilePath $debugPath |
# open the file once all output has been processed
ForEach-Object -Process { $_ } -End {
if (Test-Path $debugPath) { notepad $debugPath }
}
}.GetNewClosure()
}
}

PowerShell 技能连载 - 自动记录命令输出

http://blog.vichamp.com/2017/08/01/auto-logging-command-output/

作者

吴波

发布于

2017-08-01

更新于

2022-07-06

许可协议

评论