Invoke-Command script block not generating output

2019-07-26 19:31发布

I am trying to use a script block in a remote powershell session. This command is working and I get an output about the machine state:

$SecurePassword = $ParamPassword | ConvertTo-SecureString -AsPlainText -Force  
$cred = New-Object System.Management.Automation.PSCredential `
 -ArgumentList $UserName, $SecurePassword
$ParamDomain = 'mydomain'
$ParamHostname = "myhostname"

$fullhost =  "$ParamDomain"+"\"+"$ParamHostname"  

#Get-BrokerMachine No1
if ($ParamCommand -eq 'Get-BrokerMachine'){
$s = New-PSSession -computerName $desktopbroker -credential $cred
Invoke-Command -Session $s -ScriptBlock { param( $fullhost ) ;asnp citrix.* ; Get-BrokerMachine -machinename $fullhost  } -Args $fullhost
}

My second iteration of this, also using a scriptblock, is failing. The command Get-BrokerMachine is not executed and there is no output.

#Get-BrokerMachine No2
if ($ParamCommand -eq 'Get-BrokerMachine'){
$ScriptBlock = {
    asnp citrix.* ; Get-BrokerMachine -machinename $fullhost 
};
$s = New-PSSession -computerName $desktopbroker -credential $cred
Invoke-Command -Session $s -ScriptBlock $ScriptBlock 

}

Can someone explain what is wrong with the second script?

1条回答
时光不老,我们不散
2楼-- · 2019-07-26 20:27

The one important thing that is missing in your second script is that you are not passing $fullhost as an argument. When the scriptblock gets called on the remote system $fullhost would be $null.

Rough guess would be you need to do something like this:

#Get-BrokerMachine No2
if ($ParamCommand -eq 'Get-BrokerMachine'){
    $ScriptBlock = {
        param($host)
        asnp citrix.* ; Get-BrokerMachine -machinename $host 
    };
    $s = New-PSSession -computerName $desktopbroker -credential $cred
    Invoke-Command -Session $s -ScriptBlock $ScriptBlock -ArgumentList $fullhost
}

I changed the name of the variable inside the scriptblock to $host to remove the potential perceived ambiguity of the scopes.

查看更多
登录 后发表回答