Category Archives: Powershell

Today I got a request from a colleague of mine that was doing inventory: What are the make, model, serial number and purchase date of your monitors? Seeing as this wasn’t something I had readily in my head I had to figure it out, but being the automation enthusiast that I am, I refused to bend over my monitors and snap a photo of it all. I wanted to find it a cooler way, the powershell way ūüôā This information is stored in WMI, so all I had to do was to grab it using Get-WmiObject and then format it rather nicely for him. The powershell script I came up with isn’t my most beautiful work, but here it is: $progress = 1 foreach ($monitor in (Get-WmiObject WmiMonitorID -Namespace root\wmi)) { Write-Host “Monitor #$($progress):” -ForegroundColor Green Write-Host “Manufactur: $(($monitor.ManufacturerName | ForEach-Object {[char]$_}) -join ”)” Write-Host “PN: ” ($($monitor.UserFriendlyName | ForEach-Object…

Read more

Lately, I’ve had the pleasure of using Powershell to automate some of the basic tasks we do on our HPE 3PAR systems: creating volumes, adding them to volume sets, exporting them and so on. Since my experience with REST APIs was rather limited it was quite daunting at first but once you get the hang of how REST works and the Invoke-RestMethod cmdlet it’s really not that bad. Disclaimer: The examples below will vary somewhat in how I do certain things, simply because I had to learn all this from scratch. Hence, the first examples will sometimes do things “less correct” than the later examples since this also was quite the learning curve for me. The first step in doing anything with the REST API will always be to create a session key. If you’re not familiar with APIs, think of a session key as username and password combined into…

Read more

A tweet from @JanEgilRing caught my eye this morning, it¬†was showing¬†how you can use powershell to create passwords. The link in the tweet pointed here:¬†http://powershell.com/cs/blogs/tips/archive/2016/05/23/one-liner-random-password-generator.aspx Seeing that line and realizing how simple it was, it got me thinking on¬†how I could implement this in my scripts. The only issue I saw with that one-liner was that the passwords it creates do not necessarily comply¬†with high complexity rules. So, how can we approve on this? Firstly, we need to create a regex that we can use to validate that the password created complies with our rules. In our environment this means 12 characters, uppercase, lowercase and either a number or special character. The regex I ended up with is this one:¬†^.*(?=.{12,})(?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[@#$%^&+=]).*$ (which I found here:¬†https://nilangshah.wordpress.com/2007/06/26/password-validation-via-regular-expression/¬†) Now that we have our regex we can simple throw the one-liner into a while loop: while ($pass -notmatch “^.*(?=.{12,})(?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[@#$%^&+=]).*$”) { $pass = -join (‘abcdefghkmnrstuvwxyzABCDEFGHKLMNPRSTUVWXYZ23456789$%&*#’.ToCharArray() |…

Read more

My very first PowerCLI related post was about this same topic: listing snapshot info using PowerCLI. In my original post (which you can see here) I only wrote a pretty simple one-liner. Which was kind of okay, but it was missing one crucial thing: who took the snapshot? Why vmware hasn’t found a way to include a username in the get-snapshot cmdlet is something I just can’t understand. There’s really not much code needed to add this to the output, and there’s several ways of doing so. I found that using Get-Snapshot and Get-VIEvent together was the easiest way to get all the info I want. It’s not a perfect solution, seeing as I really wanted to make use of the much faster Get-View instead of Get-Snapshot, but I have yet to figure out a good way to handle snapshot trees using Get-View. As usual I created a function for…

Read more

In case you ever need to empty out a datastore in you vmware environment, there is a nice little one-liner in PowerCLI for that: Get-VM -Datastore “datastore1″ | Move-VM -Datastore (Get-VMHost -Location ‘cluster1’ | Select-Object -First 1 | Get-Datastore | Where-Object {($_.Name -ne ‘datastore1’) -and ($_.FreeSpaceGB -gt ‘500’)} |¬†Sort-Object FreeSpaceGB -Descending | Select-Object -First 1) Where “datastore1” is the datastore you want to empty out and “cluster1” is the cluster where the datastore is available. The command will move VMs from datastore1 to the datastore in cluster1 with the most available space (minimum 500GB)

For almost a year ago, I posted a simple one-liner to list all VMs who has ISOs mounted. You can view that post here:¬†http://cloud.kemta.net/2013/10/powershell-vmware-list-all-vms-with-iso-mounted-and-dismount-them/ That post was written before I truly discovered the major advantages of using Get-View instead of Get-VM, Get-VMHost and so on. If used correctly, there’s a major difference in speed when using Get-View over Get-VM. When writing this post I checked the differences in speed when using the old way that I linked to above and my new function (which I’ll get to in a second or two..), the result was as follows: As you can see, the difference is pretty clear. 5 seconds vs. 1.6 minutes… So,¬†without further ado, I present to you the code for Get-ISOMounts: function Get-ISOMounts { [CmdletBinding()] Param ( [switch]$Dismount ) $VMs = Get-View -ViewType virtualmachine -Property name,Config.Hardware.Device $VMsWithISO = @() $progress = 1 foreach ($VM in $VMs) { Write-Progress -Activity…

Read more

I love a powershell challenge, and last week a colleague of mine asked me for assistance in getting the uptime of vmware hosts. My initial response did the trick: Get-View ¬†-ViewType hostsystem -Property name,runtime.boottime | Select-Object Name, @{N=”UptimeDays”; E={((((get-date) – ($_.runtime).BootTime).TotalDays).Tostring()).Substring(0,5)}} However, I wasn’t completely satisfied by the the output or the ease of use. So today I went back and rewrote the code and made a function of it. Instead of using the ToString and Substring methods I went for the built-in class Math, which has a method called Round. You can learn more about the Math class here:¬†http://www.madwithpowershell.com/2013/10/math-in-powershell.html Anyways, here’s the function I came up with: function Get-VMHostUptime { [CmdletBinding()] Param ( [Parameter(ValueFromPipeline=$True,ValueFromPipelineByPropertyName=$True)][Alias(‘Name’)][string]$VMHosts, [string]$Cluster ) Process{ If ($VMHosts) { foreach ($VMHost in $VMHosts) {Get-View -ViewType hostsystem -Property name,runtime.boottime -Filter @{“name” = “$VMHost”} | Select-Object Name, @{N=”UptimeDays”; E={[math]::round((((Get-Date) – ($_.Runtime.BootTime)).TotalDays),1)}}, @{N=”UptimeHours”; E={[math]::round((((Get-Date) – ($_.Runtime.BootTime)).TotalHours),1)}}, @{N=”UptimeMinutes”; E={[math]::round((((Get-Date) – ($_.Runtime.BootTime)).TotalMinutes),1)}}} }…

Read more

I’m sure I don’t need to explain to you guys why VMware tools is a good idea to have installed on your VMs, and probably not why it’s a good idea to keep VMware tools updated. However, I haven’t found a good way to get a neat list of which VMs need to have their VMware tools upgraded. While working on my vCenter health check script I found that I had to make my own little script to get that list. And, in addition, I wanted the list to include the VM version. I ended up with creating a function to provide me with that list: function Get-VMToolsStatus { [CmdletBinding()] Param ( [ValidateSet(‘NeedUpgrade’,’NotInstalled’,’Unsupported’)][string]$Filter ) $VMs = Get-View -ViewType VirtualMachine -Property name,guest,config.version,runtime.PowerState $report = @() $progress = 1 foreach ($VM in $VMs) { Write-Progress -Activity “Checking vmware tools status” -Status “Working on $($VM.Name)” -PercentComplete ($progress/$VMs.count*100) -ErrorAction SilentlyContinue $object = New-Object PSObject…

Read more

Next in the series on getting alarms is getting datastore alarms. Again, the code is pretty similar: $Datastores = Get-View -ViewType Datastore -Property Name,OverallStatus,TriggeredAlarmstate $FaultyDatastores = $Datastores | Where-Object {$_.TriggeredAlarmState -ne “{}”} $progress = 1 $report = @() if ($FaultyDatastores -ne $null) { foreach ($FaultyDatastore in $FaultyDatastores) { foreach ($TriggeredAlarm in $FaultyDatastore.TriggeredAlarmstate) { Write-Progress -Activity “Gathering alarms” -Status “Working on $($FaultyDatastore.Name)” -PercentComplete ($progress/$FaultyDatastores.count*100) -Id 1 -ErrorAction SilentlyContinue $entity = $TriggeredAlarm.Entity.ToString() $alarmID = $TriggeredAlarm.Alarm.ToString() $object = New-Object PSObject Add-Member -InputObject $object NoteProperty Datastore $FaultyDatastore.Name Add-Member -InputObject $object NoteProperty TriggeredAlarms (“$(Get-AlarmDefinition -Id $alarmID)”) $report += $object } $progress++ } } Write-Progress -Activity “Gathering alarms” -Status “All done” -Completed -Id 1 -ErrorAction SilentlyContinue $report | Where-Object {$_.TriggeredAlarms -ne “”} And the output is pretty similar: The function code is this: function Get-DatastoreAlarms { $Datastores = Get-View -ViewType Datastore -Property Name,OverallStatus,TriggeredAlarmstate $FaultyDatastores = $Datastores | Where-Object {$_.TriggeredAlarmState -ne “{}”} $progress = 1 $report =…

Read more

The next step in my short series on getting vCenter alarms using PowerCLI is to get cluster alarms. Here’s the code: $Clusters = Get-View -ViewType ComputeResource -Property Name,OverallStatus,TriggeredAlarmstate $FaultyClusters = $Clusters | Where-Object {$_.TriggeredAlarmState -ne “{}”} $report = @() $progress = 1 if ($FaultyClusters -ne $NULL) { foreach ($FaultyCluster in $FaultyClusters) { foreach ($TriggeredAlarm in $FaultyCluster.TriggeredAlarmstate) { Write-Progress -Activity “Gathering alarms” -Status “Working on $($FaultyCluster.Name)” -PercentComplete ($progress/$FaultyClusters.count*100) -Id 1 -ErrorAction SilentlyContinue $entity = $TriggeredAlarm.Entity.ToString() $alarmID = $TriggeredAlarm.Alarm.ToString() if ($entity -like “ClusterComputeResource-*”) { $entityName = $FaultyCluster.Name $type = “Cluster” } elseif ($entity -like “HostSystem-host*”) { $entityName = (Get-View -ViewType HostSystem -Property Name | Where-Object {$_.MoRef -eq $entity}).Name $type = “VMHost” } elseif ($entity -like “VirtualMachine-vm*”) { $entityName = (Get-View -ViewType VirtualMachine -Property Name | Where-Object {$_.MoRef -eq $entity}).Name $type = “VM” } $object = New-Object PSObject Add-Member -InputObject $object NoteProperty Cluster $FaultyCluster.Name Add-Member -InputObject $object NoteProperty Entity $entityName Add-Member -InputObject $object…

Read more

10/42