Avatar of Brad Sims
Brad Sims
Flag for United States of America asked on

Assistance with PowerShell Scripting - Windows Scheduled Tasks

I am trying to get PowerShell to run a Scheduled Task if it exists, or create a scheduled task if it doesn't.  I have verified the locations of the files and that the computer names are online and reachable (I have one here at my desk as a test).  The script looks like it runs, and I don't get any errors, but the task isn't created on the remote machine like it should be.  

Did I miss something simple?  Or is my code just wrong.  I am still trying to learn PowerShell, so either scenario is very possible.

$computers = Get-Content -Path C:\Users\****\Desktop\Computers.txt


$taskname = "McAfee Agent Update"
$taskdescription = "Update McAfee Agent Using Service Account"
$action = New-ScheduledTaskAction -Execute '\\share\McAfee.bat' `
  -Argument '-NoProfile -WindowStyle Hidden -command "& Restart-Service -displayname \"McUpdates\""'

foreach ($computer in $computers) {

$taskexists = Get-ScheduledTask | Where-Object {$_.TaskName -like $taskname }

if($taskexists) {

Start-ScheduledTask -TaskName $taskname

} else {


$ts = New-TimeSpan -Days 0 -Hours 0 -Minutes 1
$trigger =  New-ScheduledTaskTrigger -Once -At ((Get-Date) + $ts) 
$settings = New-ScheduledTaskSettingsSet -ExecutionTimeLimit (New-TimeSpan -Minutes 2) -RestartCount 3 -RestartInterval (New-TimeSpan -Minutes 1)


Register-ScheduledTask -Action $action -Trigger $trigger -TaskName $taskname -Description $taskdescription -Settings $settings -User "System"

}

}

Open in new window

PowershellWindows 10Windows OS

Avatar of undefined
Last Comment
Brad Sims

8/22/2022 - Mon
ASKER CERTIFIED SOLUTION
ITguy565

THIS SOLUTION ONLY AVAILABLE TO MEMBERS.
View this solution by signing up for a free trial.
Members can start a 7-Day free trial and enjoy unlimited access to the platform.
See Pricing Options
Start Free Trial
GET A PERSONALIZED SOLUTION
Ask your own question & get feedback from real experts
Find out why thousands trust the EE community with their toughest problems.
Brad Sims

ASKER
Connecting to remote server ******* failed with the following error message : The WinRM client cannot process the request because the server name cannot be resolved. For more information, see 
the about_Remote_Troubleshooting Help topic.
    + CategoryInfo          : OpenError: (*******:String) [], PSRemotingTransportException
    + FullyQualifiedErrorId : ComputerNotFound,PSSessionStateBroken

Open in new window


This gives me an error after I type in my credentials.  I tried username@domain and domain\username formats.  I also restarted the WinRM service on the remote machine.
Brad Sims

ASKER
$machine = $computer
[System.Net.Dns]::GetHostEntry($machine)

Open in new window


I verified DNS is working as well with the statement above.  It returned FQDN and IP addresses.
Michael B. Smith

Well, @ITGuy565 is accurate that your original code did not refer to any remote computers - only the local computer.

I would also use Invoke-Command, normally, to execute something on a remote computer.

But if that isn't working for you, use Test-WsMan to tell you why it isn't working.

However if Test-WsMan fails, you can also try psexec. That may work instead.
Experts Exchange has (a) saved my job multiple times, (b) saved me hours, days, and even weeks of work, and often (c) makes me look like a superhero! This place is MAGIC!
Walt Forbes
Brad Sims

ASKER
Thanks for the help.  Part of the error was due to a proxy setting.  If I would've looked further down the page I originally found the DNS Test Code I would've seen that as well.

https://stackoverflow.com/questions/20400599/getting-error-while-trying-to-invoke-a-powershell-command-on-a-remote-machine

I did have to move two lines down to the "else" statement, but it seems to be working now.  Thanks for the help!

$computers = Get-Content -Path C:\Users\****\Desktop\Computers.txt
$cred = Get-Credential
$taskname = "McAfee Agent Update"
$taskdescription = "Update McAfee Agent Using Service Account"



foreach ($computer in $computers) {
    invoke-command -computername $computer -Credential $cred -ScriptBlock {
        $action = New-ScheduledTaskAction -Execute '\\share\McAfee.bat' `
                -Argument '-NoProfile -WindowStyle Hidden -command "& Restart-Service -displayname \"McUpdates\""'
        $taskexists = Get-ScheduledTask | Where-Object {$_.TaskName -like $taskname }

        if($taskexists) {

        Start-ScheduledTask -TaskName $taskname

        } else {
            $taskname = "McAfee Agent Update"
            $taskdescription = "Update McAfee Agent Using Service Account"
            $ts = New-TimeSpan -Days 0 -Hours 0 -Minutes 1
            $trigger =  New-ScheduledTaskTrigger -Once -At ((Get-Date) + $ts) 
            $settings = New-ScheduledTaskSettingsSet -ExecutionTimeLimit (New-TimeSpan -Minutes 2) -RestartCount 3 -RestartInterval (New-TimeSpan -Minutes 1)
            Register-ScheduledTask -Action $action -Trigger $trigger -TaskName $taskname -Description $taskdescription -Settings $settings -User "System"

            }

    }
}

Open in new window