2

I have a simple bit of Powershell code which pings servers if they are up and then disables the local admin account. How can I output the results to a log file so that I have record of what I have disabled.

This is what I have so far

$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
  }     
}
2
  • What have you tried in attempting to write out to a file? Doing so is very easy with PowerShell, and there are multiple ways to do it. Commented Sep 30, 2013 at 20:58
  • I have tried this but not sure that is the right way to do this $outputstring = $computer $outputstring -join "," >> C:\Create_Adminuser_computers.csv Commented Sep 30, 2013 at 21:22

1 Answer 1

7

Write-Host writes directly to the console. That output cannot be redirected to a file. Replace it Write-Output and drop the fancy coloring if you want to redirect the output to a file. Also, I'd pipe the computer list into a ForEach-Object loop, so you can directly write the output to a file. And Test-Connection returns a boolean value, so you can use it directly in the conditional:

$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'
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.