Powershell script runs interactively with errors, but not automatically through Task Scheduler

K

kaplan71

Hello --

I had copied a Powershell script from one of our Windows 2012R2 servers, to a another one with the hope being it would run on the new system. When running the script from Task Scheduler, the Actions that are taken are shown below:

powershell.exe -ExecutionPolicy Bypass C:\Users\Administrator\Documents\Application_Configuration_Backup_info.ps1

The configuration of the script in Task Scheduler has it run by the local Administrator, whether the user account is logged on or not, and is set to run with the highest privileges. The script is designed to query the ScheduledTaskName of another job, and determine the value of the exit code, or result, of the last job. Once that is done, an email is sent out to the administrator notifying him of the result.

The anonymized version of the script in question is shown below:

$ScheduledTaskName = "Application Configuration Backup"
$Result = (schtasks /query /FO LIST /V /TN $ScheduledTaskName | findstr "Result")
$Result = $Result.substring(12)
$Code = $Result.trim()

If ($Code -eq 0) {
$User = "<email address>"
$Pass = ConvertTo-SecureString -String "myPassword" -AsPlainText -Force
$Cred = New-Object System.Management.Automation.PSCredential $User. $Pass


$From = "Info: Scheduled Task <ApplicationConfigurationBackup@server>"
$To = "Administrator <email address>"
$Subject = "Scheduled task 'Application Configuration Backup' completed on server"
$Body = "Error code: $Code"
$SMTPServer = "<smtp server>"
$SMTPPort = "25"

Send-MailMessage -From $From -to $To -Subject $Subject `
-Body $Body -SmtpServer $SmtpServer -port $SMTPPort -UseSsl `
-Credential $Cred
}

When running the script via Task Scheduler, The Last Run Result" shows the task is currently running with the code (0x41301). The task never completes, and I am forced to end the instance with the exit code being (0x41306)

When the script is run interactively, the following error message appears on-screen:

New-Object : A positional parameter cannot be found that accepts argument '.'.
At C:\Users\Administrator\Documents\MimVista_Configuration_Backup_info.ps1:9 char:10
+ $Cred = New-Object System.Management.Automation.PSCredential $User. $Pass
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidArgument: :)) [New-Object], ParameterBindingException
+ FullyQualifiedErrorId : PositionalParameterNotFound,Microsoft.PowerShell.Commands.NewObjectCommand

Also, when the script is run interactively the Windows PowerShell required window appears on-screen. The local administrator account and password are entered, and the script completes its operation.

What step(s) do I need to take in order to get the script to successfully run automatically?

Continue reading...
 
Back
Top Bottom