How to pass local variable to Invoke-Command's -ScriptBlock

后端 未结 2 1511
庸人自扰
庸人自扰 2020-12-20 06:26

I am trying to execute following PowerShell script from Server-2 against Server-1 (i.e. Remote server):

$DBServer = \'Server1\' 

Invoke-Command -ComputerNam         


        
2条回答
  •  北海茫月
    2020-12-20 07:27

    All,
    So, finally I figured it out how to pass local variable to -ScriptBlock while using with the Invoke-Commandagainst the remote server.

    Here is the code I used and it worked like a charm:

    Write-Host "Workflow command was: "$HaloSourceCommandLine
    
    Invoke-Command -ComputerName $DBServer -ScriptBlock {
    param ([string] $t1 = $HaloSourceCommandLine, [string] $t2 = $HaloSourceExecutableLocation)
    
        $status = Start-Process $t2 $t1 -Wait -PassThru
        $ExitCodeInfo = $status.ExitCode
            if ($ExitCodeInfo -ne 0) 
            { 
                Throw "The command exited with error code: $test2"
            }
            else
            {
                Write-host "Workflow executed successfully."    
            }
    } -ArgumentList $HaloSourceCommandLine,$HaloSourceExecutableLocation
    

    Hopefully this will help to others if they are having issue executing -ScriptBlock against remote server via Invoke-Command

    Thanks, HP

提交回复
热议问题