SE HA-status of PowerCLI

Hello!

We are working on a reportingscript for our vCenter environment, and we would like to get the status of HA on our virtual machine.

We would like to get a True/False value in the csv file for each virtual machine.

I tried ".

HA = (Get-VM $_. ExtensionData . Time of execution . dasvmprotection . dasProtected) . dasProtected

"

But that did not work.

Someone knows how can I fix? Thank you.

Script:

Get-View -ViewType VirtualMachine | %{


PSObject -property @{ }


= $_. Name


= (Get-View $_. Summary . Time of execution . Host) . Name


= [system. String]::Join(",",($_. Storage . PerDatastoreUsage | %{Get-View $_. { Data store} | %{$_. Nom}))


= (Get-VM $_. Name | Select-Object -property ProvisionedSpaceGB(). ProvisionedSpaceGB #($_. Storage.PerDatastoreUsage | Measure - Object - property committed - sum). Sum


= (Get-VM $_. Name | Select-Object -property numCPU(). NumCpu


= (Get-VM $_. Name | Select-Object -property numvCPUs(). NumvCpus


= (Get-VM $_. ExtensionData . Time of execution . dasvmprotection . dasProtected) . dasProtected



| Csv export 'C:\Powershell\VM-report.csv' NoTypeInformation - -UseCulture


Try something like this

 &{Get-View -ViewType VirtualMachine | %{  New-Object PSObject -Property @{    Name = $_.Name    Host = Get-View $_.Summary.Runtime.Host | Select -ExpandProperty Name    Datastores = [system.String]::Join(",",($_.Storage.PerDatastoreUsage | %{Get-View $_.Datastore} | %{$_.Name}))    ProvisionedGB = [math]::Round( ($_.Storage.PerDatastoreUsage | Measure-Object -Property Committed -Sum | Select -ExpandProperty Sum)/1GB,1)    NumCPU = $_.Config.Hardware.NumCPU    NumvCPU = &{if($_.Config.Hardware.NumCoresPerSocket -gt 0){$_.Config.Hardware.NumCPU/$_.Config.Hardware.NumCoresPerSocket}}    DASStatus = &{if($_.Runtime.dasvmprotection.dasProtected){$_.Runtime.dasvmprotection.dasProtected}else{$false}}  }}} | Export-Csv "C:\Powershell\VM-report.csv" -NoTypeInformation -UseCulture

Note of course that you want to display under NumvCPU?

Tags: VMware

Similar Questions

  • PowerCLI 5.5 R2 and SRM - how to check the status of a Recovery Plan?

    I need to write a script that will examine the current status (apparently called a "RunMode") of a Recovery Plan, is the appropriate status (1 = Test, 3 = cleaning), then get a list of all virtual machines in a suitable specific folder and they will light up (wait 15 seconds between move them on to the next). There are reasons why the Recovery Plan cannot be responsible to do, so why do I need to write a script (the reasons have nothing to do with PowerCLI). And I have problems with the first part, determination of status.

    I have this (I won pretty well most of this pure and simple of the blog of Ken Werneburg. Thank you, Ken!) :

    $DR_vCenter = "xxxxxx".

    $SRM = connect-SrmServer-Server $DR_vCenter

    $SRM_API = $SRM. ExtensionData

    $PlanMoRef = $SRM_API. . Moref Recovery.ListPlans () [2]

    (My plan is #2, others their test plans. I checked this by looking at the name of each plan. And all the good things I want is in this 'moref,"apparently...)

    $HistoryMoRef = $SRM_API. Recovery.GetHistory ($PlanMoRef)

    (it's the history of the races of this plan. Here it is the story of the last race)

    $HistoryMoRef.GetRecoveryResult (1)


    Key: 68835

    Plan: VMware.VimAutomation.Srm.Views.SrmRecoveryPlan

    Name: Recovery_Plan_PHA

    Description:

    StartTime: 15/07/2014 11:03:15

    StopTime: 15/07/2014 11:09:29

    ExecutionTimeInSeconds: 374

    TotalPausedTimeInSeconds: 0

    ResultState: success

    RunMode: CleanupTest

    WarningCount: 0

    ErrorCount: 0

    SO: I understand how to get the history of the plan that I want, and it's more progress. The problem I have is that if the RunMode is a specific value (either "Test" or "Failover", then I need to launch other actions (power of virtual machines.) And I can't seem to do. «$HistoryMoRef.GetRecoveryResult (1).» RunMode"is empty return. I don't know how it is that the value of "CleanupTest".

    How can I query the RunMode, to see if it is a value which I am interested in?

    $HistoryMoRef.GetRecoveryResult (1) | GM


    TypeName: VMware.VimAutomation.Srm.Views.SrmRecoveryResult


    Name MemberType definition

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

    Equals method Boolean Equals (System.Object, obj)

    GetHashCode method int GetHashCode()

    Type of the method GetType GetType()

    String the ToString ToString() method

    Description property System.String Description {get; set ;}}

    ErrorCount property System.Int32 ErrorCount {get; set ;}}

    ExecutionTimeInSeconds property System.Int64 ExecutionTimeInSeconds {get; set ;}}

    Key key of System.Int32 property {get; set ;}}

    Property System.String name {get; set ;}}

    Plan of property VMware.VimAutomation.Srm.Views.SrmRecoveryPlan {get; set ;}}

    ResultState property VMware.VimAutomation.Srm.Views.SrmRecoveryResultResultState ResultState {get; set ;}}

    RunMode property VMware.VimAutomation.Srm.Views.SrmRecoveryPlanRecoveryMode RunMode {get; set ;}}

    StartTime property System.DateTime StartTime {get; set ;}}

    StopTime property System.DateTime StopTime {get; set ;}}

    TotalPausedTimeInSeconds property System.Int64 TotalPausedTimeInSeconds {get; set ;}}

    WarningCount property System.Int32 WarningCount {get; set ;}}

    Thank you

    Well, I managed to reproduce the problem and to understand what might happen.

    First the error "you can not call a method on an expression evaluated to null." seems to be linked to the "Write-Output"PG ="$pg" line. When I remove the error to go away (I'm not a person of PowerShell so don't know why this is the case).

    The second error (not not being filled seems to be linked to how they make the connection virtual computers SRM.) Specifically, you will need to establish the connection of VC and then do SRM login without specifying the SRM server, let that be determined by searching the SRM recorded with the VC you are connected to.

    The following code worked in my environment when it is connected to the protected so site full of hope that it will work for you as well:

    SE connect-VIServer-Server $protectedSiteVC - user $user-password $pass

    Connect-SrmServer-user $user-password $pass

    Write-Host "implementation details on Protection groups.

    Get-ProtectionGroup | {ForEach-Object

    $pg = $_

    Get-ProtectedVM - ProtectionGroup $pg} | {ForEach-Object

    #Write - Output 'do for each virtual computer.

    $output = "" | Select VmName, PgName

    $_. Vm.UpdateViewData)

    $output. VmName = $_. Vm.Name

    $output. PgName = $pg. GetInfo(). Name

    $output

    } | Format-Table @{Label = 'Name of the virtual computer'; Expression = {$_.} VmName}}, @{Label = 'Protection Group name'; Expression = {$_.} PgName}

    }

  • PowerCLI script optimasation vm name power STATE & vmware tool guest status.

    Get-vmhost-xxxxxxxxxxxx name | where {$_.powerstate - not power "off"} | Get - vm | % {get-view $_.id} | Select Name, @{Name = "ToolsVersion"; {Expression = {$_.config.tools.toolsVersion}}, @{Name = "ToolStatus"; Expression = {$_.} Guest.ToolsVersionStatus}}

    Output as shown below:-it does not show the STATUS of POWER & GUEST OS?

    Name ToolsVersion ToolStatus

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

    750 guestToolsNeedUpgrade 8300

    2229 8300 guestToolsNeedUpgrade

    2122 8300 guestToolsNeedUpgrade

    2816 9221 guestToolsCurrent

    Try like this

    Get-VMHost-xxxxxxxxxxxx name | where {$_.powerstate - not power "off"} |

    Get - VM |

    Select Name, PowerState,

    @{N = "GuestOS"; E={$_. ExtensionData.Guest.guestFullName}},

    @{Name = "ToolsVersion"; Expression = {$_.} ExtensionData.config.tools.toolsVersion}},

    @{Name = "ToolStatus"; Expression = {$_.} ExtensionData.Guest.ToolsVersionStatus}}

  • Unable to connect to vCD with PowerCLI

    Hi, can you help me with troubleshooting problem with connecting in vCD using PowerCLI.

    When I log in using my system administrator account

    Connect-CIServer vcdCell01 - User "username-password"pass"

    I get:

    Connect-CIServer: 11/30/2015 connect 12:19:21 AM-CIServer the

    Server returned "Unauthorized" with the status of the authorized 401 - no code.

    On line: 1 char: 1

    + Connect CIServer vcdCell01 - User "username-password 'pass' '.

    + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

    + CategoryInfo: NotSpecified: (:)) [connect-CIServer], CIException)

    + FullyQualifiedErrorId: Cloud_ConnectivityServiceImpl_ConnectCloudServer

    _ConnectError, VMware.VimAutomation.Cloud.Commands.cmdlets.ConnectCIServer

    I can connect to the Web user interface using the same system administrator account.

    The only way I can connect with PowerCLI is when I create the local account in one of the organizations and Add - Org to order

    Connect-CIServer vcdCell01-user "localuser" - password 'localpass' - 'org' Org

    Help, please.

    I used a few tricks of Python to connect to vCD. To connect as a system administrator, I had to use "Administrator@System" as the user.

    Maybe it will work for you if you use '-Org system?

  • Export data of material state via PowerCLI

    Hello

    I was just wondering if anyone have used PowerCLI for export the xml information of material status for a host to vCenter?

    I'm not really familiar with PowerShell and PowerCLI so I don't know if this is even possible but it would help us to completely automate some pilot third party verification.

    Thank you for your time and help

    Matt

    You can check the driver versions when you are connected to a host without the need for an XML export.

    I've attached a quick script and dirty to write versions of all the drivers in the console.

    Main points of the script:

    Connect-VIServer - Connect to vCenter

    Get-VMHost - lists associated Hosts the vCenter

    Get-EsxCli - access to the host ESX CLI

    $EsxCli.system.module.get("$DRIVER_NAME") - retrieves the VMKernel module (if the system knows about it) by name

    It's just the best way to show how to get information about the drivers. Basically you just connect the vCenter Server via PowerCLI, then connect to hosts one by one. When you are connected to a host, use EsxCli to obtain the driver information (module).

    I also forgot to add a line at the end of the script, so here it is: ' $DISCONNECT = Disconnect-VIServer $VCENTER_SERVER-force - confirm: $FALSE.

    -Ryan d. King

  • SE host HA status

    , We strive to use PowerCLI to get the host State HA.  We found some old posts from blog ( http://www.virtu-al.net/2009/10/28/powercli-listing-cluster-primary-ha-nodes/ and https://boerlowie.wordpress.com/2011/09/16/list-ha-runtime-states-with-powercli/ ) this reference by using Get-View and RetrieveDasAdvancedRuntimeInfo. From this, we should be able to obtain the status of host with the DasHostInfo.HostDasState property.  However, that is not filled for our clusters. We have a vCenter 5.1 and a vCenter 5.5, but we have no vCenters 4.x to check that we call the RetrieveDasAdvancedRuntimeInfo correctly.  Is it discouraged? Moved to a different location? We use only the fault of the API?

    PowerCLI C:\script > $view = get-views $cluster

    PowerCLI C:\script > $view.retrieveDasAdvancedruntimeInfo)

    SlotInfo: VMware.Vim.ClusterDasFailoverLevelAdvancedRuntimeIn

    foSlotInfo

    TotalSlots: 0

    UsedSlots: 8

    UnreservedSlots: 0

    TotalVms: 8

    TotalHosts: 1

    TotalGoodHosts: 0

    HostSlots:

    VmsRequiringMultipleSlots:

    DasHostInfo:

    HeartbeatDatastoreInfo:

    DynamicType:

    DynamicProperty:

    Yes, it is not used in vSphere 5.x more.

    You can now query the status of each host in the cluster, something like this

    $clusterName = "mycluster.

    Get-Cluster-name $clusterName | Get-VMHost |

    Select Name,@{N='State'; E={$_. ExtensionData.Runtime.DasHostState.State}}

  • Recovery of vSphere PowerCLI with alarms

    Hello

    Can you please help me write a PowerCLI script that would recover the vSphere alarms?

    I want the script to show only alarms last 24 hours only if not acknowledged or deleted.

    Example:

    Get-VIEvent - MaxSamples 10 | Select Fullformattedmessage # this command shows me the last 10 events

    Win01 from green to Red alarm # the script "MyAlarm" should show me this alarm

    win01 on esx1.company.pri in Lodz is turned off

    win01 on esx1.company.pri in Lodz stops

    Task: Stop virtual machine

    win01 on esx1.company.pri in Lodz is turned on

    Message on win01 on esx1.company.pri in Lodz: running VMware ESX in a virtua...

    starts win01 on the host esx1.company.pri in Lodz

    Task: Power on virtual machine

    Task: Initialize turn

    Alarm"monitor the health status"on changed from yellow to green data centers.

    Help, please.

    If the alarm was not recognized and authorized, it should still show.

    You can see these alarms with

    $dc = get - file - name of data centers

    $dc. ExtensionData.TriggeredAlarmState |

    Select @{N = 'Entity'; E = {Get-view-Id $_.} Entity | {{Select - ExpandProperty name}}.

    OverallStatus,

    @{N = "alarm"; E = {(Get-View-ID $_.)} Alarm). Info.Name}}

    -What are you looking for?

  • Addition of vShield Edge NAT rules from a CSV using PowerCLI

    I recently read Alan great post on adding NAT here rules: http://www.virtu-al.net/2014/07/24/working-vcd-edge-gateway-rules-powercli/

    I used it successfully for simple rules in a lab environment, but hundreds of rules I need to do in Production.

    Although I managed to hack together an Excel spreadsheet that concatenated all these parameters to create each order, I was wondering if there was a faster way to do it.

    My plan was to modify the script to Alan to import a CSV file, and then loop through each line and generate the XML file in a single pass.

    However, I am very rusty on my scripting skills, so I thought I would first ask if this has already been done by someone else.

    Anyone know if there is a way to update the rules of NAT edge vShield from a CSV file?

    Adam,

    I was an associate of the original request for this feature. Alan made us most of the way with a function to create a single rule, but as in your use case, we also had a lot of rules to build everything at once.

    Our solution was rather minor tweaks and the creation of 3 functions rather than 2.

    * Feature: New DNATRuleXML and new SNATRuleXML.  We have created these two functions to build the string XML (one for the SNAT) and one for the DNAT, their results are stored in a global variable.

    * Function: New-NATXMLExecute. It is a function execute to execute the creation of the great XML string created in the above functions.

    You should change/use power rule XML functions to interface with one worksheet, and then you should be far away. It will be useful.

    Example of code is below:

    ===============================================

    Function (new-NATXMLExecute

    $EdgeGateway,

    $NATXML,

    $FirewallEnable) {}

    Write-Host "' no nExecuting add it NAT function"-ForegroundColor Cyan

    Write-Host "-----------------------------------------------------"

    Write-Host "EdgeGateway: 't' t$ EdgeGateway '.

    #Write - Host "' tNATXML: 't' t$ NATXML '.

    Write-Host "activate the firewall?: 't' t$ FirewallEnable '.

    Write-Host "-----------------------------------------------------"

    $Edgeview = search clouds QueryType - EdgeGateway-name $EdgeGateway | Get-CIView

    If (! $Edgeview) {}

    Write-Warning 'edge Gateway with $Edgeview name not found. "

    Output

    }

    $URI = ($edgeview. Href + ' / action/configureServices ")

    $wc = new-Object System.Net.WebClient

    # Add Authorization headers

    $wc. Headers.Add ("x-vcloud-authorization", $Edgeview.Client.SessionKey)

    $wc. Headers.Add ("Content-Type", "application/vnd.vmware.admin.edgeGatewayServiceConfiguration+xml")

    $wc. Headers.Add ("Accept", "application / * + xml;") version = 5.1 ")

    $webclient = New-Object system.net.webclient

    $webclient. Headers.Add("x-vcloud-authorization",$Edgeview.Client.SessionKey)

    $webclient. Headers.Add ("accept", $EdgeView.Type + ";") version = 5.1 ")

    [xml] $EGWConfXML is $webclient. DownloadString($EdgeView.href)

    [xml] $OriginalXML = $EGWConfXML.EdgeGateway.Configuration.EdgegatewayServiceConfiguration.NatService.outerxml

    #Check if the firewall is turned on

    $FirewallStatus = $EGWConfXML.EdgeGateway.Configuration.EdgegatewayServiceConfiguration.FirewallService.IsEnabled

    Write-Host "active current firewall status: $FirewallStatus.» "This will be changed to: $FirewallEnable.

    LogWrite "active current firewall status: $FirewallStatus.» "This will be changed to: $FirewallEnable.

    If (($NATXML) - or ($FirewallStatus - not $FirewallEnable)) {}

    $GoXML = '

    http://www.VMware.com/vCloud/v1.5">

    "' + $FirewallEnable +"

    drop

    fake

    true'

    $OriginalXML.NatService.NatRule | {Foreach}

    $GoXML += $_. OuterXML

    }

    $GoXML += $NATXML

    $GoXML += '

    '

    $script: NATXMLExecute = $GoXML

    [byte []] $byteArray = [System.Text.Encoding]: ASCII. GetBytes ($GoXML)

    $UploadData = $wc. UploadData ("POST", $URI, $bytearray)

    $EdGWStatus = EdgeGatewayStatus - EdgeGateway $EdgeGateway

    Write-Host - NoNewline "Waiting for EdgeGateway configure...". »

    LogWrite "Waiting for EdgeGateway configure...". »

    While ($EdGWStatus - no "ready")

    {

    Start-Sleep - seconds 3

    Write-Host - NoNewline ". »

    $EdGWStatus = EdgeGatewayStatus - EdgeGateway $EdgeGateway

    If ($EdGWStatus - eq "Error") {}

    Write-Host "Error Has occurred...". Check the EdgeGateway"- ForegroundColor Red

    LogWrite "Error Has occurred...". Check the EdgeGateway.

    breaking

    }

    }

    Write-Host - NoNewline ".» EdgeGateway Ready.

    Write-Host "' nNAT complete building.»  ForegroundColor - Green

    LogWrite "NAT complete building."

    }

    else {}

    Write-Host "no change necessary." No changes have been made to the EdgeGateway"- ForegroundColor yellow

    LogWrite "no modification required...". No change was made.

    }

    }

    Function (new-DNATRuleXML

    $EdgeGateway,

    $ExternalNetwork,

    $OriginalIP,

    $OriginalPort,

    $TranslatedIP,

    $TranslatedPort,

    $Protocol) {}

    Write-Host "Building DNAT rule XML" - ForegroundColor yellow

    Write-Host "' tEdgeGateway: 't' t$ EdgeGateway '.

    Write-Host "' tExternalNetwork: ' t$ ExternalNetwork '.

    Write-Host "' tOriginal IP: 't' t$ OriginalIP '.

    Write-Host "' tOriginalPort: 't' t$ OriginalPort '.

    Write-Host "' tTranslatedIP: 't' t$ TranslatedIP '.

    Write-Host "' tTranslatedPort: 't' t$ TranslatedPort '.

    Write-Host "' tProtocol: 't' t$ Protocol.

    $Edgeview = search clouds QueryType - EdgeGateway-name $EdgeGateway | Get-CIView

    If (! $Edgeview) {}

    Write-Warning 'edge Gateway with $Edgeview name not found. "

    Output

    }

    $URI = ($edgeview. Href + ' / action/configureServices ")

    $wc = new-Object System.Net.WebClient

    # Add Authorization headers

    $wc. Headers.Add ("x-vcloud-authorization", $Edgeview.Client.SessionKey)

    $wc. Headers.Add ("Content-Type", "application/vnd.vmware.admin.edgeGatewayServiceConfiguration+xml")

    $wc. Headers.Add ("Accept", "application / * + xml;") version = 5.1 ")

    $webclient = New-Object system.net.webclient

    $webclient. Headers.Add("x-vcloud-authorization",$Edgeview.Client.SessionKey)

    $webclient. Headers.Add ("accept", $EdgeView.Type + ";") version = 5.1 ")

    [xml] $EGWConfXML is $webclient. DownloadString($EdgeView.href)

    [xml] $OriginalXML = $EGWConfXML.EdgeGateway.Configuration.EdgegatewayServiceConfiguration.NatService.outerxml

    If {($Script:NewID)}

    $Script: NewID += 1

    $NewID = $Script: NewID

    }

    else {}

    $NewID = [int]($OriginalXML.NatService.natrule |) Sort identifier. (Select the Id - Last 1) user.user + 1

    If {($NewID-éq. 1)}

    #If NoID was found, set the correct ID of departure

    $NewID = 65537

    }

    $Script: NewID = $NewID

    }

    $strXML = '

    DNAT

    true

    ' + $NewID + '

    "' + $OriginalIP +"

    "' + $OriginalPort +"

    "' + $TranslatedIP +"

    "' + $TranslatedPort +"

    ' + $Protocol + '

    '

    $script: DNATXML = $StrXML

    }

    Function (new-SNATRuleXML

    $EdgeGateway,

    $ExternalNetwork,

    $OriginalIP,

    $TranslatedIP

    ) {

    Write-Host "Building SNAT rule XML" - ForegroundColor yellow

    Write-Host "' tEdgeGateway: 't' t$ EdgeGateway '.

    Write-Host "' tExternalNetwork: ' t$ ExternalNetwork '.

    Write-Host "' tOriginal IP: 't' t$ OriginalIP '.

    Write-Host "' tTranslatedIP: 't' t$ TranslatedIP '.

    $Edgeview = search clouds QueryType - EdgeGateway-name $EdgeGateway | Get-CIView

    If (! $Edgeview) {}

    Write-Warning 'edge Gateway with $Edgeview name not found. "

    Output

    }

    $URI = ($edgeview. Href + ' / action/configureServices ")

    $wc = new-Object System.Net.WebClient

    # Add Authorization headers

    $wc. Headers.Add ("x-vcloud-authorization", $Edgeview.Client.SessionKey)

    $wc. Headers.Add ("Content-Type", "application/vnd.vmware.admin.edgeGatewayServiceConfiguration+xml")

    $wc. Headers.Add ("Accept", "application / * + xml;") version = 5.1 ")

    $webclient = New-Object system.net.webclient

    $webclient. Headers.Add("x-vcloud-authorization",$Edgeview.Client.SessionKey)

    $webclient. Headers.Add ("accept", $EdgeView.Type + ";") version = 5.1 ")

    [xml] $EGWConfXML is $webclient. DownloadString($EdgeView.href)

    [xml] $OriginalXML = $EGWConfXML.EdgeGateway.Configuration.EdgegatewayServiceConfiguration.NatService.outerxml

    If {($Script:NewID)}

    $Script: NewID += 1

    $NewID = $Script: NewID

    }

    else {}

    $NewID = [int]($OriginalXML.NatService.natrule |) Sort identifier. (Select the Id - Last 1) user.user + 1

    If {($NewID-éq. 1)}

    #If NoID was found, set the correct ID of departure

    $NewID = 65537

    }

    $Script: NewID = $NewID

    }

    $strXML = '

    SNAT

    true

    ' + $NewID + '

    "' + $OriginalIP +"

    "' + $TranslatedIP +"

    '

    $script: SNATXML = $StrXML

    }

    ===============================================

  • Status of the host

    Hello together,

    I have a strange question.

    I know that States to host returned by the powercli. Connected, disconnected and maintenance.

    But when I put a host in maintenance with 1 TB of RAM it takes a lot of time. Meanwhile our can´t script deploy new VM´s because the status is returned as connected.

    But when the host on the way to the Maintenance of the CLI output looks like this:

    VM-new operation is not valid due to the current state of the object.

    So the vCenter got another status...

    How can I get the status? Any idea?

    Thanks Rainer

    As far as I know, this is not a property you can recover.

    The CreateVM-task method receives an InvalidState of vSphere Server error.

    What might help is to query methods with disabilities.

    At the time wherever you set an ESXi host in maintenance mode, the method EnterMaintenanceMode_Task appears in the list.

    $esx = get-VMHost-name MyEsx

    if($ESX.) ExtensionData.DisabledMethod | where {$_ - match 'EnterMaintenanceMode_Task'}) {}

    "ESXi is in maintenance mode.

    }

    else {}

    "Go on, create a virtual machine.

    }

  • PowerCLI script to migrate virtual machines to the new vCenter environment

    Hello world

    in the next few weeks, we need about migrate 700 VMs (Windows/Linux) server to a new environment (new vCenter, new hosts, but VMs will remain on same data warehouses). VMs will be migrated not in one batch, but rather from time to time (which, however, can understand the need to migrate some 10s of virtual machines at the same time).

    Cluster names and folder structure will be identical to the old and the new vCenters. As host in the new vCenter names differ from those in the old vCenter, thought to provide a table of 'translation', which tells the script to save a given VM on host B (new vCenter) when having been registered in order to host a (old vCenter) and so on.

    I thought writing a PowerCLI script which, broadly speaking, can accomplish the following steps:

    • Connect to vCenterOld and vCenterNew
    • Correspondence table of host to read from a file (see step "register VM vCenterNew below)

    Then, in a loop:

    • Ask VM name
    • Get the settings of the virtual machine: Datastore/path, network/Portgroup, HA restart priority, host, folder, note
    • View the parameters and the VM name and request confirmation migrate the virtual machine
    • Turn off VM (closed OS gracefully, but force power off if power status is still not equal 'off' after a time given)
    • To unsubscribe from VM vCenterOld (removal of inventory)
    • Registry of the VM to the data store vCenterNew (assumptions: same folder as vCenterOld, host names are different, but for each source in vCenterOld host a host of destination in vCenterNew for you join the virtual machine to can be provided, that is, CSV)
    • The value of VM portgroup (same name as in vCenterOld)
    • Set VM HA restart priority
    • PowerON VM
    • Wait / check the VM (for example, ping) connectivity / continue immediately if the virtual machine is accessible or after a certain time if the virtual machine is still inaccessible
    • Confirm that the virtual machine has been migrated successfully, OR ask the user to check the connectivity of the virtual machine

    Now to my questions:

    • Is anyone know about an existing script that does something similar or contains parts that can be useful to compile a script like this?
    • How can vCenter two connections at the same time been managed within a PowerCLI script - or doesn't work at all and a connect/disconnect to/from the two vCenters must be completed for each virtual computer?

    Many thanks for any help.

    The following seems to work for me

    $vm = Get-VM -Name MyVM$nic = Get-NetworkAdapter -VM $vm $vdPG = $nic | select -ExpandProperty NetworkName
    
    Get-VDPortgroup -Name $vdPG
    
  • Need help PowerCLI with recovery ESXi host Asset Tag Info

    In the hope that someone, anyone, will be able to help me understand what I can do wrong and how to use PowerCLI to retrieve valid ESXi host Asset Tag information that appears in the tab material status vCenter. I have absolutely no problem of recovery of the serial numbers of host (sometimes referred to as Service Tags), manufacture, model, part, build, etc., but don't can't seem to be able to interrogate the current numbers of inventory number .

    None of the following attributes or property values currently returned the information required and which exists (see image below):

    Hardware.SystemInfo.OtherIdentifyingInfo [0]. IdentifierValue

    Hardware.SystemInfo.OtherIdentifyingInfo [1]. IdentifierValue

    Hardware.SystemInfo.OtherIdentifyingInfo [2]. IdentifierValue

    Hardware.SystemInfo.OtherIdentifyingInfo | where {$_.} IdentifierType.Key - eq "assettag" IdentifierValue})

    vCenter Server Hardware Status Tab - Asset Tag Info.png

    This is the script that I am running. I used PowerCLI Version 5.1:

    $VIServer = 'enter vCenter Server Name'


    # Add component snap kernel PowerCLI
    If (!) () Get-pssnapin-name VMware.VimAutomation.Core - erroraction silentlycontinue)) {}
    Add-pssnapin VMware.VimAutomation.Core
    }

    SE connect-VIServer $VIServer

    $HostReport = @)

    $VMH = get-VMHost | Get-View | % {}

    $Report = "" | Select the host name, Version, build, manufacture, model, series, Asset Tag

    $Report.Hostname = $_. Name

    $Report.version = $_. Config.Product.Version

    $Report.Build = $_. Config.Product.Build

    $Report.manufacture = $_. Hardware.SystemInfo.Vendor

    $Report.Model = $_. Hardware.SystemInfo.Model

    $Report.Serial = $_. Hardware.SystemInfo.OtherIdentifyingInfo [0]. IdentifierValue

    $ Tag = Report.Asset?

    $HostReport += $Report

    }

    $HostReport | Export-Csv «.\HostReport.csv"- NoTypeInformation

    Disconnect-VIServer-confirm: $false

    Ron thx.

    As far as I know, has nothing to do with PowerCLI, this is how vCenter gets this information, and how and where some HW providers make this information available.

    With the interface of the CIM, you can dump all the available information and then find exactly the tag died murdered.

    See what this returns

    import-module CimCmdlets$esxiHostname = "MyESXiServer"$HostUsername = "root"$CIOpt = New-CimSessionOption -SkipCACheck -SkipCNCheck -SkipRevocationCheck -Encoding Utf8 -UseSsl$Session = New-CimSession -Authentication Basic -Credential $HostUsername -ComputerName $esxiHostname -port 443 -SessionOption $CIOptGet-CimInstance -CimSession $Session -ClassName CIM_Chassis
    

    You will be asked the password root ESXi.

    On some of our older IBM HW, I get the following where we expect the identification sticker.

    But the information is there, just to another property.

    As we have already mentioned our VMworld session, exploring the CIM API.

    There is a lot of information in there

  • Pseudo-scrip easy, but PowerCLI, too?

    Hello. I'm testing a personal path MRU lun balancing script. I developed nickname - the following algorithm, and I would like to turn/convert it into PowerCLI. I would do exactly this:

    Hostname = 'Server1 '.


    Cont_Fix = 1
    Cont_MRU = 1


    For each host name logic unit number


    # Get the number of paths to the LUN:
    NumPaths = LeerNumPaths (Mon)


    # Paths to a LUN balancing sets:
    If (Lun = fixed) then
    # The technical set up a path for the fixed LUN and play
    # with a module to determine what path might be preferred in each case.
    Configure_Path - Lun lun = - PreferredPath = (Cont_Fix Mod NumPaths) + 1
    Cont_Fix = Cont_Fix + 1
    End If


    # Paths a MRU LUN balancing:
    If (LUN = MRU) then
    Path_To_Set_Enabled = (Cont_Mru Mod NumPaths) + 1


    (# The technical is: 1) deactivation of all paths, except one, who will take the active role:


    Path_Count = 1 To NumPaths Do
    If Path_Count <>Path_To_Set_Enabled then
    Disable_Path - Lun = Mon - Path = Path_Count
    End If
    End for


    (# 2) we turn again on the path to normalize the status of the LUN:


    Path_Count = 1 To NumPaths Do
    If Path_Count <>Path_To_Set_Enabled then
    Enable_Path - Lun = Mon - Path = Path_Count
    End If
    End for


    Cont_Mru = Cont_Mru + 1

    End If

    End for


    If Get_Paths_Disabled then
    Say 'Oops. You should review disabled access roads.
    On the other
    Say "Yes".
    End If

    It is possible to convert this power-CLI Pseudo-script?

    Thank you in advance!

    Kind regards.

    The following script PowerCLI is an implementation of your pseudocode. I didn't actually test the script. So it does not work the first time you run it.

    $HostName = "Server1"
    
    $Cont_Fix = 1
    $Cont_MRU = 1
    
    foreach ($LUN in (Get-VMHost -Name $HostName | Get-ScsiLun))
    {
        # Get the number of paths for the LUN:
        $ScsiLunPath = $LUN | Get-ScsiLunPath
        $NumPaths = $ScsiLunPath | Measure-Object | Select-Object -Property Count
    
        # Balancing paths for a Fixed LUN:
        If ($Lun.MultipathPolicy -eq "Fixed")
        {
            # The technique is configure a preferred path for the Fixed LUNs and playing
            # with a module to determining which path can be preferred in each case.
            Set-ScsiLun -ScsiLun $LUN -PreferredPath $ScsiLunPath[($Cont_Fix % $NumPaths)+1] -Confirm:$false
            $Cont_Fix += 1
        }
    
        # Balancing paths for a MRU LUN:
        If ($Lun.MultipathPolicy -eq "MostRecentlyUsed")
        {
            $Path_To_Set_Enabled = ($Cont_Mru % $NumPaths)+1
    
            # The technique is: 1) Disabling all paths except one, which will have taken the active role:
    
            for ($Path_Count=1;$Path_Count++;$Path_Count -le $NumPaths)
            {
                if ($Path_Count -ne $Path_To_Set_Enabled)
                {
                    Set-ScsiLunPath -Active $false Disable_Path -ScsiLunPath $ScsiLunPath[$Path_Count] -Confirm:$false
                }
            }
    
            # 2) We again turn on the paths to normalize the status of the LUN:
    
            for ($Path_Count=1;$Path_Count++;$PathCount -le $NumPaths)
            {
                if ($Path_Count -ne $Path_To_Set_Enabled)
                {
                    Set-ScsiLunPath -Active $true Disable_Path -ScsiLunPath $ScsiLunPath[$Path_Count] -Confirm:$false
                }
            }
    
            $Cont_Mru += 1
        }
    }
    
    if ($ScsiLun | Get-ScsiLunPath | Where-Object {$_.State -ne "Active"})
    {
        "Oups. You need to review disabled paths"
    }
    else
    {
        "Yeah."
    }
    
  • PowerCLi right size

    I've been modifing a script to do automated resizing right for me based on an imported csv file.

    I think I have the Script sorted, but it won't work, I get this error.

    Any help would be appreciated.

    Get-VM : Cannot validate argument on parameter 'Name'. The argument is null or
    empty. Supply an argument that is not null or empty and then try the command ag
    ain.
    At C:\Program Files (x86)\VMware\Infrastructure\vSphere PowerCLI\RightSize.ps1:
    66 char:28
    + foreach($vm in Get-VM -Name <<<<  ($vms."Virtual Machine")){
        + CategoryInfo          : InvalidData: (:) [Get-VM], ParameterBindingValid
       ationException
        + FullyQualifiedErrorId : ParameterArgumentValidationError,VMware.VimAutom
       ation.ViCore.Cmdlets.Commands.GetVM
    

    This is the code.

    function PowerOff-VM{
        param([string] $vm)
        
        Shutdown-VMGuest -VM (Get-VM $vm) -Confirm:$false | Out-Null
        Write-Host "Shutdown $vm"
        do {
            $status = (get-VM $vm).PowerState
        }until($status -eq "PoweredOff")
        return "OK"
    }
    
    function PowerOn-VM{
        param( [string] $vm)
        
        if($vm -eq ""){    Write-Host "Please enter a valild VM name"}
        
        if((Get-VM $vm).powerstate -eq "PoweredOn"){
            Write-Host "$vm is already powered on"}
        
        else{
            Start-VM -VM (Get-VM $vm) -Confirm:$false | Out-Null
            Write-Host "Starting $vm"
            do {
                $status = (Get-vm $vm | Get-View).Guest.ToolsRunningStatus
            }until($status -eq "guestToolsRunning")
            return "OK"
        }
    }
    
    
        
     $VIServer = Connect-VIServer "vcenter" 
    If ($VIServer.IsConnected -ne $true){
      Write-Host "error connecting to $vCenter" -ForegroundColor Red
      exit
    }
    $vms = Import-CSV .\vcopsreport.csv
    foreach($vm in Get-VM -Name ($vms."Virtual Machine")){
    
      if($vms."Recommended Memory" -or $vms."Recommended vCPU" -ne "0"){
        $poweroff = PowerOff-VM $vm.Name
        if($poweroff -eq "Ok"){
          Write-Host "PowerOff OK"
          if($vms."Recommended Memory" -ne "0"){
            
           
              
              $vm.Name | Set-VM -MemoryGB $vms."Recommended Memory" -Confirm:$False
              Write-Host "The new configured amount of memory is"(Get-VM $VM).MemoryGB
            
          }
    
          if($CPUCount -ne "0"){
            $vm.Name | Set-VM -NumCPU $vms."Recommended vCPU" -Confirm:$False
            Write-Host "The new configured number of vCPU's is"(Get-VM $VM).NumCPU
          }
    
          $poweron = PowerOn-VM $vm.Name
          if($poweron -eq "Ok"){
            Write-Host "PowerOn OK"}
        }
      }
    }
    
    Disconnect-VIServer -Confirm:$false
    

    Try to put in place the following foreach loop

    foreach($vm in Get-VM -Name ($vms | Select -ExpandProperty "Virtual Machine")){
    
    

    In this way, you will pass a table with the names for the Name parameter

  • PowerCLI VM Nics AdapterType report

    Hi all

    I'm doing a report for my virtual machines (400). I am management Vcenters 2 in bound mode and I've seen some mistakes in the process of creation of VM, e1000, Vmxnet2 maps on the server.

    I use Powershell/Powercli for two years from now, but I m facing some problems... If the servers have more than 1 NIC, my report just write 1 card...

    If you could help me, I assumed that my script is not correctly written...

    Here it is:

    # CREATE EXCEL #.
    $Excel = new-Object - Com Excel.Application
    $Excel.visible = $true
    $Excel = $Excel.Workbooks.Add (1)

    $VM = $Excel.WorkSheets.Item (1)
    $VM. Name = "Network Type".
    $VM. Cells.item(16777216) (1,1) = "name of the virtual machine.
    $VM. Cells.item(16777216) (1,2) = "name of the OS.
    $VM. Cells.item(16777216) (1,3) = 'IP address '.
    $VM. Cells.item(16777216) (1.4) = "VM HOST.
    $VM. Cells.item(16777216) (1.5) = 'VM STATUS '.
    $VM. Cells.item(16777216) (1.6) = "card Type".
    $VM. Cells.item(16777216) (1.7) = "name of the map.
    $VM. Cells.item(16777216) (1.8) = 'data center '.


    $WorkBook = $VM. UsedRange
    $WorkBook.Interior.ColorIndex = 0
    $WorkBook.Font.ColorIndex = 5
    $WorkBook.Font.Bold = $True
    $WorkBook.HorizontalAlignment =-4108
    $VmRange = $VM.range ("A1:Z500")
    $Vmrange.font.size = 8
    $intRow = 2

    # CONNECTION VCENTER #.
    SE connect-VIServer-Server $VCenter - user $User-Password $PWD - AllLinked: $true

    $VMs = get - VM | Sort-Object Name

    {Foreach ($ColVM to $VMs)
    #Gathering info on $ColVM
    $VMsItems = get-VM-name $ColVM | Select Name, VMHost, PowerState,
    @{N = "OSFullName"; E={($_ | (Get - VMGuest). OSFullName}},
    @{N = 'IP address'; E={($_ | (Get - VMGuest). Ip_address}},
    @{N = "AdapterType"; E={($_ | Get - NetworkAdapter). Type}},
    @{N = 'AdapterName'; E={($_ | Get - NetworkAdapter). Name}},
    @{N = 'Center'; E={($_ | Get - data center). Name}},
    @{N = "CardCount"; E={($_ | Get - NetworkAdapter). County}}

    #Filling Excel report
    Foreach ($Name in ($VMsItems.Name)) {}
    $VM. Cells.Item($intRow,1) = [STRING] $Name.Name
    $VM. Cells.Item($intRow,2) = [STRING] $Name.OSFullName
    $VM. Cells.Item($intRow,3) = [STRING] $Name.IPAddress
    $VM. Cells.Item($intRow,4) = [STRING] $Name.VMHost
    $VM. Cells.Item($intRow,5) = [STRING] $Name.PowerState
    If ($VMsItems.PowerState - eq "Receptor") {$VM. Cells.Item($intRow,5). Interior.ColorIndex = 4}
    Else {$VM. Cells.Item($intRow,5). Interior.ColorIndex = 3}
    $VM. Cells.Item($intRow,8) = [STRING] $Name.Datacenter
    $VM. Cells.Item($intRow,6) = [STRING] $Name.AdapterType
    If ($Name.AdapterType - eq 'Vmxnet3') {$VM. Cells.Item($intRow,6). Interior.ColorIndex = 4}
    Else {$VM. Cells.Item($intRow,6). Interior.ColorIndex = 3}
    $VM. Cells.Item($intRow,7) = [STRING] $Name.AdapterName
    {$IntRow ++}
    }
    $WorkBook.EntireColumn.AutoFit)
    $VM. Columns.Item (2). ColumnWidth = 25

    # BACKUP #.
    $Excel.SaveAs ($FILENAME)

    # DISCONNECT VCENTER & EXCEL KILL PROCESS.
    Disconnect-VIServer-Server *-confirm: $false - Force: $true
    #Stop - Process - processname excel

    Thank you

    Julien

    Also have you tried

    $VMs = get-ResourcePool-name "REC". Get - VM

    That should only give you virtual machines in this specific resourcepool.

    And you can have more than 1 name on Name - parameter

  • Report to the VMHosts list and status from VMotion NICS

    Hello

    I'm trying to set up a script reports the State of my VMotion NIC.

    I tried the following code, but it does not give me the status of the VMotion env:

    and-data center $DC | Get-VMHost | Get-VMHostNetworkAdapter | Export-CSV VMotionNics.csv - NoType

    Thanks in advance.

    Tony

    Hi Tony,.

    the following script PowerCLI returns network vMotion for guests datacenter $DC cards and records them in a file called VMotionNics.csv. I would like to know if you want other property included in the output.

    Get-DataCenter $DC |
    Get-VMHost |
    Get-VMHostNetworkAdapter |
    Where-Object {$_.GetType().Name -eq "HostVMKernelVirtualNicImpl" -and $_.VMotionEnabled} |
    Select-Object -Property VMHost,@{N="NIC";E={$_.Name}},Mac,DhcpEnabled,IP,SubNetMask,DeviceName |
    Export-CSV -Path VMotionNics.csv -NoTypeInformation -UseCulture
    

Maybe you are looking for