I am having trouble running a Powershell script as a scheduled task. The script remotely logs into two Hyper-V hosts, queries the replication status and emails the result back to me. The script works fine when I run it manually, either in Powershell ISE or by running the script directly, however when I run it as a scheduled task the task gets stuck in a running state and I never get a result.
I've checked my scheduled task setup is working correctly by replacing the script with one that simply writes a text file to a local folder so it's not that. I'm also logged in as the same user as the task runs under when I manually run the script so it's no that, what am I missing?
Here's my script:
$array = @("host1.domain.com", "host2.domain.com")
for ($i=0; $i -lt $array.length; $i++) {
$pass = cat C:\Scripts\Creds.txt | convertto-securestring
$mycred = new-object -typename System.Management.Automation.PSCredential -argumentlist "username",$pass
Invoke-Command -ComputerName $array[$i] -Credential $mycred -FilePath "C:\Scripts\Check_VMReplication.ps1"
}
The script calls another script in the same folder:
$hstname = Hostname
$Replication = Get-VMReplication
$MessageFail = $hstname + ' Replication Alert'
$SmtpServer = 'smtp.server.com'
hostname > C:\Scripts\iveremoted.txt
for ($i=0; $i -lt $Replication.length; $i++) {
$MessageBody = $hstname+ " has reported a replication status of " + $Replication.health[$i] + ' for server ' + $Replication.name[$i]
$FailMessageSubject = $Replication.name[$i] + " Replication Alert"
if ($Replication.health[$i] -ne 'Normal') {
send-mailmessage -to "mail@address.com>" -from 'frommail@address.com' -subject $MessageFail -body $MessageBody -smtpServer $SmtpServer
}
else{
send-mailmessage -to "mail@address.com" -from 'frommail@address.com' -subject 'Everything's OK' -body $MessageBody -smtpServer $SmtpServer
}
}
The script appears not to be able to log on because the iveremoted.txt file doesn't get written to the remote machine.
Any idea on what I might have missed?