2013-09-30 89 views
2

我有一个简单的PowerShell代码,如果服务器ping通,然后禁用本地管理员帐户。如何将结果输出到日志文件,以便记录我禁用的内容。PowerShell输出结果从脚本到日志文件

这是我迄今为止

$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 
    }  
} 
+0

你有什么试图写入到文件中试过吗?这样做对于PowerShell来说非常容易,并且有多种方式可以实现。 – alroc

+0

我试过这个,但不知道这是做到这一点的正确方法$ outputstring = $ computer $ outputstring -join“,”>> C:\ Create_Adminuser_computers.csv – user2785434

回答

6

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'