Countdown to 2009

function CountDown
{
 While ((Get-Date).Year -lt 2009)
 {
  Clear-Host
  Write-Host “COUNTDOWN TO 2009:”
  (Get-Date “1/1/2009 0:00″) – (Get-Date) | Format-Table Days, Hours, Minutes, Seconds -AutoSize
  Write-Host “Countdown brought to you by:”
  Write-Host “http://www.peetersonline.nl
  Start-Sleep -Seconds 1
 }
 Clear-Host
 Write-Host “HAPPY NEW YEAR!”
 Write-Host “from Hugo at http://www.peetersonline.nl
}
CountDown

Happy Holidays to all of you!

Add RDM Size info to VI Client using Powershell

I have had a lot of comments on my sample scripts that add information to the VI Client using Custom Fields. I did have to resolve some issues with the scripts, so I have updated the scripts in the original post here. Be sure to refresh your browser to get the latest versions.

In the VMware VI Toolkit Communities, a request was made for a similar script that adds the total size of all Raw Device Mappings (RDMs) on a VM to a Custom Field in the VI Client. The difference between this sample script and the ones I showed you earlier, is that the information is now pulled from $VM and not from $VMView. So I pulled the Get-View command inside the loop and here’s the result:

add-vmrdmsize (rename to .ps1)

Let me know if you can’t get it to work.

Hugo

»crosslinked«

TOP 10 Commandlets in a Oneliner

“It’s the time for lists”, I read somewhere today. Sure, that is true. But blogging little lists isn’t much fun.

So, I will let you generate your very own TOP 10 list. Use the following Powershell Oneliner to get a TOP 10 list of your most frequently used cmdlets in your scripts. (Remember to modify the path to your script storage location.)

Happy Holidays!

Get-ChildItem D:Scripts -Filter *.ps1 -Recurse |
 Select-String (Get-Command|%{$_.Name}) |
 Group Pattern |
 Sort Count -Descending |
 Select -First 10 |
 Format-Table Name, Count -AutoSize

Add Custom Fields to VI Client with Powershell (Samples)

In my previous post, I showed you how to add information to your VI Client using Custom Fields. Here are some ready-to-go scripts to add very useful info:

Snapshot Count

I already showed you how to do this, but I have now added an IF-statement so that only changes are updated (equal values are not overwritten). And I have added Julian Wood’s correction. add-vmsnapshotcount (rename to .ps1)

Total Snapshot Size

The number of snapshots is quite inetresting, but even more interesting, is the total size of the delta files all snapshots are occupying. They might be eating up all your precious SAN space. Plus, reverting to or committing a large snapshot is tricky. add-vmsnapshotsize1 (rename to .ps1)

Host Hardware Model

Want to see what models of hardware you are using in your datacenter? You could look at the summary tab of each host. Or run this script to add the info to the every Hosts tab in the VI Client. Select your Datacenter, select the Hosts tab and enjoy! add-vmhostmodel (rename to .ps1)

Host ESX Version

Did you update all your ESX Servers to the latest version? Check it quickly using this script. add-vmhostversion (rename to .ps1)

Host LUN Count

Last but certainly not least: are you sure every datastore you are using is available to all your ESX Servers? It is visible at a glance when you add the LUN Count to your VI Client! add-vmhostluncount (rename to .ps1)

Happy Holidays!

Hugo

Add Snapshot Information to the VI Client using Powershell

Although I spend quite some time in the Powershell Command Line Interface, the main tool for managing the Virtual Infrastructure remains the VI Client. So wouldn’t it be great if we could somehow show the results of our Powershell VI Toolkit scripts inside the VI Client?
Well, we can! Let’s take a closer look at Custom Fields / Custom Attributes.
If you select either a VMHost (ESX Server) or a VM in the VI Client and open the Summary tab, you will see the Annotations section in the bottom left. When you click Edit, I’m sure you have used the Notes section to enter Descriptions. But have you ever used the Attributes section? Here you can manually add and remove custom attributes and their values. Go ahead and create one. Then select a cluster or datacenter and click the Hosts or Virtual Machines tab. You will notice you can display your custom attribute in this table view, just like all the other properties of your VMs / Hosts. Pretty sweet!
But we don’t want to add and update those fields manually, now do we? Of course not, we’ve got Powershell! Let’s see how we can automate this.
We start by connecting to the Custom Fields Manager:

$VCServerName = “MYVCSERVER”
$VC = Connect-VIServer $VCServerName
$SI = Get-View ServiceInstance
$CFM = Get-View $SI.Content.CustomFieldsManager

Take a look at the $CFM.Field property. It contains an array of available fields. Next step: add our own custom field.

# Variables
$CustomFieldName = “Snapshots”
$ManagedObjectType = “VirtualMachine”
# Check if the custom field already exists
$myCustomField = $CFM.Field | Where {$_.Name -eq $CustomFieldName}
If (!$myCustomField)
{
# Create Custom Field
$FieldCopy = $CFM.Field[0]
$CFM.AddCustomFieldDef($CustomFieldName, $ManagedObjectType, $FieldCopy.FieldDefPrivileges, $FieldCopy.FieldInstancePrivileges)
}

Final step: Fill the custom field with some relevant information:

# Fill Custom Fields
$VMs = Get-VM
$VMViews = $VMs | Get-View
ForEach ($VMView in $VMViews)
{
$SnapshotCount = ($VMView.Snapshot.RootSnapshotList | Measure-Object).Count
If ($SnapShotCount)
{
$VMView.setCustomValue($CustomFieldName,$SnapShotCount)
}
}

Now take a look at the VI Client:
snapshots
More examples coming soon!
Hugo

PS: Don’t forget to schedule the script to run at an interval, so the values are kept up-to-date!

Powershell function to find event log explanations

Today I am attending the Dutch VMware User Group (VMUG) Meeting. No doubt I’ll return with lost of inspiration for new Powershell VI Toolkit scripts.
In the meantime, I will show you a nifty little function that will come in handy if you are troubleshooting Windows Server Event Log errors and / or warings. The usage is super-simple:

Find-Event EventID [Source]
For example: Find-Event 18056
Or: Find-Event 1 MSSQLServer

What it does? Give it a go (it’s harmless)… ;)

Here’s the code:

Continue reading

Get VMware Disk Usage with Powershell

Using VMware seriously requires a lot of (shared) storage. This kind of storage (on a SAN for instance) is quite expensive. So you might want to check if you are wasting a lot of this space. When you look at the storage in VMware, it consists of multiple abstraction layers. A virtual machine has one or more Logical Disks, which are indicated by driveletters. You can use WMI to determine the amount of used and free space (Win32_LogicalDisk). One or more logical disks are contained in a partition. One or more partitions reside on a physical disk. That physical disk is really a virtual disk, a vmdk file to be precise. One or more vmdk files reside in a Datastore, which can be found on a LUN on your SAN.
The following script enumerates most of these layers (from logical disk to datastore) and calculates the used and free space. The final line exports the results to a csv file for use in Excel. And the script also helps you to calculate the average free space by showing the totals without the duplicates (don’t try to average the averages in excel, that’s not accurate because datastores contain duplicates and averages should be weighed).

UPDATE: I have modified the script, so no more matching of disks is done based on disk size. The match is made based on SCSI IDs and WMI relations. Thanks to adavidm on the VI Toolkit Community Continue reading

Powershell Poker Game

There is more to life than just work. For that reason, and because I enjoy a puzzle, I have created a little Poker game in Powershell. The games’ concept is based on a poker game by Arne Rippe, which I enjoyed so much, I recreated it. You have to survive 20 rounds of poker. You can bet 100 credits, half your bankroll or go all-in. The payout is always 2 to 1. The special part about this game is the fact you get to see all starting hands and get to choose which you prefer. Give it a go, I’m sure you’ll like it! My high score is 3400 credits.

Hugo
Continue reading

Get SQL Log Messages with Windows Powershell

Here’s a little something for the sysadmin that monitors SQL servers (who doesn’t?). This handy little function retrieves SQL log messages for a specified instance. You can also specify how many of the most recent messages to retrieve.

function Get-SQLLog
{
param([string]$Instance, [Int]$SizeLimit = 10)
If ($Instance -eq $null){Write-Warning “Syntax: Get-SQLLog [-Instance] [[-SizeLimit] ]”}
Else
{
[System.Reflection.Assembly]::LoadWithPartialName(‘Microsoft.SqlServer.Smo’) | Out-Null
$Sql = New-Object (‘Microsoft.SqlServer.Management.Smo.Server’) $Instance
$sql.ReadErrorLog() | select -last $SizeLimit
}
}

Handy little function: Create-Script

One of the great features of Windows Powershell is the combination of the rich scripting language and the interactive shell. I often find myself playing around in the interactive shell until I know how to get the information I need. Then I start to put the code into a script for easy use. (And to share it with you, of course.) And although the shell allows for copy/paste, I wouldn’t be much of a scripting enthusiast if I didn’t want that to be easier ;)
Enter Create-Script. This little function belongs in any scripter’s profile. It copies your entire history into a file and opens it for you. Just remove the obsolete lines and add formatting and comment and your script is as good as done!

function Create-Script
{
$ScriptFile = ‘D:\scripts\newscript.ps1′
Remove-Item $ScriptFile -Confirm
ForEach ($i in (Get-History -Count 999))
{
Add-Content $ScriptFile $i.CommandLine
}
Invoke-Item $ScriptFile
}

The function re-uses the same file each time, asking for confirmation to overwrite it. Don’t forget to use Save As… to store your finished work.

I can’t wait to see the masterpieces you will create. Don’t forget to share them!
Hugo

PS: You might want to consider to increase the amount of commands kept in your history. Just set the $MaximumHistoryCount variable to the desired value.