我是PowerShell的新手,所以这很明显,或者我用自己的方法吠叫了错误的树。但是在这里搜索和Google都没有帮助我(也许是搜索错误的术语?)
我正在尝试编写一个简单的PowerShell脚本(可以正常工作/运行)。但是,我也有一个要求将过程(命令运行和所有输出)记录到我难以实现的txt文件中。我试图使用开始脚本并添加-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
Run Code Online (Sandbox Code Playgroud)
脚本运行,记事本打开,等待5秒钟,然后再次关闭。但是,仅为stop-process命令创建详细输出,这导致仅写入主机消息和stop-process写入我的事务/日志文件。但是,我需要它来将记事本进程启动然后停止的操作写入我的文件。
下面的脚本将为您提供您所要求的内容:
我在脚本本身中添加了每个阶段的注释,以便更好地理解。您可以添加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
Run Code Online (Sandbox Code Playgroud)
示例文件输出:
对于远程执行:
获取进程-名称记事本-计算机名称SERVER01 | 停止进程
注意:有多种方法可以远程停止服务。浏览 PowerShell Remoting 并查看详细信息。
| 归档时间: |
|
| 查看次数: |
10262 次 |
| 最近记录: |