Daniel Gower
Daniel Gower

Reputation: 45

How to Output to a Log File

How can I output the screen results to a txt file when I run this code?

#removes disabled clinical or corp accounts from SGs in the I-Drive OU

$searchOU = "OU=I-Drive,OU=SAS,OU=Application Security Groups,OU=Groups,OU=Enterprise,DC=z,DC=x,DC=y"

Get-ADGroup -Filter 'GroupCategory -eq "Security"' -SearchBase $searchOU | ForEach-Object{ $group = $_
    Get-ADGroupMember -Identity $group | Get-ADUser | Where-Object {$_.Enabled -eq $false} | ForEach-Object{ $user = $_
        $uname = $user.Name
        $gname = $group.Name
        Write-Host "Removing $uname from $gname" -Foreground Yellow
        Remove-ADGroupMember -Identity $group -Member $user -Confirm:$false
    }
}

Upvotes: 1

Views: 553

Answers (2)

Satish Kumar Nadarajan
Satish Kumar Nadarajan

Reputation: 196

  • Store the value you'd like to log in a variable say $abc
  • Write to log file and keep appending $abc | Out-File -FilePath "C:\Somewhere\log.txt" -Append -Encoding UTF8

Refer - Log output of ForEach loop

Upvotes: 1

codewario
codewario

Reputation: 21488

Pipe the output of Get-ADGroup to Set-Content like so:

Get-ADGroup -Filter 'GroupCategory -eq "Security"' -SearchBase $searchOU | ForEach-Object{
  $group = $_
  Get-ADGroupMember -Identity $group | Get-ADUser | Where-Object { $_.Enabled -eq $false} | ForEach-Object{
      $user = $_
      $uname = $user.Name
      $gname = $group.Name
      Write-Host "Removing $uname from $gname" -Foreground Yellow
      Remove-ADGroupMember -Identity $group -Member $user -Confirm:$false
  }
} | Set-Content filename.txt

If you want any additional output (warnings, verbose, errors) change the last line a bit to redirect the other streams:

} *>&1 | Set-Content filename.txt

Alternatively, you can also use the built-in transcript logging to log everything to a file as well just call one of the following from within your script:

Start-Transcript

or if you want the log to go to a specific place:

Start-Transcript -Path "\Path\To\LogFile.log"

Note that transcript logging is more useful in scripts than during an interactive session.

Upvotes: 1

Related Questions