connection of several VC with connect-viserver

Based on another post, I tried to connect to multiple environments within a script.   My intention was to use

$vclist = 'server1', 'Server2', 'server' 3

{foreach ($vc to $vclist)

to connect-viserver $vc

}

So to do the job

{foreach ($connection in $defaultVIServers)

to connect-viserver-session $connection. SessionId

{do work}

}

It did not work. A command such as get - vm were withdrawing from all 3 of VC.   Should I rewrite with a connect then disconnect?

How to work with different connections is implemented a little differently.

First of all, make sure that you configure PowerCLI to work in multi mode.

$config = Get-PowerCLIConfiguration if($config.DefaultVIServerMode -eq "Single"){
    Set-PowerCLIConfiguration -DefaultVIServerMode Multiple}

Open your vCenter or ESX (i) connections

$vclist = "server1","server2","server3" foreach ($vc in $vclist){
     connect-viserver $vc}

When you run a cmdlet against a use specific vCenter the -Server setting

Get-VM -Server $defaultVIServers[0]

If you omit the - server parameter and you run in multi mode, the cmdlet will run against all connections.

The $defaultVIServers variable contains all the connections.

Tags: VMware

Similar Questions

  • How to operate with several connections open for VCs (Connect-VIServer).

    Hello:

    I know that I can open multiple connections to VCs (Connect-VIServer), but do not really understand how to run with them...

    How can I speak in VC1 for a single operation and after that VC2 to another without closing the connection in VC1?  I might need to do this several times in my script...

    Any help and simple example will be really appreciated.

    Thank you

    qwert

    The cmdlet Connect-VIServer of PowerCLU 4u1 leave takes supported several open sessions.

    The sessions are stored in a table called $defaultVIServers.

    If you need restore an open session, you can use the entry for this server in the array and then use the SessionId property to make this session open session / by default (which is stored in the variable $defaultVIServer).

    Something like that

    Connect-VIServer -Server VC1
    Connect-VIServer -Server VC2
    # Show the sessions and their properties
    $defaultVIServers | Select *
    
    # Open the session to VC1
    Connect-VIServer -Session $defaultVIServers[0].SessionId
    
    # Open the session to VC2
    Connect-VIServer -Session $defaultVIServers[1].SessionId
    
    # The open session
    $defaultVIServer
    
  • Extraction of SSL with initial Connect-VIServer

    Sorry if this has already been asked before, but I was not able to find it by searching online or in the forums.

    When you start a connection to another host of VC/ESXi, there is some information about x 509 certificate as shown below.

    * The X 509 chain could not be achieved with the root certificate.

    Certificate: [subject]

    C = US, CN = vcenter60 - 4.primp - industries.com

    [Issuer]

    O = vcenter60 - 4.primp - industries.com, C = US, DC = local, DC = vghetto, CN = CA

    [Number]

    00D9B9AE28CFD6CF4D

    [Not before]

    02/08/2015-09:19:14

    [Not After]

    02/02/2025 09:19:13

    [Imprint]

    B846B9F36C1D978CEDA0199294E61B4515656396

    I would like to enter the thumbprint SSL "B846B9F36C1D978CEDA0199294E61B4515656396"? I looked online and even asked some people but never able to retrieve this property by using PowerShell/PowerCLI. I can do it easily on one other system Windows with openssl (http://www.virtuallyghetto.com/2012/04/extracting-ssl-thumbprint-from-esxi.html), but wanted to see if there is a way without going through relays on the external packaging and since it is available as part of the connect-VIServer, I thought it must be possible but my PowerCLI-Fu isn't quite at the height as the others , figure so I ask. If it is indeed removable, which I guess it is then a bonus would be to format and so I have a variable that looks like: B8:46:B9:F3:6 C: 1 d: 97:8 C: ED: A0:19:92:94:E6:1 B: 45:15:65:63:96


    Luc Merci in advance

    Function Test-WebServerSSL {
    # Function original location: http://en-us.sysadmins.lv/Lists/Posts/Post.aspx?List=332991f0-bfed-4143-9eea-f521167d287c&ID=60
    [CmdletBinding()]
        param(
            [Parameter(Mandatory = $true, ValueFromPipeline = $true, Position = 0)]
            [string]$URL,
            [Parameter(Position = 1)]
            [ValidateRange(1,65535)]
            [int]$Port = 443,
            [Parameter(Position = 2)]
            [Net.WebProxy]$Proxy,
            [Parameter(Position = 3)]
            [int]$Timeout = 15000,
            [switch]$UseUserContext
        )
    Add-Type @"
    using System;
    using System.Net;
    using System.Security.Cryptography.X509Certificates;
    namespace PKI {
        namespace Web {
            public class WebSSL {
                public Uri OriginalURi;
                public Uri ReturnedURi;
                public X509Certificate2 Certificate;
                //public X500DistinguishedName Issuer;
                //public X500DistinguishedName Subject;
                public string Issuer;
                public string Subject;
                public string[] SubjectAlternativeNames;
                public bool CertificateIsValid;
                //public X509ChainStatus[] ErrorInformation;
                public string[] ErrorInformation;
                public HttpWebResponse Response;
            }
        }
    }
    "@
        $ConnectString = "https://$url`:$port"
        $WebRequest = [Net.WebRequest]::Create($ConnectString)
        $WebRequest.Proxy = $Proxy
        $WebRequest.Credentials = $null
        $WebRequest.Timeout = $Timeout
        $WebRequest.AllowAutoRedirect = $true
        [Net.ServicePointManager]::ServerCertificateValidationCallback = {$true}
        try {$Response = $WebRequest.GetResponse()}
        catch {}
        if ($WebRequest.ServicePoint.Certificate -ne $null) {
            $Cert = [Security.Cryptography.X509Certificates.X509Certificate2]$WebRequest.ServicePoint.Certificate.Handle
            try {$SAN = ($Cert.Extensions | Where-Object {$_.Oid.Value -eq "2.5.29.17"}).Format(0) -split ", "}
            catch {$SAN = $null}
            $chain = New-Object Security.Cryptography.X509Certificates.X509Chain -ArgumentList (!$UseUserContext)
            [void]$chain.ChainPolicy.ApplicationPolicy.Add("1.3.6.1.5.5.7.3.1")
            $Status = $chain.Build($Cert)
            New-Object PKI.Web.WebSSL -Property @{
                OriginalUri = $ConnectString;
                ReturnedUri = $Response.ResponseUri;
                Certificate = $WebRequest.ServicePoint.Certificate;
                Issuer = $WebRequest.ServicePoint.Certificate.Issuer;
                Subject = $WebRequest.ServicePoint.Certificate.Subject;
                SubjectAlternativeNames = $SAN;
                CertificateIsValid = $Status;
                Response = $Response;
                ErrorInformation = $chain.ChainStatus | ForEach-Object {$_.Status}
            }
            $chain.Reset()
            [Net.ServicePointManager]::ServerCertificateValidationCallback = $null
        } else {
            Write-Error $Error[0]
        }
    }
    
    $cert = Test-WebServerSSL MYVC
    $cert.Certificate.Thumbprint
    
  • to connect-viserver to several viservers @ simultaneously fails

    Hello

    because they are forced to leave related modes, we cannot use the connect-viserver - alllinked more...

    If google told me to use connect-viserver vc1, vc2

    You can check this, if you check the $global value: DefaulViServers

    In my case, there is only the vc2 listed, even if the connection to the two vcenters works very well...

    Version is 5.1 Release 1 PowerCLI

    Why?

    THX in advance

    Chakoe

    Add the parameter Scope

    Game-PowerCLIConfiguration - multiple DefaultVIServerMode - Scope Session

  • Ideas re: ' Connect-VIServer: could not connect using the requested protocol "failure

    I know, it's a matter of weakness, but I hit the wall on this one. I've even got desperate enough that bouncing private LuD, and I tried everything we discussed, but I'm still @ deadlocked.

    I developed and tested several scripts that I am finally ready to go with Prod.

    I get this error when I am trying to connect to Vcenter server or host of the cmndline of vitoolkit (and obviously in scripts).

    «Connect-VIServer: could not connect using the requested protocol.»

    I'm runing the vitoolkit FROM the server VCenter, so I wouldn't exepct the local to be a problem connection. I expect calls the ESX servers as questions) (we have several firewalls in the game). But even once, on-site I would not expect a problem.

    I checked my ports of VC and even more precisely called listener in the connect command, but it does not help.

    I tried to watch the ports through various lines of command, but I don't see anything.

    Any suggestions?

    Add - confirm: $false and it won't be quick.

    =====

    Carter Shanklin

    Read the PowerCLI Blog
    [Follow me on Twitter |] http://twitter.com/cshanklin]

  • start-work using connect-viserver hangs in powercli 6

    Hello

    Previously, I used powercli jobs to execute commands to invoke vmscript quite successfully in our workplaces 5.1 and 5.1.

    I'm testing these scripts in vSphere 6 with pwoercli 6 and am having some problems with the script.

    An example of the previous scripts that worked is as follows:

    -----------------------------------

    Start-job-name $vm - RunAs32 - PSVersion 2.0 - scriptblock {}

    Param ($vm, $vcentre, $GuestCred, $session)

    {if(!$Global:DefaultVIServer)})

    If (!) () Get-pssnapin. where {$_.name - eq "vmware.vimautomation.core"})) {}

    try {}

    Add-pssnapin VMware.VimAutomation.Core - ea 0. out-null

    } catch {}

    throw "could not load the PowerCLI snap."

    }

    }

    try {}

    to connect-viserver $vcentre - $session wa - 0 session | out-null

    } catch {}

    throw "Failed to connect to server VI".

    }

    }

    $TestGuestCredentials = "dir C:\. »

    Invoke-VMScript - VM $vm GuestCredential - $GuestCred - $TestGuestCredentials ScriptText

    } - ArgumentList, $vm, $GuestCred, $session, $vcentre | FT

    -----------------------------------

    Now, in powercli 6 using modules that I tried to edit the script as well as the previous option using addsnapin is no longer works:

    -----------------------------------

    Start-job-name $vm - RunAs32 - PSVersion 4.0 - scriptblock {}

    Param ($vm, $vcentre, $GuestCred, $session)

    If (!) () Get-Module-name VMware.VimAutomation.Core - ErrorAction SilentlyContinue)) {}

    . "C:\Program Files (x 86) \VMware\Infrastructure\vSphere.

    }

    try {}

    to connect-viserver $vcentre - $session wa - 0 session | out-null

    } catch {}

    throw "Failed to connect to server VI".

    }

    $TestGuestCredentials = "dir C:\. »


    Invoke-VMScript - VM $vm GuestCredential - $GuestCred - $TestGuestCredentials ScriptText

    } - ArgumentList, $vm, $GuestCred, $session, $vcentre | FT

    -----------------------------------

    Using the foregoing in powercli 6 that the work never ends.  It's as if the connect-viserver command causes a response that requires intervention and locks work.


    If I remove the connect-viserver in the work section - it full well.

    Any ideas would be very appreciated!

    See you soon

    Have you tried switching of warning messages via the cmdlet Set-PowerCLIConfiguration , the DisplayDeprecationWarnings parameter?

  • Connect-VIServer throws the invalid URI error in the Studio of Powershell, but is very well outdoors

    I don't know if it's a problem of Powershell Studio 2014 or PowerCLI, but other people have reported the "invalid URI: the hostname could not be parsed" error, so I'll start here.

    I have a PowerCLI 5.0.1 on Windows 7, Powershell v2.0 and Powershell Studio 2014.

    In my script, when I run the Connect-VIServer-Server $server command, the command fails and generates the invalid URI error.  However, when I run my script in the command window PowerCLI, the script works fine.

    I guess I have a problem of environment in the Studio of Powershell, but wonder what circumstances causes PowerCLI to raise this error.

    So far, I have not had much luck with Studio 2014 Powershell and PowerCLI, don't know if it's powershell v2.0 or something else.

    It looks like a Studio of Powershell environment problem.

    I have many ps1 files and use the point of supply to load the files ps1 in support which includes the call to connect-VIServer.  When I put the connect-VIServer in the file main ps1 I can connect to my vCenter, but when I put in the origin file, I cannot connect, nor can fact the fitting of test-work order.

    Thanks for the help.

  • Running PowerCLI connect VIServer & Get - VM as a single command

    I'm trying to create a script that allows me to generate the results of the cmdlet 'get - vm | Get-snapshot | format-list' in a file


    I use a piece of software that allows us to run scripts remotely via commands or PowerShell prompt


    How can I create a single command line that would Connect-VIServer vCenterServerName order & the get - vm | get-snapshot | format-list?


    I add variables via our software for the name of user and password & vmware server IP. These variables must be part of the command, for example:


    SE connect-VIServer-Server @VMwareHostIP @ - protocol https - User @Username @ - Password @Password @.


    Is there a way I could call the PowerCLI from the Windows command prompt?

    You can try below to the command prompt

    PowerShell "add-pssnapin vmware.vimautomation.core"; ' Connect-VIServer-Server @VMwareHostIP @ - protocol https - User @Username @ - Password @Password @; ' get - vm | Get-snapshot | format-list.

    Separate each command with ';' and best practices is Quote unquote each order.

  • Release of connect-viserver added to the variable - how?

    Hello

    I'm fighting to understand a problem with a script that I write to stop our vSphere & NetApp infrastructure when our UPS battery is critical.  If someone would be so kind help where I am wrong, I would be happy.

    A function connects to vSphere, gets the list of running virtual machines and this output to a csv file.  The value of the csv path is then returned by the function to be used elsewhere in the script.

    The problem I encounter is that the output of the command connect-viserver is being added for the returned data, and so I did not have a clean file to a csv file name more.  When I put a breakpoint on the return line, the value of $RunningVM_File is: C:\Path\To\file.txt, continue the script and check the value of the variable of the function is returned to, and the returned value has changed:

    Port of user name

    ----                           ----  ----

    vCenter_Server_NAme 443 domain\username

    C:\Path\To\file.txt

    Here is the function of the origin of the problem:

    function Initialize-vSphereShutdown

    {

    [CmdletBinding()]

    [OutputType ([string])]

    Param

    (

    # Description helps Param1

    [Parameter (mandatory = $true,)]

    ValueFromPipelineByPropertyName = $true,

    Position = 0)]

    $vSphereServer,

    # Description helps Param2

    [string]

    $BasePath,

    [pscredential]

    $Credential,

    # Description helps Param

    [Parameter]

    [string] $Logfile

    )

    Begin

    {

    #Connect to vSphere

    SE connect-VIServer-Server $vSphereServer - Credential $Credential # - User $UserName - Password $Password

    Write-debug ' connected to: $vSphereServer.

    Write-output ((Get-Date-f o) +"- connected to vCenter / ESXi host:"+ $vSphereServer) | out-file $Logfile - Append

    $RunningVM_File = ($BasePath) + "RunningVMs.txt".

    }

    Process of

    {

    If (Test-Path ($RunningVM_File)) {}

    Remove-Item ($RunningVM_File)

    }

    #Return list of all ESXi hosts managed by the host connected/vCenter

    $ESXiSRV = get-VMHost | Select-Object - ExpandProperty name | Out-string

    Write-debug ' following ESXi hosts are available:

    $ESXiSRV write-debug

    Write-output ((Get-Date-f o) +"- the following ESXi hosts are available:"+ $ESXiSRV) | out-file $Logfile - Append

    $vCenterESXiHost = get-VMHost - VM $vSphereServer | Select-Object - ExpandProperty name | Out-string

    $vCenterESXiHost | Out-file ($BasePath + "vCenterESXiHost.txt")

    Write-debug ' vCenter Server running on host: $vCenterESXiHost.

    Write-output ((Get-Date-f o) +' - vCenter Server running on the host: "+ $vCenterESXiHost) | out-file $Logfile - Append

    Debugging of Scripture "implementation of virtual machines.

    $RunningVM = get - VM | Where-Object {$_.} PowerState - eq "Receptor"} | SELECT name, folder, VApp

    $RunningVM | Export-Csv $RunningVM_File - NoTypeInformation

    Write-debug ' list of virtual computers running sauvΘs: $RunningVM_File.

    Write-output ((Get-Date-f o) +' "-list of virtual machines running recorded at:" + $RunningVM_File) | out-file $Logfile - Append

    }

    End

    {

    return $RunningVM_File

    }

    }

    Send the output of the cmdlet COnnect-VIServer into a black hole ;-)

    Like this

    SE connect-VIServer-Server $vSphereServer - Credential $Credential # - User $UserName - Password $Password | Out-Null

  • Scheduled - task to connect-VIServer

    Hi all. I wrote a script to do some work, but I have a problem with authentication. Whenever it runs it runs under my accout rather one specified in the script.

    I followed this guide so so before him below exported a copy of the password for the user account for the script (PSCredentials file)

    $PowerCLIUserAccount = "DOMAIN\User
    
    $PowerCLIUserPassword = Get-Content PSCredentials | ConvertTo-SecureString
    $PowerCLICredentials = New-Object System.Management.Automation.PsCredential $PowerCLIUserAccount, $PowerCLIUserPassword
    
    Connect-VIServer -Server VCSERVER
    

    At this point if it is connect but using my account rather than the script details?

    Try changing the last line to

    SE connect-VIServer-Server VCSERVER - Credential $PowerCLICredentials

  • Display object changed after Connect-VIServer format

    I found the custom effects Connect-VIserver the output format of the my objects. For example

    Without to connect-VIServer

    $output=@()
    
    $hosts = @("host1","host2")
    $VMs = @("VM1","VM2")
    
    $obj1 = New-Object psobject
    $obj1 | Add-Member NoteProperty -Name "Host" $hosts[0]
    $obj1 | Add-Member NoteProperty -Name "VM" $VMs[0]
    $obj2 = New-Object psobject
    $obj2 | Add-Member NoteProperty -Name "Host" $hosts[1]
    $obj2 | Add-Member NoteProperty -Name "VM" $VMs[1]
         
    $output = $output + ($obj1, $obj2)
    
    $output
    
    
    
    

    Gives this output:

    1.PNG

    With Connect-VIServer


    Connect-VIServer localhost -user $VCuser -password $VCpass
    
    $output=@()
    
    $hosts = @("host1","host2")
    $VMs = @("VM1","VM2")
    
    $obj1 = New-Object psobject
    $obj1 | Add-Member NoteProperty -Name "Host" $hosts[0]
    $obj1 | Add-Member NoteProperty -Name "VM" $VMs[0]
    $obj2 = New-Object psobject
    $obj2 | Add-Member NoteProperty -Name "Host" $hosts[1]
    $obj2 | Add-Member NoteProperty -Name "VM" $VMs[1]
         
    $output = $output + ($obj1, $obj2)
    
    $output
    
    

    Output looks like

    2.PNG

    I can not find a way to fix this and was hoping someone might have a solution?

    Thank you

    Luke

    The explanantion of what you see to understand how PowerShell handles objects in the output stream.

    We'll find a very good explanation in how PowerShell formatting and output REALLY works.

    In short:

    • Connect-VIServer returns a VMware.VimAutomation.ViCore.Impl.V1.VIServerImpl object
    • There is no registered view (.ps1xml files) for this type of object
    • so out-default leans on the number of properties on the object in the stream 1
    • Connect-VIServer more than 5 properties, so off-Format applies to the Format-List
    • and all the following objects in the output stream will be displayed with Format-List
  • Impossible to use Connect-VIServer

    I have two machines, both with PowerCLI 5.1 R1. A machine is Server 2003 with .net 2.0 SP1, 3.0 SP1 .net, and installed .net 4 (call this server1). The other machine is Windows 7 with .net installed 4.5 (let's call this Station1). The machine called server1 is also the vCenter Server

    When I opened PowerCLI to Workstation1, it connects fine. When I opened PowerCLI on server1, I get the following error:

    SE connect-VIServer: method not found: ' Int32 System.Threading.WaitHandle.WaitAny
    (System.Threading.WaitHandle [], Int32) ».
    On line: 1 char: 17
    + Connect-VIServer < < < < server1
    + CategoryInfo: NotSpecified: (:)) [connect-VIServer], MissingMet)
    hodException
    + FullyQualifiedErrorId: System.MissingMethodException, VMware.VimAutomati
    on.ViCore.Cmdlets.Commands.ConnectVIServer

    What Miss me?

    Thank you.

    Install this package, which includes .net Framework 3.5, but also the latest service packs for 2.0 and 3.0.

    http://www.Microsoft.com/en-US/Download/details.aspx?ID=25150

    Then I would also download .NET framework of Microsoft security patches, as there were some published since these versions of .NET have been released.

  • Unable to connect via Connect-VIServer

    Hi all!

    So here's the scoop:

    I have a service account that connects our different servers of vSphere for various applications / reporting tools we use.  I have a script to remove the ISO every night - the script works very well except a portion - connecting to the vSphere servers themselves.

    Even manually enter the connection string in PowerShell returns the same error:

    Cannot complete the connection due to an incorrect user name or password.

    I then go to vSphere and use the same credentials and I am able to connect.  I don't know where to go with that many other administrative applications use this account and all work fine.  Any thoughts?

    Thanks in advance for any idea on this issue!

    Sincere greetings,

    ALAN

    This seems to work for me, you can give it a try?

    Create the file with the password

    Read-Host -AsSecureString |
    ConvertFrom-SecureString |
    Out-File C:\VCS.txt
    

    Then to use the encrypted password

    $user = 'domain\uname' $cred = New-Object System.Management.Automation.PsCredential $user,(Get-Content c:\vcs.txt| ConvertTo-SecureString)
    
    Connect-VIServer vcenter -Credential $cred
    
  • Pass the credentials to connect-VIServer

    Hey all,.

    I give my first ride with scritping with powercli. I have currently a "script" that consists of two one liners, first line is to remove a virtual machine and the second line is to create a virtual machine from a clone. Nothing major, I know. I'm trying to understand, what I would plan this script as a Windows task and pass the credentials used to run the task to the cmdlet Connect-VIServer I at the beginning of the scipt.

    Someone help a rookie?

    TIA,

    -Jason

    Why not let the scheduled task run with this specific account?

    In this way, you don't have to pass the credentials to the cmdlet Connect-VIServer, it uses the credentials of the user under which the scheduled task runs.

    If the above is not possible and you must pass credentials, take a look at Hal functions PSCredential-export and import-PSCredential.

    These jacks allow the use the credentials in a secure manner that pass them in clear text in your script.

  • Connect-VIserver problem

    Since the update to version PowerCLI 4.0 U1 I had a problem with the connection to the vCenter server.  I can only make 1 connection to the server.  If I close the connection, it won't let me log in again.  Example below...

    $vcserver = "etvcenter01".

    $srv = connect-viserver-Server $vcserver

    WARNING: There are one or more problems with the server certificate:

    • The X 509 chain could not be achieved with the root certificate.

    • The certificate CN name does not match the passed value.

    $test = get - vm

    disconnect-viserver-Server $srv - confirm: $False

    $srv = connect-viserver-Server $vcserver

    SE connect-VIServer: Server etvcenter01 not connected.

    On line: 1 char: 24

    + $srv = to connect-viserver & lt; & lt; & lt; & lt; -Server $vcserver

    D:\Program Files\VMware\Infrastructure\vSphere PowerCLI & gt; Get - vm (just to check that I am not always connected)

    Get - VM: 2009-12-23 13:13:45 get-VM PowerCLI is not currently connected to a server. To create a new connection

    tion using Connect-VIServer.

    Online: 1 character: 6

    + get - vm & lt; & lt; & lt; & lt;

    I fear this is a known issue with PowerCLI 4u1, see Re: PowerCLI 4.0 U1 does not reconnect to the server.

    The ring road is to provide a user & password.

Maybe you are looking for