Expanding local vars on invoke-command

Welcome Forums General PowerShell Q&A Expanding local vars on invoke-command

This topic contains 3 replies, has 3 voices, and was last updated by

 
Participant
4 years, 3 months ago.

  • Author
    Posts
  • #18346

    Participant
    Points: 1
    Rank: Member

    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:

      If I put everything in $schtasks in double quotes the result is it echos it as a string (naturally).
      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.
      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.

    So what's the best way to approach this?

  • #18347

    Keymaster
    Points: 1,673
    Helping HandTeam Member
    Rank: Community Hero

    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

    Member
    Points: 0
    Rank: Member

    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

    Participant
    Points: 1
    Rank: Member

    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!

The topic ‘Expanding local vars on invoke-command’ is closed to new replies.