【问题标题】:How to log the PowerShell commands that were run如何记录运行的 PowerShell 命令
【发布时间】:2017-01-04 13:01:02
【问题描述】:

我是 PowerShell 新手,所以这可能很明显,或者我用我的方法找错了树。但是在这里搜索和谷歌并没有帮助我(也许搜索错误的术语?)

我正在尝试编写一个简单的 PowerShell 脚本(工作/运行没有问题)。但是,我还需要将过程(命令运行和任何输出)记录到我正在努力实现的 txt 文件中。我尝试使用 start-transcript 并添加 -verbose 通用参数,但它没有像我预期的那样工作。

我的最终目标是让脚本在我们的一台服务器上运行,这将停止服务,停止服务的任何相关进程,然后再次启动服务。但是对于这个无法记录正在发生的事情的示例,我将其简化为只是启动和停止一个进程。我的例子如下:

Start-Transcript -path "C:\tester.txt" 

Write-Host "starting the shell command"

Start-Process notepad -verbose
Start-Sleep -s 5
Stop-Process -processname notepad -verbose

Stop-Transcript

脚本运行,记事本打开,等待 5 秒钟,然后再次关闭。但是,详细输出仅为 stop-process 命令创建,这只会导致 write-host 消息和 stop-process 被写入我的事务/日志文件。但是我需要它写入我的记事本进程已启动然后停止的文件。

【问题讨论】:

  • 您的 PowerShell 版本是什么?我希望这会显示您运行的命令,但它不适合我,所以我正在测试。
  • 您是否在 ISE 中运行此程序?我得到与你相似的结果。它实际上在 PowerShell 提示符下工作。所以这将是一个错误或现状。不确定是哪个。尝试在常规 PowerShell 中运行它
  • @Matt - 我也尝试从常规 powershell 运行脚本,但得到相同的结果。
  • @Matt - 我有以下版本。主要 - 5,次要 - 1,内部版本 - 14393,修订版 576
  • 是的。这也发生在我身上。如果从 shell 运行命令会发生什么......而不是脚本。我复制并粘贴了您的代码,它有效。不是答案,而是故障排除。

标签: powershell


【解决方案1】:

以下脚本将为您提供所需的内容:

为了更好地理解,我在每个阶段的脚本本身中添加了 cmets。您可以添加一个 Logfile.txt 检查它是否存在,基于此您也可以创建文件。 Get-History 将为您提供所有已在 shell 上执行的命令的历史记录。

$Log_File= "E:\LogFile.txt"

Clear-History
# You can do a file check using Test-Path followed by the path

## Out-file will give the output to the file, -Force will create the file if not existed and -append will append the data.
"starting the shell command" | Out-File $Log_File -Force -Append

Start-Process notepad -verbose

"Notepad started" | Out-File $Log_File -Append

Start-Sleep -s 5
Stop-Process -processname notepad -verbose

"Notepad stopped" | Out-File $Log_File -Force -Append

"List of commands which are executed are below: " | Out-File $Log_File -Force -Append
Get-History | Out-File $Log_File -Append

示例文件输出:

对于远程执行:

Get-Process -Name notepad -ComputerName SERVER01 |停止进程

注意:有多种方法可以远程停止服务。浏览 PowerShell Remoting 并查看详细信息。

【讨论】:

  • 那么你应该为这个解决方法取出转录行吗?您也可以考虑在开始时清除历史记录,这样您就不会得到在此之前未执行的内容。
  • 是的。我们可以把成绩单拿出来。是的,从一开始就清除历史记录也是一个好主意。让我说一下。 @马特
  • 一个更安全的想法是在每次执行后将((Get-History).CommandLine)[-1] 输出到文件中。这样您就可以获得订单并保留历史记录
  • @Matt:修改完毕。是的,我们也可以使用它
  • @RanadipDutta- 当然越来越近了。当我逐行运行上述脚本时,我得到了相同的结果,但是当我在 ISE 或 powershell 提示符中执行脚本时,我只记录了消息的第一部分,没有命令历史记录。当我添加 ((get-history).commandline)[-1] | Out-File $Log_File -Append 在每个命令之后我得到一个关于 NULL 数组的错误。这是否意味着作为脚本运行时不存储历史记录?
猜你喜欢
  • 2013-08-17
  • 2011-06-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-01-08
  • 2021-12-16
  • 1970-01-01
  • 2018-03-14
相关资源
最近更新 更多