gpt4 book ai didi

从脚本到日志文件的 powershell 输出结果

转载 作者:行者123 更新时间:2023-12-02 07:33:47 25 4
gpt4 key购买 nike

我有一些简单的 Powershell 代码,如果服务器已启动,它会 ping 服务器,然后禁用本地管理员帐户。我怎样才能将结果输出到日志文件,以便我记录我已禁用的内容。

这是我目前所拥有的

$computers = Get-ADComputer -filter {OperatingSystem -like "Windows Server*"} | 
ForEach ($computer in $computers) {
$rtn = Test-Connection -CN $computer -Count 1 -BufferSize 16 -Quiet
IF($rtn -match 'True') {
write-host -ForegroundColor green $computer | Disable-localUserAccount -ComputerName $computer -username Administrator
} ELSE {
Write-host -ForegroundColor red $computer
}
}

最佳答案

Write-Host 直接写入控制台。该输出无法重定向到文件。如果您想将输出重定向到文件,请将其替换为 Write-Output 并删除花哨的颜色。此外,我会将计算机列表传送到 ForEach-Object 循环中,这样您就可以直接将输出写入文件。而 Test-Connection 返回一个 bool 值,所以你可以直接在条件中使用它:

$computers | % {
if (Test-Connection -CN $_ -Count 1 -BufferSize 16 -Quiet) {
Write-Output "$_ online"
Disable-localUserAccount -ComputerName $_ -username Administrator
} else {
Write-Output "$_ offline"
}
} | Out-File 'C:\path\to\your.log'

关于从脚本到日志文件的 powershell 输出结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19103554/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com