Question : Add logging to PowerShell script

I have the following PowerShell script.

# This is the loop through the CSV
Import-CSV "YourFile.csv" | ForEach-Object {
  # $_ represents the current line in the CSV. Elements are accessed by column name.
  Add-MailboxPermission $_.Email -User Admin -AccessRights FullAccess
  New-InboxRule -Name $_.ForwardingAddress  -Mailbox $_.Email -RedirectTo $_.ForwardingAddress -DeleteMessage $True
  Remove-MailboxPermission identity $_.Email -User Admin -AccessRights FullAccess -Confirm:$False
}

I am using this script to update the mailbox setting for around 20K users and need to add logging . For each of the following commands,  I want to write the output to a logfile. Add-MailboxPermission, New-InboxRule, Remove-MailboxPermission.

Can you help me with this? I am new to PowerShell.

Thanks.

Answer : Add logging to PowerShell script

try the following:

$logfile = "c:\temp\output.log"

Import-CSV "YourFile.csv" | ForEach-Object {
write-output $_.Email | out-file $logfile
write-output $_.ForwardingAddress  | out-file $logfile -append

  # $_ represents the current line in the CSV. Elements are accessed by column name.
write-output  "Add-MailboxPermission:"  | out-file $logfile -append

  Add-MailboxPermission $_.Email -User Admin -AccessRights FullAccess | Out-File $logfile -append

write-output  "New-InboxRule:"  | out-file $logfile -append

  New-InboxRule -Name $_.ForwardingAddress  -Mailbox $_.Email -RedirectTo $_.ForwardingAddress -DeleteMessage $True | Out-File $logfile -append

write-output  "Remove-MailboxPermission:"  | out-file $logfile -append

  Remove-MailboxPermission identity $_.Email -User Admin -AccessRights FullAccess -Confirm:$False | Out-File $logfile -append
}

Random Solutions  
 
programming4us programming4us