Pass a local variable to a remote session using the invoke-command

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

  • Author
    Posts
  • #18819
    Profile photo of H Man
    H Man
    Participant

    heres what i have so far

    $computername = 'PC-123456'
    $user = 'JDoe'
    
    
    
    Invoke-Command  $computername  {
    
    mkdir "\\flileShare\users$\$user\BKUP" -Force
    Move-item 'c:\MyFive9.reg' -Destination "\\flileShare\users$\$user\BKUP"
    } -Auth CredSSP -Cred $cred 
    
    

    im looking to pass $user within the Invoke-Command script block

  • #18824
    Profile photo of Aaron Jensen
    Aaron Jensen
    Participant

    You pass arguments via the ArgumentList parameter:

    $computername = 'PC-123456'
    $user = 'JDoe'
     
    Invoke-Command  $computername  {
    
    $user = $args[0]
    
    mkdir "\\flileShare\users$\$user\BKUP" -Force
    Move-item 'c:\MyFive9.reg' -Desination "\\flileShare\users$\$user\BKUP"
    } -Auth CredSSP -Cred $cred -ArgumentList $user
    

    The script block also allows you to specify named parameters, so you can do this, too:

    $computername = 'PC-123456'
    $user = 'JDoe'
     
     
     
    Invoke-Command  $computername  {
    param(
        $user
    )
    
    mkdir "\\flileShare\users$\$user\BKUP" -Force
    Move-item 'c:\MyFive9.reg' -Desination "\\flileShare\users$\$user\BKUP"
    } -Auth CredSSP -Cred $cred -ArgumentList $user
    
  • #18826
    Profile photo of Don Jones
    Don Jones
    Keymaster

    You can also use $using:user in v3+.

  • #18830
    Profile photo of H Man
    H Man
    Participant

    Thanks Guys got it working with your help

You must be logged in to reply to this topic.