Quantcast
Channel: VMware Communities : Document List - vSphere PowerCLI
Viewing all 379 articles
Browse latest View live

PowerAlarm Manager


Getting PID of running Virtual Machines from a list of servers

$
0
0
#Powershell and plink from Putty
#Getting PID of running Virtual Machines from a list of servers
#You shall supply a password for root as a parameter to the script
param($password = $(throw 'You shall supply a password for root'))
#List of servers
$servers = "esx01","esx02","esx03","esx04"
$data = @()
$account="root"
$regexp ='^root +(?<pid>[1234567890]+).*[/]+(?<machine>.*)[.]vmx$'

for ($i=0;$i -lt $servers.Length; $i++) {
$data += new-Object psobject
$data[$i] | add-Member -membertype noteproperty -name server -value $servers[$i]
$t1=$account + "@" + $servers[$i] + ".avisen.dk"
$t2=.\plink -pw $password $t1 "ps auxfw | grep vmkload_app | grep vmx$"
foreach ($f in $t2) {
$f -match $regexp > $null
$data[$i] | add-Member -membertype noteproperty -name $matches.machine -value $matches.pid
}
}
$data

Snapshot Email Reminder

$
0
0

 

Fed up of chasing those people who constantly create snapshots and leave them hanging around for weeks or even months on end ?

 

You no longer have to do the chasing, just use the following script to automatically find the offending snapshot, find the person who created it, get their email address from AD and send them an email reminding them of their mortal sin.

 

A few requirements:

 

  • The accounts must have the E-Mail field filled outin AD

  • The account you run the script as must have read permissions to AD (Any member of the domain should have this)

  • You need to fill in the smtp server address, VI Server name and the from address at the top of this script

 

The script is set to remind of anything over 2 weeks old but this can easily be amended

 

 

 

More information is available here: http://www.virtu-al.net/2009/06/22/powercli-snapreminder/

 

 

Folder Name Mismatch

$
0
0

 

Isn’t it annoying when you are looking for a VM on your datastore and you cant find it because the folder name is not the same as the VM,

use the below script and you will never have that problem again.

 

This script will compare the name of the VM to the folder it is stored in, any mismatches will be output.

 

I know a regex expert could probably do this better, let me know if you are one 

 

Sample Output:

 

 

 

VM

Path

New VM 1

storage1 New VM

ABCDEV01

storage1 Dev Test

MicroDS

SAN11 New VM

VM127

SAN11 Windows 2003 Server

 

For more information visit: http://www.virtu-al.net/2009/06/22/powercli-folder-name-mismatch/

 

 

Service status and email if down (as well as try to start it)

$
0
0

Here is a script I sorta came up with that checks common vmware services and then emails if any one of them aren't running (and trys to start them)(since our vsphere upgrade bombed a few times thanks to sql i was asked to try to write this), I am sure this has been done before and bits where taking from another place that I can't find again to give credit, so its not all mine, but somone might find this usefull, write back with questions or comments

 

Thanks!

 

 

 

 

 

 

 

 

 

 

 

Creating Reports

Get PID of VMservers

Health Check VM


Clone VM from SnapShot

Configure Switching for ESX host based on .CSV

$
0
0

A couple of weeks ago I was in need to configure several new ESX servers with multiple NICs, vSwitches, and VLANs. Since I'm not one to do the same thing over and over again I turned to scripting. To further complicate things I wanted to allow the same script to create vSwitches, configure vMotion switch, add port groups, and create NIC Teams all from a prepopulated .CSV file. I'm doing this primarily so that all configuration could be done before the server arrived and so that I could create "Switch Profiles" when I add new hosts to clusters.

 

In the end I developed a script that reads from a .CSV file and then creates the desired switching. The first column tells the script what type of addition it is and the script processes the information for that object accordingly. I've noticed a few others have been posting recently about scripts on setting up portgroups, etc. and thought it was time to no longer keep this to myself (i.e. finally found the time to post). I too would like to also credit Hal Rottenburg's book Managing VMware Infrastructure with Windows Powershell which was very helpful for this and many other scripting projects I will be posting soon. Mike Laverick's post linked below helped in configuring the vMotion switch.

 

I hope you find this helpful. It has been HUGE in my environment.

 

Download the files here:

ESX-ConfigureSwitchCSV-Generic.txt

esx_switching_generic.csv

 

Links where others discuss switch configuration with PowerCLI.

http://halr9000.com/article/828

http://www.holy-vm.com/2009/10/01/adding-port-groups-with-powercli/

http://www.rtfm-ed.co.uk/?p=1514

 

 

Text of Script w/out comments

 

$getinfo = Import-Csv "
server\share\file.csv"

Connect-VIServer -Server vCenterServer

 

$getinfo | % {

$Type = $_.Type #!!!! Case Sensitive !!!!!!

$gethost = Get-VMHost -Name $_.HostName

$SwitchName = $_.SwitchName

$PortGroup = $_.PortGroupName

$Nic = $_.NIC

$VLAN = $_.VLAN

$IP = $_.IP

$Subnet = $_.Subnet

$kernelGW = $_.KernelGW

 

If ($Type -eq "Switch") {

$gethost | New-VirtualSwitch -Name $SwitchName -Nic $Nic

}

If ($Type -ne "vMotion") {

$getswitch = Get-VirtualSwitch -VMHost $gethost -Name $SwitchName

}

If ($Type -eq "Team"){

$getswitch | Set-VirtualSwitch -Nic $Nic

}

IF ($Type -eq "Portgroup") {

$getswitch | New-VirtualPortGroup $PortGroup -VLanId $VLAN

}

IF ($Type -eq "vMotion") {

 

$newvswitch = New-VirtualSwitch -VMHost $gethost -Name $SwitchName -Nic $Nic

$vmotion = New-VirtualPortGroup -VirtualSwitch $newvswitch -Name $PortGroup

New-VMHostNetworkAdapter -VMHost $gethost -PortGroup $PortGroup -VirtualSwitch $newvswitch -IP $IP -SubnetMask $subnet -VMotionEnabled: $true

 

$vmhostnetwork = get-vmhostnetwork $gethost

set-vmhostnetwork -network $vmhostnetwork -vmkernelgateway $kernelGW

}

}

 

 

NTP, PowerShell, It's about time.

$
0
0

 

There's no doubt that time is critically important in a computing

environment. Given this sensitivity, and the recent recognition that we

had rogue hosts improperly configured, I decided to crank out a script

that would analyze our environment. I wanted to find whether the NTPD

service was running, what the NTP server configuration was, and provide

a report of this. Additionally I wanted to have the option (with

commenting) to automatically make corrections.

 

 

 

 

 

 

 

Always open to suggestions and improvements.  I hope this helps you in your environment.

 

 

 

 

 

 

###--


FULL SCRIPT--


#####

 

 

 

Connect-VIServer -Server server.domain.com     #Enter your vCenter Server

 

$NtpServer = "10.10.10.10"   #Provide your default NTP Server. This will be used as default so entering a NTP server when prompted is not necessary

 

$OldNtpServer = "10.10.10.11"         #Leave set as 127.127.1.0 as default unless you wish to change settings in your environment

 

$DefaultNtpServer = "127.127.1.0"    #NTP Server Value that is set on a fresh ESX installation.

 

#Location based on Date

$date = Get-Date -UFormat %Y%m%d

$ExportLocation = "C:\NTP-$date.csv"

 

#Location where you would like report to be saved to.

#$ExportLocation = 'C:\NTPReport.csv'

 

$NTPHosts

= Get-VMHost | Select-Object Name,@{Name="NTPServer";Expression={$_ |

Get-VMHostNtpServer}}, @{Name="NTPRunning";Expression={($_ |

Get-VMHostService | Where-Object {$_.key -eq "ntpd"}).Running}} |

Sort-Object -Property "NTPRunning", "NTPServer"

 

$NTPHosts | Export-Csv $ExportLocation -NoTypeInformation

& $ExportLocation #Opens generated report file

 

$Restart = Read-Host "Would you like to start NTPD services or change NTP configurations on hosts? (y/n)"

#$Restart = "y"  #Comment above line and uncomment this line if you wish to automatically restart services.

If ($Restart -eq "y"){

Import-Csv $ExportLocation | % {

$vmhost = $_.Name

 

#Checks the NTP configuration against a value previously determined at the top of script.

If (($_.NTPServer -eq $OldNtpServer) -or ($_.NTPServer -eq $DefaultNtpServer)){

$NtpInput

= Read-Host "Some servers are configured with NTP set as $OldNtpServer

or $DefaultNtpServer and may need their NTP settings reconfigured.

Please enter NTP Server FQDN or IP address. <$NtpServer> is

default."

 

If ($NtpInput -ne "") {

$NtpServer = $NtpInput

#Sets $NtpServer to the inputted value and does nothign if left blank.

This allows use of default when value is consistent in the environment.

}

Add-VMHostNtpServer -VMHost $vmhost -NtpServer $NtpServer | Where-Object {$_.NTPServer -eq $OldNtpServer}

Remove-VMHostNtpServer -VMHost $vmhost -NtpServer $OldNtpServer

}

 

#Now time to restart any NTPD services that are currently not running.

If ($_.NTPRunning -eq "False") {

Get-VmHostService -VMHost $vmhost | Where-Object {$_.key -eq "ntpd"} | Start-VMHostService

}

}

}

Write-Host "Process Complete"

 

 

Job-Rescan-ALL-HBA

$
0
0

This program will rescan all the HBA's in your vm enviroment, and instead of doing it one at a time, it creates a seperate job for each ESX host. Thus multithreading the rescan. For ESX 3.5 this is really handy, for vsphere 4 you can have it do a rescan of all HBA's through the vi interface. But this will work against vsphere as well.

 

I developed this script as I needed a quick way to rescan the HBA's when a failover of our HP EVA occurs. And I need the servers to rescan. I'll be working on another version which will suspend the vm's on a particular LUN, failover that particular LUN, rescan and then restart the vm.. As you can imagine this will be tricky and others have written it for other storage systems but not for HP EVA's. 

 

 

 

#Rescan all HBA's creating 1 job for each ESX server


# Kyle Weir, jkw117@gmail.com, 10-05-09

#connects initially to get the list of ESX servers 



Connect-VIServer  "vcenter" -User Administrator -Password password 



vm=get-vmhost



#Passes the server names individually to different jobs. Thus allowing it to ask each ESX host to rescan itself. 



for ($x=0 ; $x -le $vm.length; $x++)
{
Start-Job -ArgumentList $vm[$x|http://communities.vmware.com/community-document-picker.jspa?communityID=3077&subject=%24x].name -ScriptBlock {
Add-PSSnapin VMware.VimAutomation.Core
Connect-VIServer  "vcenter" -User Administrator -Password $pasd
get-vmhost $args| Get-VMHostStorage -RescanAllHBA -rescanVMFS -refresh
} 
} 

 

 

 

Any questions please email me, I am sure this can be updated to eliminate 

 

 

vCheck (Daily Report) V3

$
0
0

 

Daily Report does what it says on the tin, it runs as a scheduled task before you get into the office to present you with key information about your infrastructure in a nice easily readable format.

 

For more information see my blog post.

 

This script picks on the key areas of the virtual infrastructure and reports it all in one place so all you do in the morning is check your email.

 

One of they key things about this report is if there is no issue in a particular place you will not receive that section in the email, for example if there are no datastores with less than 5% free space (configurable) then the disk space section will not show in the email, this ensures that you have only the information you need in front of you when you get into the office.

 

 

 

 

 

 

Initially when I started this script I wanted people to be clear

that this was a report that was going to give you a daily summary of

any issues which may exist in your Virtual Infrastructure, from the

beta testing I did to a select few it was clear that they were

expecting this to send them a full inventory of their infrastructure.

 

 

That wasn’t the point in this script and I think people now have the

idea that this is more of an issue log than an audit script so I will

now revert to my original name of…. vCheck.

 

 

The key thing to remember is that if an issue does not exist in a

particular area then it will not show in the output, when and if issues

turn up they will start appearing in the output almost like magic !

 

 

I want to thank everyone who is using this script and those who have

left a comment, even if its just to say how much you like it !

 

 

I especially want to thank Raphaël SCHITZ (http://www.hypervisor.fr/) for all his contributions, he has added some great features to this version and helped me take it to a new level.

 

 

 

 

 

So what areas does this script report on ?

 

 

 

The previous version already reported on these areas:

 

  • General Details

    • Number of Hosts

    • Number of VMs

    • Number of Templates

    • Number of Clusters

    • Number of Datastores

    • Number of Active VMs

    • Number of Inactive VMs

    • Number of DRS Migrations for the last days

  • Snapshots over x Days old

  • Datastores with less than x% free space

  • VMs created over the last x days

  • VMs removed over the last x days

  • VMs with No Tools

  • VMs with CD-Roms connected

  • VMs with Floppy Drives Connected

  • VMs stored on local datastores

  • VMs with CPU ready over x%

  • VMs with over x amount of vCPUs

  • List of DRS Migrations

  • Hosts in Maintenance Mode

  • Hosts in disconnected state

  • NTP Server check for a given NTP Name

  • NTP Service check

  • vmkernel warning messages ov the last x days

  • VC Error Events over the last x days

  • VC Windows Event Log Errors for the last x days with VMware in the details

  • VC VMware Service details

 

So what is added to V3 ?

 

 

Well firstly I have fixed some bugs which existed in V2 and made things slightly faster.

 

 

The other added features are as below:

 

  • Status report to screen whilst running interactively

  • At the top of the script you can now turn off any areas you do not want to report on (this makes it faster to run)

  • VMs on Local storage has been changed to report VMs stored on datastores attached to only one host

  • VM active alerts

  • Cluster Active Alerts

  • If HA Cluster is set to use host datastore for swapfile, check the host has a swapfile location set

  • Host active Alerts

  • Dead SCSI Luns

  • VMs with over x amount of vCPUs

  • vSphere check: Slot Sizes

  • vSphere check: Outdated VM Hardware (Less than V7)

  • VMs in Inconsistent folders (the name of the folder is not the same as the name)

  • Added the number of issues to each title line

 

As always please let me know if you have any comments, I already

have some great ideas that I could not fit into this version so watch

out for V4 !

 

 

+Also a reminder that this script also checks your Windows

vCenter server for services and event logs, it does this via WMI and

therefore needs the correct permissions, there is still an area at the

top of the script which you can give alternate credentials from the

account that is running the script if needed.+

 

 

If your new to this script and would like more details on how it looks or how to run it please check this post.

 

 

At the bottom of he script is also an area which you can uncomment to save a the daily report as a htm file in a specific folder.

 

I think that’s it !

 

If there is anything missing please let me know and I will add it to future versions.

 

To run this script simple setup a scheduled task as per my previous post running the script and passing it your VI server as a parameter as below:

 

C:\WINDOWS\system32\windowspowershell\v1.0\powershell.exe -PSConsoleFile “C:\Program Files\VMware\Infrastructure\vSphere PowerCLI\vim.psc1″ ” &  “C:\Scripts\DailyReport.ps1 TESTVC01″

 

 

Using PowerCLI to migrate VMs in a DRS enabled Cluster

$
0
0

 

We are running ESX 4.0 on HP DL380G6 servers.  I created a cluster with three hosts and enabled HA and DRS.  I can use the VSphere GUI to tell a host to enter Maintenance Mode, and since it is in a DRS enabled cluster, it will migrate it's VMs to the other hosts in the cluster and all is well.  When I try to do the same thing in PowerCLI (i.e. : Set-VMHost -VM <VMHostName> -State "Maintenance"), I get the message: "There are one or more powered on virtual machines on host: <VMHostName>.  The host will go into maintenance mode once all virtual machines are powered off."  We are trying to create some Security Updates scripts and would like the capability to do this without having to specify the migration of each VM manually by name.

 

 

Any ideas?

 

 

create a. bat file to connect to vCenter

$
0
0

 

Hello, I need to create one .bat to open a connection automatically to vCenter, I created a .bat PowerCLI calling and opens well but I did not connect, you copy the contents:

 

C: \ Windows \ System32 \ WindowsPowerShell \ v1.0 \ powershell.exe-psc "C: \ Program Files (x86) \ VMware \ Infrastructure \ vSphere PowerCLI \ vim.psc1"-noe-c ". \" C: \ Program Files (x86) \ VMware \ Infrastructure \ vSphere PowerCLI \ Scripts \ Initialize-VIToolkitEnvironment.ps1 \ ""

 

connect-viserver -Server localhost -Protocol https -User administrator -Password password1

 

 

 

When I open PowerCLI and run the line connect-viserver successfully connected but not connected when I run the .bat.

 

Any ideas? Thanks

 

 


Need a PS script to delete/remove a VM

$
0
0

Hello,

 

Is there any sample powershell script to perform something simple like removing a VW?

 

 

 

Given the datacenter name and the vm name, is there such a script someplace I could use to perform that?

 

 

Thanks.

PowerCLI script to clone and customize Linux guest OS

$
0
0

http://honglus.blogspot.com/2010/10/vsphere-powercli-script-to-clone-and.html

 

The script can clone Linux and assign ip addresses to multiple adapters.

 

There are 2 scripts

discover-info.ps1 Discovery information of target viserver/ESX host and generate template file to be used for clonevm.ps1

vmclone.ps1 clone after read information from template file generated by discover-info.ps1 script

The scripts has been tested in VMware vSphere PowerCLI 4.0 for VMs in ESX 3.5/ESX4.0 managed by Virtual Center Server.

 

Scripts in Action

 

PowerCLI # D:\Temp> .\discover-info.ps1Discovered ESX hosts:esx01 esx02

Please enter target ESX hostname: esx01

..

Template file: vmdata.txt has been generated. Edit the file then run 'clonevm.ps1 -f file-name' to start cloning

 

PowerCLI # D:\Temp> cat vmdata.txt (after customization)

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

#Discovered information

 

#PortGroups='Service Console' 'vlan-01' 'vlan-02'

#Folders='host' 'Discovered Virtual Machine' 'Datacenters' 'vm'

#DataStores= 'nfs_storage' 'esx01:storage1'

#resourcepools=Name: Resources ID:ResourcePool-resgroup-7 Name: Resources ID:ResourcePool-resgroup-65

####----


 

####----


Customize your VM values using the template

esxhost=esx01

##Resource pool id is NOT required for using virtual machine as source, but IS required for using template as source

#resourcepoolid=

#vm means Virtual Machine; vt means template ( resourcepoolid is required for vt)

SrcName=vm,linuxtemplate

DstName=pstest1

##Use vm as folder if no user folders defined

Folder=vm

DataStore=nfs_storage

##Gateway is optional, enter - to skip this value

##Networkadapter type is optional (Auto choosen for guest OS) , enter - to skip this value

##Supported adapter types: e.g e1000, Flexible, Vmxnet, EnhancedVmxnet

Network=EnhancedVmxnet,vlan-01 ,172.19.1.1,255.255.248.0,172.19.1.10 ; -,vlan-02,172.20.1.1,255.255.255.0,-

DNS=10.1.1.1,10.1.1.2

Domain=example.com

#Poweron=yes

 

 

PowerCLI # D:\Temp> .\clonevm.ps1 -f .\vmdata.txt

==> Retrieving info for source VM: linuxtemplate

==> Starting clone process ...

4% 10% 16% 21% 27% 33% 38% 45% 51% 57% 62% 68% 74% 79% 85% 91% %

Completed Task: Task-task-2366

==> Checking new VM ...

 

 

Name PowerState Num CPUs Memory (MB)

pstest1 PoweredOff 1 4096

==> Removing existing network adapters ...

==> Adding 2 new network adapters ...

..

==> Customizing guest OS ...

%

Completed Task: Task-task-2370

==> Checking new VM ...

pstest1 PoweredOff 1 4096

 

 

Number of vCPUs in a cluster

Get-VDMData (takes a username and returns data about all the Virtual Desktops they are entitled to use)

$
0
0

We get tickets from users that are having an issue with their Virtual Desktops and we only have their username to figure out which VM they are using. It can be a pain to find out which VMs they are entitled to in the GUI so I wrote a script to pull the data.

 

I have found that there are currently no VMWare cmdlets that allow you to get data from Virtual Desktop Manager directly. However, VDM stores it's data in an ADAM instance and PowerShell can connect to ADAM to get at the data.

 

My script will prompt you for your credentials (to talk to Virtual Center and Virtual Desktop Manager) and then prompt you for a username. It will then convert the username to a SID and lookup the SID in the ADAM instance on your VDM server to find which VMs the user is entitled to use. The script then uses the VIToolkit cmdlets to pull information about those VMs.

 

You need to update the script with data for these variables:

 

 

$VCServer - this needs to be the FQDN of your Virtual Center server

 

 

$VDMServer - this is the Virtual Desktop Manger server that has the entitlement information for the user

 

 

Enjoy!

 

This document was generated from the following thread: Get-VDMData (takes a username and returns data about all the Virtual Desktops they are entitled to use)

Find Orphaned VMDK's

$
0
0

 

 

 

 

(This script is for ESX 3.01, to find snapshots on 3.5 and above change the script en the names it searches for!!!!!)

 

 

 

 

Hi,

 

This script will find all orphaned vmdk's on all your virtual centers (we have more than one ).

 

Our VM's are being administered by mutliple people. When removing a virtual disk, sometimes people forget to delete the vmdk file itself.

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

This script asks the virtual center what the disk are of each VM and puts this into an array. After this, it reads all files on all datastores. If the file is a vmdk file, it will check wheter this file is in the array. If it's not, you've found a orphaned vmd.

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

Output is being written to a file.  Script displays the Host off which files are being enumerated(For waiting purposes).

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

Variables whcih have to be submitted:

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

$arrayVC = "YourVirtualCenter"

$OutputFile = "C:\OrphanedVMDK.txt"

                                                                                Greetings,

 

 

 

 

 

 

Ad van Bokhoven

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

This document was generated from the following thread: Find Orphaned VMDK's

 

 

Viewing all 379 articles
Browse latest View live


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