简体   繁体   中英

Powershell invoke-command $input

I have a trouble.. Can someone help me? Here is my Code :

$A = '123'
$servers = 'computer1'
$Properties = [ordered]@{A = $A
                          servers = $servers     
                        }

$MyObject = New-Object -TypeName PSObject -Property $Properties

$MyObjec
...

$result = Invoke-Command -ComputerName Machine -UseSSL -InDisconnectedSession -ScriptBlock {
$MyObject.A
$MyObject.servers
$env:computername
}`
–InputObject $MyObjec -port 5986 -ConfigurationName myEndpoint -SessionOption @{OutputBufferingMode="Drop"} -Credential $credential | Receive-PSSession

$result

Question: Why the $result doesn't show anything about $MyObject ?

It only show $MyObjec (not in the invoke-command) and $env:computername (in the invoke-command)

How can I fix it?

PS this is really what I want to make, I want to get into multiple machine which in 6 different AD in the same time, but they should use different username, and I need $A in the remote machine to deal another thing.

$A = '123'
    $servers = 'computer1'
    $Properties = [ordered]@{A = $A
                              servers = $servers     
                            }

    $MyObject = New-Object -TypeName PSObject -Property $Properties

    $MyObjec
    ...

#Add
$servers@{'Machine1','Machine2','Machine3'}

Foreach ($servers in $servers) {

Star-Job {

$username = $servers+'account'

$password = $password

$credential = ....($username,$password)

    $result = Invoke-Command -ComputerName $servers -UseSSL -InDisconnectedSession -ScriptBlock {
    $MyObject.A
    $MyObject.servers
    $env:computername
    }`
    –InputObject $MyObjec -port 5986 -ConfigurationName myEndpoint -SessionOption @{OutputBufferingMode="Drop"} -Credential $credential | Receive-PSSession

    $result
}

}

I will try -Argument-List and param{} Beacase I try Start-Job with -Argument-List and $Using, there have an error. Thank u for your reply!

Because the part within -Scriptblock { ... } gets executed on the remote system and has therefore no access to the variables on the local system (different scope).

You can change that by passing the variables to the remote system using the -Argument-List parameter like this:

Invoke-Command -ComputerName Machine -ArgumentList $MyObject -ScriptBlock { 
    param($MyObject)

    $MyObject.A
}

Or use $using: to get access to the locally defined variables like that:

Invoke-Command -ComputerName Machine -ScriptBlock { 

    $using:MyObject.A
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM