I've intentionally written an error in the following:
Try
{
Start-Transcript -Path $Errorlog
#$TermRep = Import-Csv $TermReport
#$Donna = Import-Csv $HRReport
$TermRep = Import-Csv $Path\TestFileTerm2.csv
$Donna = Import-Csv $Path\TestFileDonna.csv
#Job to match users between CSVs
$Job = ForEach($i in $TermRep){
$TID = $($i.'Person ID')
ForEach($u in $Donna){
$DID = $($u.UserID)
If($TID -eq $DID){
"Move-ADObject -Identity $TID -TargetPath 'PATH' `r`n"
}
}
}
Stop-Transcript
#Send email of results or statement of no results
$smtpServer = "blah.net"
$msg = new-object Net.Mail.MailMessage
$smtp = new-object Net.Mail.SmtpClient($smtpServer)
$msg.From = $EmailFrom
$msg.To.Add($EmailTo)
#$msg.To.Add($EmailTo1)
#$msg.To.Add($EmailTo2)
$msg.Priority = "High"
If($Job -notlike ""){
$msg.Subject = "Open a ticket for Terminated Exception Users for Lit-hold changes."
$msg.Body = "Fix these users"
}
Else{
$msg.Subject = "Terminated Exception Users Script was run for Lit-holds"
$msg.Body = "No users need fixing."
}
$smtp.Send($msg)
}
Catch [system.exception]
{
#If the script errors (e.g. it cannot find one of the lists) send the following email.
$smtpServer = "blah.net"
$msg = new-object Net.Mail.MailMessage
$smtp = new-object Net.Mail.SmtpClient($smtpServer)
$msg.From = $EmailFrom
$msg.To.Add($EmailTo)
#$msg.To.Add($EmailTo1)
#$msg.To.Add($EmailTo2)
$msg.Priority = "High"
$msg.Subject = "Open a ticket for Terminated Exception Users - Script Failure"
$msg.Body = "Script error."
$smtp.Send($msg)
}
Specifically, $TermRep = Import-Csv $Path\TestFileTerm2.csv
does not exist. However, my transcript comes back as the following:
**********************
Windows PowerShell Transcript Start
Start time: 20151223165030
Username : DOMAIN\Username
Machine : WKSTNName (Microsoft Windows NT 6.1.7601 Service Pack 1)
**********************
Transcript started, output file is D:\DIR\LogFile2015-12-23.log
**********************
Windows PowerShell Transcript End
End time: 20151223165030
**********************
Can anyone tell me what I'm missing? Do I not understand how Start-Transcript
works?
If someone can help me, all I'm trying to do is get an error log to file.
Updated Attempts
I tried changing it to:
Try{$TermRep = Import-Csv $Path\TestFileTerm.csv -verbose -EA stop}
Catch { Write "$DateTime Error: Import-Csv: $_" >>$Errorlog}
If I set each command to try-catch
it prints the errors to the log file, but it no longer runs the error email function (2nd email) even when I try to import a non-existent CSV. Instead it runs the Else
on the first email, which means no users were found.
Further, Matt's suggestion, when tried prints the errors to the log file, but causes it to always send the error email (2nd email), even when there is no error:
try{
Start-Transcript -Path c:\temp\text.txt
$TermRep = Import-Csv $Path\TestFileTerm2.csv
} catch {
$Error[0]
}