Disable hibernation on multiple Windows 2008 servers using Windows Powershell

By default hibernation is disabled on Windows 2008 server machines. However, a file called “hiberfil.sys” (equally sized to the amount of memory in the machine) is created in the root of the system volume.
On a machine with 2GB of memory, this is not a big issue. However I discovered this on a VM with 12GB of memory.. *auch*
After some google’ing around I found out that there’s a way to get rid of this “hiberfil.sys”, the following Microsoft KB article gives you more information about this: http://support.microsoft.com/kb/920730/en-us
This command disables hibernation and also get’s rid of the hiberfil.sys file:

powercfg.exe /h off

But what if we wanted to repeat this task for let’s say 30-40 servers? Do it by hand? No way, Powershell to the rescue!
Here’s the script I came up with, enjoy:

# Ask for credentials used to do remote WMI.
$cred    	= Get-Credential DOMAIN\account

# Filter used for active directory query. Only 2008 server machines.
$strFilter 	= "(&(objectClass=computer)(operatingSystem=Windows *2008*))"

$objDomain 	= New-Object System.DirectoryServices.DirectoryEntry
$objSearcher = New-Object System.DirectoryServices.DirectorySearcher
$objSearcher.SearchRoot = $objDomain
$objSearcher.Filter = $strFilter
$objSearcher.SearchScope = "Subtree"

$colResults = $objSearcher.FindAll()

# Loop through list of servers.
foreach ($objResult in $colresults)
{
	$objItem = $objResult.Properties
	$name = $objItem.name[0]

	Write-Host "Disabling hibernation on: $name"

	try {
		invoke-wmimethod -cred $cred -path win32_process -name create -argumentlist "powercfg.exe /h off" -ComputerName $name
	} 
	catch {
		Write-Host "Failed to disable hibernation on: $name, no permission or server down?"
		break
	}
	finally {
		Write-Host "Hibernation disabled on: $name"
	}
}

Onwards!