Author Posts

August 27, 2014 at 7:34 am

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 [i]$using:[/i] 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 [b]don't [/b]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?

August 27, 2014 at 7:36 am

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.

August 27, 2014 at 7:38 am

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.

August 27, 2014 at 7:58 am

Doh! I didn't think to [b]not[/b] 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!