Quantcast
Channel: VMware Communities : All Content - VMware PowerCLI
Viewing all 16717 articles
Browse latest View live

List VMs with Hostname Viewable

$
0
0

I'd like to get a list of all VMs in my environment.  Then for each one, I'd like to know if Vmware tools is installled and working, then I'd like to know if  the hostname inside the GuestOS is viewable, and if so what it is. 

How can I do this with PowerCLI?


Import Data with Extra Spaces

$
0
0

I'm running this script to input a csv and get VM data:

 

#Simplified version

$report = @()

Import-Csv -path c:\inputfile.csv -UseCulture | foreach{

$vmname = $_.vmname

$report += $vmname

}

$report | select vmname |  export-csv c:\outputfile.csv -notypeinformation -useculture

 

The problem is that if the input file has a column called VMName with no spaces AFTER the column title, everything works fine, but if there are spaces after the column title, it won't pick up the vmnames in the input file.  Every time someone different creates the input file, they may add an extra space before or after the column title, and mess up the results.

 

How can I make the import-csv statement read the column titles even if there are spaces before or after the column title?

 

Thanks!

A faster way to retrieve all the VM's associated to a portgroup

$
0
0

I have a script that I use to add/remove portgroup to a large set of VM's. I'm curious if there's a faster to get the list of VM's associated to a port group.

Right now, a command like this

Get-VM |Get-NetworkAdapter | Where {$_.NetworkName -eq "PortGroupName" } 

Takes a long time as it is running for each VM.

When I log into VSphere, I see all the VM's under a portgroup right away, is there a better way through PowerCLI?

PowerCLI "New-VDSwitch" command-let returns "Operation is not valid due to the current state of the object"

$
0
0
PS /home/morgany/Documents/vmware/powershell>> New-VDSwitch -Name VM_Operation_DvSwitch -Location $(Get-Datacenter)
New-VDSwitch : Operation is not valid due to the current state of the object.
At line:1 char:1
+ New-VDSwitch -Name VM_Operation_DvSwitch -Location $(Get-Datacenter)
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo          : NotSpecified: (:) [New-VDSwitch], InvalidOperationException
+ FullyQualifiedErrorId : System.InvalidOperationException,VMware.VimAutomation.Vds.Commands.Cmdlets.NewVDSwitch

 

 

However, the VDSwitch does get created

 

PS /home/morgany/Documents/vmware/powershell>> Get-VDSwitch                                                                               
Name                           NumPorts   Mtu        Version  Vendor
----                           --------   ---        -------  ------
VM_Operation_DvSwitch          0          1500       6.0.0    VMware, Inc.

How to make this powercli Script that i created to run faster than now?

$
0
0

Hello VMware and Powershell Experts,

 

I have created the below powercli script to collect inventory of our 5.5 and 6.0 VMware Hosts, VMs and Clusters. The problem with it is, it is terribly slow. It takes half a day to run this script fully to get details from 3 to 4 of our vCenters. Is there a way to make this script faster, by reducing the processing times, and cutting down unwanted loops, while maintaining the exact output, as requested by my manager? Input vcenter information at line 3 of the script. Thanks a million in advance!

 

$Username = Read-Host -Prompt "Please enter your Username:"

$Password = Read-Host -Prompt "Please enter your Password:"

$vcenters = @("vcenter1","vcenter2","vcenter3")

$GB = 1073718240

$HostReport = @()

$VMReport = @()

$ClusterReport = @()

ForEach ($vcenter in $vcenters)

{

Connect-VIServer $vcenter -User $Username -Password $Password

Get-VMHost |Get-View |%{ 

     $HReport = "" | select vCenter, Hostname, Cluster, Stand_Alone, State, ESX_Version, Build, Model, CPU_Sockets, CPU_Cores, RAM_GB, VM

     $HReport.vCenter = $vcenter

  $HReport.Hostname = $_.Name

  $HReport.Cluster = Get-Cluster -VMHost $_.Name

  $HReport.Stand_Alone = if($HReport.Cluster) {'No'} else {'Yes'}

     $HReport.State = $_.runtime.connectionState

     $HReport.ESX_Version =$_.config.product.version

     $HReport.Build =$_.config.product.build

     $HReport.Model =$_.hardware.systemInfo.model

     $HReport.CPU_Sockets =$_.hardware.CpuInfo.numCpuPackages

     $HReport.CPU_Cores =$_.hardware.CpuInfo.numCpuCores

     $HReport.RAM_GB = [math]::Round((($_.hardware.memorySize)/($GB)),1)

  $HReport.VM = $_.vm.Count

     $HostReport += $HReport

}

Get-VM |Get-View |%{

     $VReport = "" | select vCenter, VM, IP, OS, ESX_Host, Status

  $VReport.vCenter = $vcenter

  $VReport.VM = $_.config.Name

  $VReport.IP = $_.guest.ipaddress

  $VReport.OS = $_.config.guestFullName

  $VReport.ESX_Host = Get-VMHost -VM $_.config.Name

  $VReport.Status = $_.guest.guestState

  $VMReport += $VReport

}

Get-Cluster |Get-View |%{

  $esx = Get-VMHost -Location $_.Name

  $vm = Get-VM -Location $_.Name

  $CReport = "" | select vCenter, DC, Cluster, Number_of_Hosts, Number_of_VMs, Total_Processors, Total_Cores, Total_Physical_Memory_GB, Configured_Memory_GB, Available_Memory_GB, Total_CPU_Ghz, Configured_CPU_Ghz, Available_CPU_Ghz  

  $CReport.vCenter = $vcenter

  $CReport.DC = Get-Datacenter -Cluster $_.Name

  $CReport.Number_of_Hosts = $esx.Count

  $CReport.Number_of_VMs = $vm.Count

    $CReport.Cluster = $_.Name

    $CReport.Total_Processors = ($esx | measure -InputObject {$_.Extensiondata.Summary.Hardware.NumCpuPkgs} -Sum).Sum

    $CReport.Total_Cores = ($esx | measure -InputObject {$_.Extensiondata.Summary.Hardware.NumCpuCores} -Sum).Sum

    $CReport.Total_Physical_Memory_GB = [math]::Round((((($esx | Measure-Object -Property MemoryTotalMB -Sum).Sum)/1024)/($GB)),1)

    $CReport.Configured_Memory_GB = [math]::Round((((($esx | Measure-Object -Property MemoryUsageMB -Sum).Sum)/1024)/($GB)),1)

    $CReport.Available_Memory_GB = [math]::Round((((($esx | Measure-Object -InputObject {$_.MemoryTotalMB - $_.MemoryUsageMB} -Sum).Sum)/1024)/($GB)),1)

    $CReport.Total_CPU_Ghz = [math]::Round((((($esx | Measure-Object -Property CpuTotalMhz -Sum).Sum)/1024)/($GB)),1)

    $CReport.Configured_CPU_Ghz = [math]::Round((((($esx | Measure-Object -Property CpuUsageMhz -Sum).Sum)/1024)/($GB)),1)

    $CReport.Available_CPU_Ghz = [math]::Round((((($esx | Measure-Object -InputObject {$_.CpuTotalMhz - $_.CpuUsageMhz} -Sum).Sum)/1024)/($GB)),1)

  $ClusterReport += $CReport

  $esx = ""

  $vm = ""

  }

Disconnect-VIServer $vcenter -Confirm:$false

}

$HostReport | Export-Csv "C:\HostReport.csv" -NoTypeInformation

$VMReport | Export-Csv "C:\VMReport.csv" -NoTypeInformation

$ClusterReport | Export-Csv "C:\ClusterReport.csv" -NoTypeInformation

What OS do you run natively on your primary work machine?

powercli upgrade vm compatibility

$
0
0

any idea how to upgrade or schedule a VM compatibility upgrade?

 

I am running the VM on esxi 5.5 so need to go to v10

vSphere 6 host connections

$
0
0

Hi Everyone,

 

We are moving down the vSphere 6 road. We are building hosts and vCenter. I have a post install script that I run to do various post install things and when it runs the first thing it does is connect to the host via connect-viserver to the host in questions and connects via the root usename and password. This failed with an error: Permission to perform this operation was denied. Required privilege 'System.View' on managed object with id 'Folder-ha-folder-root'

 

I have never seen this before and I am not sure what to do?

 

thoughts?


script to execute DRS recommendations

$
0
0

Hello Community, I need your assistance

I upgraded to VC 6.5 U1G and it has a bug that when deploying a VM with DRS enabled it crashes vpxd

Until I upgrade to 6.0 U2 (need to wait for an app verification I need help with the following

 

I was forced to set DRS to manual, I am manually checking DRS recommendations every night and clicking run DRS if there are recommendations

Can someone help me scripting that? please.  JUst a script to execute recommendations

Error In Invoke-VMScript for pormote Domain controller

$
0
0

Hello

I create PowerCLI Script for Promote some DC

My Script is join with the error :

 

 

Invoke-VMScript : 02/11/2017 15:18:51 Invoke-VMScript Failed to authenticate with the guest operating system using the supplied credentials.

 

Au caractère Ligne:48 : 4

 

+    Invoke-VMScript -VM $NewName -GuestUser Administrateur -GuestPassw ...

 

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

 

    + CategoryInfo          : NotSpecified: (:) [Invoke-VMScript], InvalidGuestLogin

 

    + FullyQualifiedErrorId : Client20_VmGuestServiceImpl_GetProcessOutputInGuest_ViError,VMware.VimAutomation.ViCore.Cmdlets.Commands.InvokeVmScript

 

 

 

==> The Domain Controller is promote the VM is restarting soon...

 

 

 


I can't find the way for hide this error, my DC is promote successfully but i try the function Try catch but with no success.

 

Can you help me Please.

Get List of IP addresses for each VM

$
0
0

Hello,

I have a script to get Ip address and vm name:

 

Get-VM | Select Name,VMHost, @{N="IP Address";E={@($_.guest.IPAddress[0])}} |

Export-Csv -NoTypeInformation C:\Users\gemela\Desktop\machine_ip.csv

 

I get only one IP, I want to get also management ip and backup ip.

 

Is possible? ideally will be nice to get all IP for each machine.

 

Thanks

Find Orphaned Disks and Remove it

$
0
0

Hi,

I am looking for simple script to collect the Orphaned disks in my vcenter.

where my most of the VMs will have snapshots too, so need to get the report exclude of the snapshot disks.

i found from LuCD (Orphaned Files Revisited - LucD notes ) it is high advanced.

so please help me with simple method to collect the information.

Fetch ESXi license name & expiration date with PowerCLI

$
0
0

Hi folks,

 

i have a simple PowerShell inventory script for our ESXi servers and i would like to integrate two additional items:

 

License type (Standard, Enterprise, Enterprise Plus)

License expiration date.

 

Does anybody have an advice how to obtain this information with my script below?

 

The script looks like follows:

 

 

Get-View -ViewType HostSystem  |

select Name,

    @{N='Cluster';E={

      $parent = Get-View -Id $_.Parent -Property Name,Parent

      While ($parent -isnot [VMware.Vim.ClusterComputeResource] -and $parent.Parent){

        $parent = Get-View -Id $parent.Parent -Property Name,Parent

      }

      if($parent -is [VMware.Vim.ClusterComputeResource]){

        $parent.Name}}},

@{N="Type";E={$_.Hardware.SystemInfo.Vendor+ " " + $_.Hardware.SystemInfo.Model}},

@{N="BIOS version"; E={$_.Hardware.BiosInfo.BiosVersion}},

@{N="BIOS date";E={$_.Hardware.BiosInfo.releaseDate}},

@{N='Product';E={$_.Config.Product.FullName}},

@{N='Build';E={$_.Config.Product.Build}}| export-csv -NoTypeInformation -Path C:\temp\report_esxihosts.csv

 

The script's output so far is a CSV with hostname, cluster, hardware & BIOS information, product name and build number.

 

I am not sure whether i can retrieve the addional information with the "Get-View" pipe as well or if i have to build an entirely new loop statement for this ( i am a PowerShell newbie, i must admit).

 

 

Thanks in advance!

Karsten

Removing VMware Tool Modules via PowerCLI

$
0
0

I have an issue where we need to removed the Network Instrospection modules from serveral thousand VMs but keep File Instrospection module installed. I have found and adapted the following but I'm getting an error. 

 

Script:

Get-VM  | %{

  Mount-Tools -VM $_

  $DriveLetter = Get-WmiObject Win32_CDROMDrive -ComputerName $_.Name | 

    Where-Object {$_.VolumeName -match "VMware Tools"} | Select-Object -ExpandProperty Drive

  $ScriptText = "$DriveLetter\setup64.exe /S /v `"/qn REBOOT=R ADDLOCAL=ALL REMOVE=Hgfs,NetworkIntrospection`""

  Invoke-VMScript -VM $_ -ScriptText $ScriptText -ScriptType bat

}

 

Error:

Get-WmiObject : Access is denied. (Exception from HRESULT: 0x80070005 (E_ACCESSDENIED))

At line:3 char:18

+ ... $DriveLetter = Get-WmiObject Win32_CDROMDrive -ComputerName $_.Name |

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

    + CategoryInfo          : NotSpecified: (:) [Get-WmiObject], UnauthorizedAccessException

    + FullyQualifiedErrorId : System.UnauthorizedAccessException,Microsoft.PowerShell.Commands.GetWmiObjectCommand

 

Thanks for any insight is able to provide.

 

Get-VM LWVMUTSET007 | %{
  Mount-Tools -VM $_
  $DriveLetter = Get-WmiObject Win32_CDROMDrive -ComputerName $_.Name | 
    Where-Object {$_.VolumeName -match "VMware Tools"} | Select-Object -ExpandProperty Drive
  $ScriptText = "$DriveLetter\setup64.exe /S /v `"/qn REBOOT=R ADDLOCAL=ALL REMOVE=Hgfs,NetworkIntrospection`""
  Invoke-VMScript -VM $_ -ScriptText $ScriptText -ScriptType bat
}
 

'VMWare.VimAutomation.Core' is not installed on this computer

$
0
0

Hi,

I'm new in PowerCLI world and I need some help.

I'm getting the following error:

Add-PSSnapin : The Windows PowerShell snap-in 'VMWare.VimAutomation.Core' is not installed on this computer.

 

Usefull information from my computer:

PowerCLI Version:

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

   VMware PowerCLI 10.0.0 build 7895300

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

Component Versions

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

   VMware Cis Core PowerCLI Component PowerCLI Component 10.0 build 7893915

   VMware VimAutomation VICore Commands PowerCLI Component PowerCLI Component 10.0 build 7893909

 

$PSVersionTable:

Name                           Value

----                           -----

PSVersion                      5.1.16299.251

PSEdition                      Desktop

PSCompatibleVersions           {1.0, 2.0, 3.0, 4.0...}

BuildVersion                   10.0.16299.251

CLRVersion                     4.0.30319.42000

WSManStackVersion              3.0

PSRemotingProtocolVersion      2.3

SerializationVersion           1.1.0.1


Help getting cluster name for array / datastore

$
0
0

I borrowed this script from another thread, it was created by LucD.  I cannot get the following line to show me the cluster name for the datastore, I know I am missing something, I just don't know what.  The report shows every other row, but for cluster it is just blank.  The script is pulling all datastores that are less than 20% free space and converting that data to an HTML file for reporting purpose.

 

@{N='Cluster';E={$_.Cluster.Name}},

 

 

 

 

&{foreach($vcin$global:DefaultVIServers){

    Get-Datastore| ? {($_.name -like "LUN*" -or $_.Name -like "iSCSI*") -and ($_.Name -notlike "*LOG*)} |

    where {($_.FreeSpaceGB/$_.CapacityGB) -le0.20} |

    Select @{N='vCenter';E={$vc.Name}},

        @{N='Cluster';E={$_.cl.Name}},

        @{N='FreespaceGB';E={[math]::Round($_.FreespaceGB,2)}},

        @{N='Freespace%';E={[math]::Round($_.FreespaceGB/$_.CapacityGB*100,1)}}},

     

}

ConvertTo-HTML -CssUri "pathtomycssfile" | Out-File c:\temp\datastore_report.html

 

Appreciate the help!

Want to sort VMs in a folder older than 5 days then delete

$
0
0

Hi,

I have been looking at various posts for the last week or so and havent found exactly what I am looking for.

 

I plan on kicking off powershell jobs with Jenkins that will go to a specific folder in vSphere, find all VMs older than 5 days, power off the ones that are on, then delete them.

 

We have a testing group that has a habit of using jenkins to spin up vm's for testing builds, but then does not delete them.

 

I have found parts of code that look right  but i can't make it all come together.

 

Apologies to anyone this code came from...I copied a lot from various web sites and forums.

 

Here is the piece that will find VMs powered on in the time specifed

 

$Folder = get-folder powershell | get-vm

$vmOn = $Folder | where {$_.PowerState -eq "PoweredOn"}

$On = Get-VIEvent -Entity $vmOn -Start (Get-Date).AddDays(-700) -Finish (Get-Date).AddDays(-5) -MaxSamples ([int]::MaxValue) | where {$_ -is [VMware.Vim.VmPoweredOnEvent]} |

Group-Object -Property {$_.Vm.Name} | %{

  $lastPON = $_.Group | Sort-Object -Property CreatedTime -Descending | Select -First 1 | Select -ExpandProperty CreatedTime

  New-Object PSObject -Property @{

    VM = $_.Group[0].Vm.Name

    "Last Poweron"= $lastPON

    Duration = [math]::Round((New-TimeSpan -Start $lastPON | Select -ExpandProperty TotalDays))

  }

}

 

this does show me VMs that were powered on prior to 5 days ago...but when I try to do a "Stop-VM $On" it is not finding the VM name, but another part of the FullyFormatedMessage.

Duration Last Poweroff         VM

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

       0 5/29/2018 10:51:56 AM bb-003-new

       0 5/29/2018 10:51:56 AM bb-tf-demo-3

       0 5/29/2018 10:51:55 AM bb-new-000

       0 5/29/2018 10:51:56 AM BB-001

 

I would not be opposed to looking at it from a "Created Time" so anything created longer than 5 days ago would get turned off and then removed.

I have played with that as well and had the same issues.

 

CreatedTime          VM

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

5/22/2018 9:50:12 AM bb-003-new

1/4/2018 3:22:01 PM  bb-tf-demo-3

5/17/2018 11:05:1... BB-002

5/22/2018 9:52:23 AM bb-new-000

5/17/2018 11:04:4... BB-001

 

 

 

Any help would be appreciated.

Thanks in advance

Brian

Re: Want to sort VMs in a folder older than 5 days then delete

$
0
0

You are trying to stop the VM with an Event object, that doesn't work.

Try like this

 

# Get all powered on VMs in hash table

 

$vmTab= @{}

Get-Folder powershell |Get-VM|where {$_.PowerState-eq"PoweredOn"} |%{

   $vmTab.Add($_.Name,$_)

}


# Remove from the hash table the VM that were powered on in the last 5 days


Get-VIEvent-Entity $vmTab.Values-Start (Get-Date).AddDays(-5)-MaxSamples ([int]::MaxValue)|

   where {$_-is [VMware.Vim.VmPoweredOnEvent]} |

   Group-Object-Property {$_.Vm.Name} |%{

   $lastEvent=$_.Group| Sort-Object -Property CreatedTime -Descending | Select -First 1

   $vmTab.Remove($lastEvent.VM.Name)

  }


# Stop & remove the VMs remaining in the hash table


$vmTab.Values|%{

   $vm=Get-VM-Name $_.VM.Name

   Stop-VM-VM $vm-Confirm:$false

   Remove-VM-VM $vm-DeletePermanently -Confirm:$false

}

 

 

VM with multple Datastore

$
0
0

Hi

 

Need help to  script to list vm with multiple datastore

 

 

VM Name      Cluster Name     Datastore name

VM1              Cluster 1              Datastore 1, Datastore 2, Datastore 3

vm2               Cluster 1              Datastore 2, Datastore 1

 

 

Best Regards,

Deepak Koshal

Adding NICs to LACP uplinks

$
0
0

Hi All,

 

I am having a little trouble finding in the documentation how to add physical NICs to the the LACP port groups that i have configured on a DvS.

 

The DvS has 4 pNICs per host, vmnic0 and vmnic3 ($LagNIC1 + $LagNIC2 respectively) connect to the LAG uplinks and then vmnic1 and vmnic2 connect to standard uplinks..

 

I'm confident in adding standard uplinks, but there isn't much around about adding to LACP. I suspect the line I have below is incorrect for what I want to achieve, but the lack of resources doesn't seem to help improve it.

 

$DvSwitchName | Get-VDUplinkLacpPolicy | Set-VDUplinkTeamingPolicy -ActiveUplinkPort $LagNIC1,$LagNIC2 -Confirm:$false

 

 

If you have any further questions/clarification, please let me know.

 

Appreciate your assistance. Thank you.

 

- Keiran.

Viewing all 16717 articles
Browse latest View live


<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>