Link to home
Start Free TrialLog in
Avatar of ndalmolin_13
ndalmolin_13Flag for United States of America

asked on

Scheduling a powershell script

Hello All,
I'm having trouble with using the Scheduled Tasks utility to run a powershell script.  I have read the posts here and on different sites and they all have indicated that I should:
1.  Create my powershell script.
2.  Create a batch file to run that script.
3.  Use the Scheduled Task utility to execute the batch file.

I have created my powershell script.  Here is the code:

$OS = "Windows*server*"
$Servers = Get-QADComputer -OSName $OS | foreach{$_.name} | Sort-Object
$results = ""
Foreach ($item in $Servers) {
$PingResult = Get-WmiObject -Query "Select * From win32_PingStatus Where address='$item'"
      If ($PingResult.statuscode -ne 0) {
      $results = $results+ "$item is not pingable and the server is off-line. `n"
      }
}

$mail = New-Object System.Net.Mail.MailMessage("Server@test.com","nick@test.com","Offline Servers", $results)
$smtp = New-Object System.Net.Mail.SmtpClient("mail01.summitlan.states", "25");
$smtp.Send($mail);

I have created a batch file to execute the powershell script.  Here is that code:
Powershell -command "$ {c:\sascripts\OfflineServers.ps1}"

When I run the powershell script from PowerShell or PowerGUI it works fine.  When try to schedule the script to run, I get a blank email.

I thought this could be a security issue so I set the executionpolicy to unrestricted and I verified that the scheduled task was configured to run with my credentials.

As always, and and all help is extremely appreciated.

Regards,
Nick
ASKER CERTIFIED SOLUTION
Avatar of tojo2k
tojo2k

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of ndalmolin_13

ASKER

Here was the problem:
Powershell -command "$ {c:\sascripts\OfflineServers.ps1}"

The "$" in the above line should have been a "&".

I made this change and it worked as expected.

still it didn't work out man, see the attached code.

G:\>Powershell -command "& {G:\Print.ps1}"
File G:\Print.ps1 cannot be loaded. The file G:\Print.ps1 is not digitally sign
ed. The script will not execute on the system. Please see "get-help about_signi
ng" for more details..
At line:1 char:16
+ & {G:\Print.ps1 <<<< }
    + CategoryInfo          : NotSpecified: (:) [], PSSecurityException
    + FullyQualifiedErrorId : RuntimeException

Open in new window