While my script runs both ways, when run through task scheduler, it messes up on an if-else statement. It’s supposed to send out an email when it detects that there are fewer than three objects in a directory and creates a pdf with letters for patients when there are three or more files in that directory (two folders and a variable amount of patient data files). The issue that I’m running into is that when it’s running through task scheduler, it creates a blank pdf when there’s no patient data instead of sending out the email. Has anyone else run into similar issues?
Here is how it’s set up in Task Scheduler:
- Runs whether user is logged in or not, at the highest privileges
- Runs weekly, on weekdays in the morning (a time when I’m usually logged on doing something)
- Start program details: C:WindowsSystem32WindowsPowerShellv1.0powershell.exe -file “PRG”
- Starts only when a network connection is available
- Special settings:
- Task can be run on demand
- Runs as soon as scheduled task is missed
- If it fails, restarts every 10 minutes
- Restarts up to 3 times
- Stops if running longer than 8 hours
- Can be force stopped
Code for testing:
cd 'A:Data SourcesProvider'
$Sources = dir
cd 'U:'
if($Sources.Length -lt 3) {
$mess = New-Object -comObject Outlook.Application
$mail = $mess.CreateItem(0)
$mail.Subject = "SAMPLE SUBJECT"
$mail.Body = "SAMPLE MESSAGE"
$mail.To = "[email protected]"
$mail.Send()
}
else {
## Simplified this part due to its length and function calls
& "DATA-CONVERSION-PRG.lnk"
Start-Sleep -Milliseconds 60000
$Data = Invoke-Sqlcmd -ServerInstance "SERVERNAME" -Database "DB" -TrustServerCertificate -Query "SELECT * FROM dbo.NegPap"
$Word = New-Object -ComObject Word.Application
$Word.Visible = $True
$Document = $Word.Documents.Add()
$Selection = $Word.Selection
for($i = 0; $i -lt $Data.Count; $i++) {
$Selection.TypeText(Data.Get($i))
}
$date = Get-Date -Format "MM-dd-yyyy"
$SavePath = "C:path" + $date + ".pdf"
$Document.ExportAsFixedFormat($SavePath,17,$false,0,0,0,0,0,$false,$false,0,$false,$true)
$Document.Close([Microsoft.Office.Interop.Word.WdSaveOptions]::wdDoNotSaveChanges)
$Word.Quit()
[System.Runtime.Interopservices.Marshal]::ReleaseComObject($Word)
Remove-Variable Word
$NewPath = "\fileservernew-path" + $date + ".pdf"
Move-Item -Path $SavePath -Destination $NewPath
}