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

LVL 7
Brad Sims, CCNACyberSecurity AnalystAsked:
Who is Participating?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

x
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

ITguy565Commented:
Try something like this:

$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 {
            $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

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
Brad Sims, CCNACyberSecurity AnalystAuthor Commented:
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, CCNACyberSecurity AnalystAuthor Commented:
$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. SmithManaging ConsultantCommented:
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.
Brad Sims, CCNACyberSecurity AnalystAuthor Commented:
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

It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Powershell

From novice to tech pro — start learning today.