SOLVED

Create new-scheduletaskaction and execute powershell command within a variable

Frequent Contributor

Hi,
I've developing some scripts to automate some tasks, like managing Windows Updates by using the PSWindowsUpdate module.

Now I'm at the stage where I got a variable with the update I need to do, like for example:

$UpdateString = "Get-WindowsUpdate -MicrosoftUpdate -Verbose -Install -AcceptAll -ScheduleReboot 'date' -KBArticleID $KBToInstall | Out-File '\\fileshare\WindowsUpdateLogs\$(get-date -f dd-MM-yyyy)-WindowsUpdateInstall.log' -Append -Force"

 

Now I need to create a scheduled task to run this command. 

I've tested this code: 

$UpdateString = "Get-WindowsUpdate -MicrosoftUpdate -Verbose -Install -AcceptAll -ScheduleReboot 'date' -KBArticleID $KBToInstall | Out-File '\\fileshare\WindowsUpdateLogs\$(get-date -f dd-MM-yyyy)-WindowsUpdateInstall.log' -Append -Force"
powershell.exe $UpdateString

And runs well. But what I need is this:

$taskAction = New-ScheduledTaskAction -Execute 'powershell.exe $UpdateString'
Register-ScheduledTask -TaskName "name" -Action $taskAction -RunLevel Highest -User "System"
Start-ScheduledTask -TaskName "name"

But this way the $UpdateString variable will not work within the schedule task.
Is there a way to convert the string to the code itself so it will run when the task starts?


Thanks

2 Replies
best response confirmed by dmarquesgn (Frequent Contributor)
Solution

You need to specify it as argument, so :
$taskAction = New-ScheduledTaskAction -Execute 'C:\Windows\system32\WindowsPowerShell\v1.0\powershell.exe' -Argument $UpdateString'

Ok, just tried that and it worked.
Thanks