Expanding local vars on invoke-command

This topic contains 3 replies, has 3 voices, and was last updated by Profile photo of VirGnar VirGnar 2 years, 3 months ago.

  • Author
    Posts
  • #18346
    Profile photo of VirGnar
    VirGnar
    Participant

    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?

  • #18347
    Profile photo of Don Jones
    Don Jones
    Keymaster

    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.

  • #18348
    Profile photo of Dave Wyatt
    Dave Wyatt
    Moderator

    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.

  • #18349
    Profile photo of VirGnar
    VirGnar
    Participant

    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!

You must be logged in to reply to this topic.