SE connect-viserver to remain persistent through different functions.

For some reason, I can't get my Virtual Center connection to remain persistent so I can use in a different function when the connection is in service.  If I perform other tasks in the same function as the "Connect-VIServer" then they work without any problem.  I know I must be missing something.  Two examples of code base of what I'm trying to do.

Code

function connectVC

{

SE connect-VIServer $vcserver

}

function showdatacenters

{

Get-data center

}

Add-PSsnapin VMware.VimAutomation.Core

Initialize - VIToolkitEnvironment.ps1

$vcserver = read-host 'Target VirtualCenter Server'

connectVC

showdatacenters

Error

2009-05-07 15:51:22 Get-data center you are not currently connected to all servers. Sign in first using Connect-VIServer or one of his pseudonyms.

To: tank line: 7:15

+ Get-Data Center & lt; & lt; & lt; & lt;

Code

function connectVC

{

$objVC = to connect-VIServer $vcserver

}

function showdatacenters

{

$objVC.------

Get-data center

}

Add-PSsnapin VMware.VimAutomation.Core

Initialize - VIToolkitEnvironment.ps1

$vcserver = read-host 'Target VirtualCenter Server'

connectVC

showdatacenters

Error

The argument cannot be null or empty.

To: tank line: 7:24

+ $objVC.

Get-data center & lt; & lt; & lt; & lt;

Is the reason that you see, it is because of the "scope" in which you connect to the VC server.

While in a function (connectVC in your first example), local variables you create are lost when you leave the service.

There are 2 solutions

1) connect to the VC server outside of a function, the scope of the script called


function showdatacenters
{
Get-Datacenter
}

Add-PSsnapin VMware.VimAutomation.Core
Initialize-VIToolkitEnvironment.ps1

$vcserver = read-host "Target VirtualCenter Server"
Connect-VIServer $vcserver
showdatacenters

(2) store the ViServerImpl object (which is returned by the cmdlet Connect-VIServer) outside the function and pass on all other VITK cmdlets.


function connectVC
{
$global:vc = Connect-VIServer $vcserver
}
function showdatacenters
{
Get-Datacenter -Server $global:vc
}

Add-PSsnapin VMware.VimAutomation.Core
Initialize-VIToolkitEnvironment.ps1

$vcserver = read-host "Target VirtualCenter Server"
connectVC
showdatacenters

If you want to learn more about scope modifiers (like the World Cup, I used 2)), take a look at this.

Tags: VMware

Similar Questions

  • Wake on LAN (WOL) through different VLAN on SG-300-10

    Hello

    I try to get WOL working through different VLAN on a Switch SG-300-10 in layer 3 Mode.  To achieve this, I set up a UDP relay (GUI menu Configuration IP) for UDP Port 7 to 255.255.255.255 (this should inundate all interfaces with the package), however, does not work WOL in different VLANS.  When I am connected directly to the VLAN corresponding, WOL works fine in the same subnet.  Am I missing something here?

    All comments appreciated!

    Thank you very much!

    Hi Romeo,.

    A few minutes to try it on my SG300 - 10 p mode layer 3.

    My NAS unit is capable WOL and I thought I would use it in my test environment...

    Ran a basic test to check my sender of packet Magic from my PC "awakened" my NAS unit.

    As you would expect, on the same subnet, the magic packet WOL caused my NAS unit to power, no problem.

    But this isn't really the test, just a test database to check that my sender of the packet magic WOL and NAS was working well.

    The screenshot below shows WOL software I used on my PC.  Why use this software, no reason except that it was available for free. Also, I'm sure other WOL software out there for different platforms that work just as well or with more features.

    First of all, I see according to your question, you used relays UDP destination port 7, well it is the default setting on the UDP relay on my switch.

    I wonder why you used or stayed with destination UDP port 7, because the Magic packet mailers may use different destination UDP ports?

    I had to use wireshark to see the real destination UDP port that uses my sender of the magic packet WOL.

    Notice of capturing wireshark above, that my magic packet software uses the UDP port destination 9, NOT the default value that you can see on the switch. Ignore what wireshark labels this port.

    OK, I then created a VLAN that I named "VLAN2' with a = 2 VID on my SG300 - 10 p (SRW2008P-K9-NA)

    I added a 192.168.2.1/24 IP interface to VLAN2, which is a different network from the default VLAN.

    I then added three ports this VLAN newly created as a member untagged VLAN2.

    The default VLAN (VID = 1) an IP network 192.168.10.0/24.

    My NAS (WOL capable) unit has an IP address of 192.168.10.61.

    I plugged my PCt to the vlan 2 and statically assigned 192.168.2.2/24.  It is the PC that has the magic package software.

    I added a route static to my router WAN, just so that I could access the router my PC attached to the VLAN2 WAN.

    I tried the magic packet WOL software and will not turn on my NAS.  He expected that the magic packet broadcast would never jump over a limit of LAN in one VLAN different...

    Now, I tried to install a UDP relay so that the Magic Packet WOL "would be" the VLAN2 network interface VLAN1.

    So I configure and add to my SG300 UDP relay entry - 10 p.   See the screen capture below.

    I have to admit, I'm used to using UDP relay normally take a netbios broadcast and unicast to a server Ms.

    But check the screenshot below, I put the switch to send the UDP relay to the broadcast address of VLAN1 network... The magic packet Wakeup sent from my PC into 2 VLANS must have passed over the limit VLAN that my NAS unit woke.

    In order to check the destination port UDP to your WOL software using wireshark, and then create an appropriate UDP relay.

    Experiment and play with that, once you get your device WOL properly powereing successfully.

    Best regards, Dave

    If I answered your question, please rate the relevance of this response

  • 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
    
  • 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
    
  • 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.

  • SE connect-VIServer Powershell

    Hello

    When I am trying to connect through Connect-VIServer using powershell is as far as I get.

    Any ideas how I progress?

    Thank you

    You can safely ignore the warning of certificate.

    You are connected. Do a PowerCLI cmdlet to check

    Get-VM
    

    for example.

    ____________

    Blog: LucD notes

    Twitter: lucd22

  • 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]

  • All my iTunes music is on a disk hard Ext. connected to my home network through a router. Is it possible that devices that are part of my home network share iTunes can access the music on this disc hard Ext. without my laptop being on?

    All my iTunes music is on a disk hard Ext. connected to my home network through a router. Is it possible that devices that are part of my home network share iTunes can access the music on this disc hard Ext. without my laptop being on?

    Additional information: the laptop is what I used to install all the music, via iTunes, which is located on the external hard drive connected through home network router.

    Is it possible that devices that are part of my home network share iTunes can access the music on this disc hard Ext. without my laptop being on?

    Laughing out loud

  • I have XP pro and you want to connect to the MSN remote connection that uses my computer through my D Link router so that I can use the router to connect a tablet.

    How D link to connect to the modem connection

    I have XP pro and you want to connect to the remote connection MSN my computer use through my D Link router so that I can use the router to connect a tablet like Kindle Fire.

    Hi Bob,

    You can follow this link & check if it helps:

    How to set up and use remote connections in Windows XP?

    Internet Connection Wizard


    Reference:
    How to configure Internet access in Windows XP Professional?

    Hope the helps of information.

  • I get the following error when I am trying to connect to a network by using different credentials. 1219 system error has occurred.

    Multiple connections to a server or resource shared by the same user

    I get the following error when I am trying to connect to a network by using different credentials.

    1219 system error has occurred.

    Multiple connections to a server or a shared resource by the same user, using more than one user name, are not allowed. Disconnect all previous connections to the server or shared resource and try again...

    I don't want to use the IP address. and I don't want to delete all connections using the net use * / delete command.

    Kindly give me the solution as I am now frustrated with this issue.

    Kind regards

    Sajid

    Hello

    ·         Have you tried to access the files that were on Skydrive?

    ·         Did someone else uses your computer?

    From now on, I suggest you try the steps mentioned in the article below.

    Error message when you use user credentials to connect to a network from a Windows computer: "the specified network folder is currently mapped using a different username and password.

    http://support.Microsoft.com/kb/938120

    You can also ask your question in the forum of the Tech Net Windows Server using best.

    http://social.technet.Microsoft.com/forums/en/category/WindowsServer

    Hope this information is helpful and let me know if you need additional assistance.

  • y at - it a keyboard shortcut to navigate through different open files from adobe now that we have put tabs in place?

    y at - it a keyboard shortcut to navigate through different open files from adobe now that we have put tabs in place?

    CTRL + Tab to move forward or Ctrl + Shift + Tab to move backward in the tab order.

  • 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?

  • Need to export Connect-VIServer drive and import it for later use

    Hello

    I'm trying to export Connect-VIServer on disk:

    $vcenterconnection = Connect-VIServer-Server vcenterserver

    $vcenterconnection | Export-Clixml-path C:\TEMP\session.xml

    I want to import the session exported to a new process of powershell that it connects faster to vcentern later:

    $ImportedSession = import-Clixml-path C:\TEMP\session.xml

    I can access all the properties of the imported object that before exporting it.

    $NewConnection = Connect-VIServer-Session $ImportedSession - Server vcenterserver

    It does not work:

    SE connect-VIServer: 23.11.2015 14:11:17SE connect-VIServerUnable to connect to the VI server: https://vcenterserver/SDK using session Id: "vcenterserver"On line: 1 char: 22

    Is there a way to export a vCenter session on the disc to reuse it in a new process of powershell?

    Thank you

    For the parameter of the cmdlet Connect-ViServer Session you must pass a Guid.

    Your current logon, you can retrieve this Guid

    Global $: DefaultVIServer | Select - ExpandProperty SessionId

    Note that when you want to reconnect, that these sessions have a time-out value.

    They don't stay open forever (normally).

  • What is the minimum privileges that I return so he can make a Connect-VIServer and a Get - VM?

    Hi all

    I'm writing a small script to list all our virtual machines.

    I want installation service account just for that and I want to give to these minimum permissions accounts: just enough to Connect-VIServer and a Get - VM.

    Should what minimum privileges I give?

    How could I have figured this out on my own?

    Thanks in advance!

    -Chris


    Read only role applied to the vCenter node.

  • 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.

Maybe you are looking for

  • Aperture 3 hungry

    I have what I thought, it was an iMac Apple reasonable suitable for mounting all kinds of great images, take a look... iMac 27 inch end 2013, 3.2 GHz intel core i5, 16 GB 1600 MHz DDR3, NVIDIA GeForce GT755M 1024 MB, so why my editing in my opening v

  • Pane 'Inspect element' Firefox 17

    I like the component element inspect with dark background of 17 more than that in 18 with a white background.Where can I find the CSS of the component element Firefox 17 inspect?

  • Satellite A100 - 771 PSAA9E: ID ERR NOTINSTALLTVALZ MESSAGE appears

    Hallo, I've updated my system from xp to vista. The type of my computer laptop Satellite A100 - 771-PSAA9E ist.and when I install the update program, which either download the form from the website, to get out this message 'ID_ERR_NOTINSTALLTVALZ_MES

  • Suddenly, satellite L750 going to sleep - low battery?

    Hi guys,. I just want to ask why is that when I'm playing games like Assassins Creed/DMC.Sometimes my phone will shut down. The indicator lights on the left side were: A/c power: white Uni Power: Flashing Orange Battery: Flashing orange and And when

  • system information app is missing in el capitan

    "About this Mac" appears in the apple menu, but nothing happens when you click it. The application of the information system is not in the utility folder at all. Updated to El Capitan about a month previously and updated to version 10.11.3 today. How