Invoke-command from CSV input

Welcome Forums General PowerShell Q&A Invoke-command from CSV input

This topic contains 4 replies, has 4 voices, and was last updated by

 
Participant
3 months ago.

  • Author
    Posts
  • #108134
    B

    Participant
    Points: 0
    Rank: Member

    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.

     

  • #108137

    Participant
    Points: 536
    Helping Hand
    Rank: Major Contributor

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

    Get-Help Import-Csv -Full
    Get-Help ForEach-Object -Full
    
  • #108329
    B

    Participant
    Points: 0
    Rank: Member

    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: (:) [Connect-VIServer], ParameterBindingValidationException

  • #108332
    Max

    Participant
    Points: 2
    Rank: Member

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

  • #108334

    Participant
    Points: 159
    Helping Hand
    Rank: Participant

    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

The topic ‘Invoke-command from CSV input’ is closed to new replies.