Expanding local vars on invoke-command

Still getting a few of the nuances with Powershell.

Here’s the culprit line in my script:

invoke-command -Session $session -ScriptBlock {schtasks /create /RU `"SYSTEM`" /TN $using:TaskName /TR `"net share $using:ShareName /DELETE`" /V1 /Z /SC ONCE /ST 01:00 /SD $using:Date}

It works, but as you can tell, it’s ugly. I planned on splitting it by putting the whole scriptblock in a local var (let’s call it $schtasks) and with $using: I would refer to it in the invoke-command’s scriptblock as such:

$schtasks = schtasks /create /RU `"SYSTEM`" /TN $using:TaskName /TR `"net share $using:ShareName /DELETE`" /V1 /Z /SC ONCE /ST 01:00 /SD $using:Date

invoke-command -Session $session -ScriptBlock {$schtasks}

However, if I do that, now I’m in a bit of a pickle:

[ul]If I put everything in $schtasks in double quotes the result is it echos it as a string (naturally).[/ul]
[ul]If I don’t put everything in $schtasks in double quotes, when it declares the variable it performs the whole command locally before I even have a chance to use it in the invoke-command.[/ul]
[ul]I suspect that if I could expand $schtasks properly, I need to make sure the variables inside of it ($using:ShareName, $using:Date) also expand properly.[/ul]

So what’s the best way to approach this?

Have you defined $schtasks as a script block, rather than a string?

$schtasks = { do-stuff-here }

That’s the correct way to delimit a script block, which s what -ScriptBlock takes for Invoke-Command.

Try this:

$schtasks = { schtasks /create /RU "SYSTEM" /TN $using:TaskName /TR "net share $using:ShareName /DELETE" /V1 /Z /SC ONCE /ST 01:00 /SD $using:Date }
invoke-command -Session $session -ScriptBlock $schtasks

This way, $schtasks is still a ScriptBlock literal and can be passed directly to the Invoke-Command cmdlet. (No extra curly braces needed in the call to Invoke-Command.) You also shouldn’t need to escape the double quotation marks within the script block, so I removed the backticks there.

Doh! I didn’t think to not include the brackets in the invoke command and only keep them on the declared var. Having them doubled up like that tripped it up. It’s always those little things that slip past me. Thanks!