Brently
Brently

Reputation: 1

Powershell remote execution

PS newbie here...

I am attempting to run the following script:

Enter-PSSession -ComputerName hyper-V hostname
$VMList = Get-VM | Where-Object {$_.State -eq 'Running'}
    foreach ($VM in $VMList)
    {
     Write-Host $VM.VMName
    }
Exit-PSSession

When I execute the commands individually I get the anticipated data returned. For example I run the Enter-PSSession and it commects to the remote computer. I run the foreach loop and it returns the list of vms running on the host. Then I run the Exit-PSSession and it closes the connection.

However when I try to run the code all together I don't get the list of runnings vms.

Ideas...Suggestions?

Upvotes: 0

Views: 448

Answers (1)

Santiago Squarzon
Santiago Squarzon

Reputation: 60035

Enter-PSSession is meant for interactive shells, if you want to run a script unattended that will connect to a remote host, the cmdlet you should be using is Invoke-Command:

$VMList = Invoke-Command -ComputerName 'hyper-V hostname' -ScriptBlock {
    Get-VM | Where-Object {$_.State -eq 'Running'} |
        Select-Object -ExpandProperty VMName
}

Upvotes: 2

Related Questions