【问题标题】:powershell output results from a script to log filepowershell 将脚本的结果输出到日志文件
【发布时间】:2017-09-22 23:18:21
【问题描述】:

我有一段简单的 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
  }     
}

【问题讨论】:

  • 您在尝试写入文件时尝试过什么?使用 PowerShell非常轻松做到这一点,并且有多种方法可以做到这一点。
  • 我已经尝试过了,但不确定这是正确的方法 $outputstring = $computer $outputstring -join "," >> C:\Create_Adminuser_computers.csv

标签: powershell powershell-2.0 powershell-3.0


【解决方案1】:

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

$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'

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-11-06
    • 2011-05-07
    • 1970-01-01
    • 1970-01-01
    • 2022-11-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多