Invoke-Command script block not generating output

十年热恋 提交于 2019-12-13 19:03:15

问题


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:


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.



来源:https://stackoverflow.com/questions/29370042/invoke-command-script-block-not-generating-output

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!