Invoke-command from CSV input

Hi All,

in my local desktop i am having a CSV file which contains server and VCserver.

using foreach loop, from local desktop connect server using invoke-command from there using connect-viserver connect VC (corresponds to Server row) and export the required VM output to CSV file.

 

Is this your requirement ? Did you try anything ? below help files will guide you.

Get-Help Import-Csv -Full
Get-Help ForEach-Object -Full

here is my sample script which i used

$cred = Get-Credential

$vclist = import-csv “c:\temp\vc.csv”

foreach ($j in $vclist){

Invoke-Command -ComputerName $j.jump -Credential $cred -ScriptBlock {

Import-Module VMware.VimAutomation.Core

Connect-VIServer -Server $j.vc -WarningAction SilentlyContinue

Get-VM } | Export-csv “C:\temp\test.csv” -append -NoTypeInformation

Disconnect-VIServer -Server $j.vc -Force -Confirm:$False

}

error message: Cannot validate argument on parameter ‘Server’. The argument is null or empty. Supply an argument that is not null or empty and then try the command again.

  • CategoryInfo : InvalidData: (:slight_smile: [Connect-VIServer], ParameterBindingValidationException

Looks like you’re missing the argumentlist option after your script block to pass in the j variable.

Your loop should look a little more like this:

$cred = Get-Credential

$vclist = import-csv "c:\temp\vc.csv"

$results = foreach ($j in $vclist){
    $jump = $j.jump
    $vc = $j.vc
    Write-Host ("Connecting to jump server {0} on vm {1}" -f $j.jump, $j.vc)
    Invoke-Command -ComputerName $jump -Credential $cred -ScriptBlock {

        Import-Module VMware.VimAutomation.Core
        Connect-VIServer -Server $using:vc -WarningAction SilentlyContinue
        Get-VM 
        Disconnect-VIServer -Server $using:vc -Force -Confirm:$False
    
    }
}

$results| Export-csv "C:\temp\test.csv" -NoTypeInformation

The error you are receiving indicates that you are trying to pass a NULL variable, basically nothing to server. Your running into a scope issue, see about_Remote_Variables