Posts Tagged ‘Powershell’

Powershell-How to query memory state via Get-WMIObject

March 27, 2017

here is a simple example how WMI queries can be call’d from powershell. this one is just an example and you can extend this by any system property like processors, available memory or even include disk space informations. all is about your needs and of course your creativity

$x = read-host -prompt "Please enter the machine name " 
$colItems = get-wmiobject -class "Win32_ComputerSystem" -namespace "root\CIMV2" -computername $x

foreach ($objItem in $colItems){
$displayGB = [math]::round($objItem.TotalPhysicalMemory/1024/1024/1024, 0)
write-host "Total Physical Memory:" $displayGB "GB"
write-host "Total CPU (Sockets) found:" $totalsockets
write-host "Model: " $objItem.Model

$colItems2 = get-wmiobject -class "Win32_Processor" -namespace "root\CIMV2" -computername $x

foreach ($objItem2 in $colItems2){
write-host "System Name:" $objItem2.SystemName


an example from a previous post, here I do calculate the memory pressure on a cluster node to identify oversubscribed hosts which can lead perf issues




the WMIBrowser is really useful when you do not know exactly what properties are available and how to call them


WMI is really powerful and nearly every Windows property can be called from there – Ok I see how you are thinking about all the creative ways now…Happy scripting Winking smile

Powershell-3rd Party modules

April 27, 2016

there are several 3rd party Powershell modules available which enables you to manage your devices like F5 BIG or Cisco UCS with Powershell. just from my experience, the functions are limited but at least if offers you ability to automate basic reoccurring stuff like a.e. backup configuration and also a good starter to develop your own crazy stuff. here are 2 which I use currently and which I can recommend to take a look at


Cisco UCS Powertool

Around Cisco UCS you can also check out this site from joemar which provides lots of examples for management UCS centers

there are many more out there so please share any 3rd party modules you would recommended and I will add them to this list

Thanks and stay tuned Winking smile


Powershell–How to monitor HP Smartarray disk status?

July 4, 2014

really a quick one and straight forward but sometimes very useful. here is a quick example how you can monitor your smartarray controller disk status and in case of “Failed” drive detected sent a mail out to you with the summary.

Of course, SCOM has also automated capabilities to monitor HP hardware components in a much more efficient way but that’s a another story

Prerequisites are:

– depends on your SA version – you need the “HP ProLiant Array Configuration Utility (CLI) for Windows” and can be found here, the user guide here

– if required, modify program path to hp array utility command line tool "C:\Program Files\HP\hpssacli\bin\hpssacli.exe"

– modify smtp settings $smtpServer, $smtpFrom, $SMTPPort, $Username, $Password and $smtpTo

– modify $localhost

– check if your controller is 0 “controller slot=0”

###Code Snippet###

Get-item ".\log.txt" -ea 0 | Remove-Item -ea 0

function CheckSmartArray {
Write-Host " "
Write-Host "Checking SmartArray on system"$localhost"" -foregroundcolor green
C:\Windows\System32\cmd.exe /c "C:\Program Files\HP\hpssacli\bin\hpssacli.exe" controller slot=0 physicaldrive all show

CheckSmartArray | out-file -filepath $logfile -append

function SentDiskDrivefailedviaMail {
$Logs=Get-Content $logfile
$smtpServer = ""
$smtpFrom = ""
$SMTPPort = "25"
$Username = ""
$Password = "passwordhere"
$smtpTo = ""
$messageSubject = "Disk Drive failed at $localhost"

[string]$messagebody = ""

foreach ($log in $logs )
    $messagebody = $messagebody + $log + "`r`n"
Write-Host "failed disk detected – starting to sent mail to $smtpTo via $smtpServer …." -ForegroundColor red
$smtp = New-Object Net.Mail.SmtpClient($smtpServer)
$smtp.Credentials = New-Object System.Net.NetworkCredential($Username, $Password);
Write-Host "mail sent completed " -ForegroundColor green
Write-Host " "

#Check logfile if a "Failed" status can be found, if true send a mail with "SentDiskDrivefailedviaMail" function
[array]$logcontent=gc $logfile
foreach ($line in $logcontent) {
    if ($line -match "Failed") {
    Write-Host " "
    write-host "failed disk found at $localhost " -foregroundcolor red
    write-host "detailed logs can be found $logfile " -foregroundcolor red
    Write-Host " "

###Code Snippet###

Sample Output from smart array CLI utility “controller slot=0 physicaldrive all show”


Disclaimer: Please read and test script before you run in your production!

Powershell-How to easily verify patch level between computers

July 4, 2014

Compare patches between computers? Here is a quick and easy way how you can verify this with Powershell

$node1 = Get-HotFix -ComputerName SERVER1
$node2 = Get-HotFix -ComputerName SERVER2
Compare-Object -ReferenceObject $node1 -DifferenceObject $node2 -Property HotFixID

Example Output:

HotFixID                                                    SideIndicator
——–                                                    ————-
KB2862152                                                   =>
KB2876331                                                   =>
KB2884846                                                   <=
KB2892074                                                   <=
KB2894029                                                   =>

The Compare-Object cmdlet compares two sets of objects. One set of objects is the "reference set," and the other set is the "difference set."

The result of the comparison indicates whether a property value appeared only in the object from the reference set (indicated by the <= symbol), only in the object from the difference set (indicated by the => symbol) or, if the IncludeEqual parameter is specified, in both objects (indicated by the == symbol).

Compare-Object is really powerful, check it out

How to configure Preferred Owners and AutoFailback with Powershell in Failover Cluster?

April 7, 2014

Consider scenario, you “balanced” your VMs across your nodes and you come back in the morning and they are migrated “for whatever reason” to different nodes. But as a typical administrator 😉 you know your workload best and you want to keep them preferred on a targeted node. In case of an unexpected reboot the VMs will get migrated to next available node in your Failover Cluster and goal is as soon as the node is back the VM should automatically fail back = PreferredOwners. 

Here is a quick example where you configure all clustered VM roles in a targeted cluster for preferred owners based on the current owner node. this should only give you an idea how things can be automated very easily with Powershell:

$Cluster = Read-Host "Cluster Name "
$Praefix = Read-Host "Please provide präfix for your clustered VM role names (a.e.SCVMM) "
Write-Host " "
Write-Host "Getting all clustered VM roles and configure Preferred Owners in cluster $Cluster" -ForegroundColor yellow
Write-Host " "
Write-Host " "
$AllClusterGroup = Get-ClusterGroup -Cluster $Cluster -Name $Praefix*

Write-Host "….running loop for all Clustered VMs"
Write-Host " "
Write-Host " "
foreach ($ClusterGroup in $AllClusterGroup)
    $ClusterGroupDetails = Get-ClusterGroup -Name "$ClusterGroup"
    Write-Host "Getting current Owner for $ClusterGroup…." -ForegroundColor yellow
    $CurrentOwner = $ClusterGroupDetails.OwnerNode.Name

    Set-ClusterOwnerNode -Group $ClusterGroup $CurrentOwner
    Write-Host "Current owner for VM $ClusterGroup is $CurrentOwner, configure Preferred Owner…done" -ForegroundColor yellow
    #Enable Autofailback
    (Get-ClusterGroup -Name "$ClusterGroup").AutoFailbackType=1
    Write-Host "Enabling Autofailback VM $ClusterGroup…done" -ForegroundColor yellow
    Write-Host " "

Disclaimer: Please read and test script before you run in your production, this reconfigures the preferred owner property at all your clustered VM roles in your cluster !!

There are more options how you can control clustered roles, like “AntiAffinityClass” – when a group is moved during failover, anti-affinity affects the algorithm used to determine the destination node. a.e. never run together at same node…

Here are just a few more good resources around failover options in a Failover Cluster:

Preferred Owners in a Cluster

Failover behavior on clusters of three or more nodes

Understanding Hyper-V Virtual Machine (VM) Failover Policies

Modify the Failover Settings for a Clustered Service or Application

Configure Failover and Failback Settings for a Clustered Service or Application


Using Guest Clustering for High Availability

How to use Powershell in Failover Clustering–Part 1

August 5, 2011

Powershell is a really powerful toy for any Windows administrator where tasks need to be automated and or repeated several times.

Here I would like to start an blog series of how to use Powershell in Windows Server Failover Cluster (WSFC) environments.

Let’s start over with some basic commandlet’s to get status of clustered groups, resources and cluster core resources, move groups and soon. Later we will do some advanced operations with Powershell.

The WSFC Powershell (CLI) interface is everywhere available where WSFC feature is installed:

  • Windows Server 2008 R2 (SP1)
    • Full
    • Core (not installed by default)
  • Microsoft Hyper-V Server 2008 R2 (SP1)
  • Remote Server Administration Tools (RSAT) for Windows 7 (SP1)

First of all, you must import the “FailoverCluster” module to get the commandlet’s. To get a list of all available modules you can use:

PS:\ Get-Module -ListAvailable


To import the module you need to use “Import-Module” commandlet:

PS:\ Import-Module FailoverClusters


YUHUU Smile We have now the full set of all Failover Cluster commandlet’s available, let’s have a look which they are:

PS:\ Get-Command –Module FailoverClusters or Get-Command | findstr Cluster



As you can see, there are for the most of the GUI actions an cmdlet available, sometimes more. In total there are 69 Failover Cluster specific cmdlet’s which gives you many many *creative* usage ways.

NOTE: A really helpful method with Powershell is the Get-Help cmdlet:
Built-in help:
Get-Help cmdlet -Full
Get-Help cmdlet –Examples
Online help (INET connection is required):
Get-Help cmdlet –Online

Let’s start with some easy commandlet to do some basic operations:

How to get a list of all clustered groups via Powershell?

PS:\ Get-ClusterGroup



As you can see I do have some resources offline. Let’s bring them online

How to bring online a Cluster Group via Powershell?

PS:\ Start-ClusterGroup “GROUPNAME” image

Now, let’s move a group to a different node to balance the workloads in my *test* cluster Smile

How to move a cluster group via Powershell?

PS:\ Move-ClusterGroup “GROUPNAME” –Node “NODENAME”


How to get a list of all clustered resources via Powershell?

PS:\ Get-ClusterResource


How to get a list of all clustered groups from an node via Powershell?

PS:\ Get-ClusterNode –Name “NODENAME” | Get-ClusterGroup


How to get a list of all clustered resources within a cluster group via Powershell?

PS:\  Get-ClusterGroup "GROUPNAME" | Get-ClusterResource


How to get more parameters from a clustered disk (resource)?

PS:\ Get-ClusterResource "Cluster Disk 1" | Get-ClusterParameter



How can I test/validate my cluster via Powershell?

Since R2 you can also validate your cluster via CLI Powershell:

PS:\ Get-Help Test-Cluster

A.e.: PS:\ Test-Cluster –Node Node1,Node2



A list of all available Test-Cluster scenarios – which can be *in-/excluded*- can you find here:


Hope this has opened your interest in more around Powershell for Failover Clustering – stay tuned for more or start with playing with PS…..Winking smile

Some additional reference can you find here:

Mapping Cluster.exe Commands to Windows PowerShell Cmdlets for Failover Clusters

PowerShell Quick Reference

Clustering with PowerShell

PowerShell for Failover Clustering: Finding the Drive Letter

PowerShell for Failover Clustering: Understanding Error Codes

PowerShell for Failover Clustering: Frequently Asked Questions


Ramazan Can

Powershell–How to write your own custom functions in Powershell?

May 15, 2011

How to write your own functions within Powershell?

As most of you knows, Powershell is a really powerful toy for administrators which are dealing with a lot of systems. Most of the time, you do same operations and need to write your own scripts. I usually use here the "function" method to build my own Powershell functions which I call later in my script anytime.

Function Example: Enumerate all drives/partitions on a server
function GetDrives
    Get-WmiObject Win32_DiskPartition | select-Object Name, VolumeName, DiskIndex, Index 

Function Example: Start all VMs
function StartVM ([string]$VMName) {
    write-host (‘INFOTEXTBOX: Starting all VM now: ‘+$VMName)
    Get-VM -Suspended $VMName | Start-VM -Force
    Get-VM -Stopped $VMName | Start-VM -Force
    while (!(Get-VM $VMName -Running)) {sleep 1}

Function Example: Cleanup or Remove all VM
function RemoveVM ([string]$VMName) {
    write-host (‘INFO: Remove VMs now:’+$VMName)
    Get-VM $VMName| Remove-VM -force | Out-Null
    while (Get-VM $VMName) {sleep 3}

Function Example: Remove ISO drive from VM
function RemoveISO ([string]$VMName) {
    $DVD=Get-VMDisk $VMName | Where-Object {$_.DriveName -like ‘DVD Drive’} | Where-Object {$_.DiskImage -like ‘*.iso’}
    if ($DVD) {
        ForEach ($actDVD in $DVD) {
            write-host (‘INFO: Remove Mounted ISO from VM ‘+$VMName)
            Remove-VMDrive $VMName -ControllerID $actDVD.ControllerID -LUN $actDVD.DriveLUN -DiskOnly | Out-Null

These are examples for Hyper-V and Cluster Environments where we do utilize command like  “Remove-VMDrive” or “Get-VM” from the Powershell Hyper-V library module from Codeplex or built in Failover Cluster module.

PowerShell: calling a function with parameters

PowerShell Tutorial 10: Functions and Filters

Stay tuned for further PS examples Winking smile



VM MASS DEPLOYMENT with Powershell – Hyper-V

September 12, 2010

As you already know powershell is really useful in several scenarios where you need to automate task operations in windows world. I personally use “Powershell for Hyper-V” often ( especially in mass deployment scenarios where I need to deploy hundreds of virtual machines.

In this blog post I will use the powershell commandlet “NEW-VM” which I had used to create a loop within a script.

The goal here is to deploy, 384 VMs in a automated way 🙂

Therefore I had created an MASTER-VM, which I had installed with all the required application (AV, Apps, Updates.…), tools and finally sysprepped the VM. The exactly command to generalize the VM –> SYSPREP /OOBE /GENERALIZE /SHUTDOWN  .

required preparations:

1. Download and Install Powershell Library from codeplex –>
2. Customize General Parameters in Script like
    – Number of required VMs (a.e. start at 1 and run 384 loops = 384 Vms)
    – Prefix name for your VMs (a.e. W2K8R2-T)
    – customize vRAM and vCPU settings
    – change destination drive where VMs should be created (“V:\”+$vmname)
    – copy your MASTER-VM (sysprepped) and amend location where MASTER-VHD can be found a.e. V:\Master\MASTER_R2.vhd
    – amend disk drive at “ADD-VMDISK” operation a.e. Add-VMDisk $vmname 0 0 (“V:\”+$vmname+”\”+$vmname+”.vhd”)Here we go with our powershell script:

Import-Module hyperv
# Here we import the hyper-v specific hyper-v module which must be downloaded and installed 1st

For ($Counter=1; $Counter -le 384; $Counter++) {
# most important section within this script. Here we define our loop and also how much VMs we want to create here. In my case the loop will start at 1 and run 384 times

# Here we give our VMs an prefix for name which is called in my case “W2K8R2-T” +  counter number = a.e. W2K8R2-T1

# Default VM RAM setting = 1 GB RAM

# Default vCPU setting = 1 vCPU

New-VM -name $vmname -Path (“V:\”+$vmname)
# Now here we call the powershell commandlet “NEW-VM” and point to my drive V:\ where the VMs should be created

Copy V:\Master\MASTER_R2.vhd (“V:\”+$vmname+”\”+$vmname+”.vhd”)
# here we duplicate (copy) the master-VHD to the destination drive (source -> destination)

Set-VM -vm $vmname -bootOrder @(2,1,0,3)
Set-VMMemory -vm $vmname -memory $vmram
Set-VMCPUCount -vm $vmname $vmcpu
Add-VMNIC $vmname
Set-VMNICSwitch -vm $vmname -nic (choose-vmNic $vmname) (choose-VMswitch 0)
Add-VMDrive $vmname 0 0
Add-VMDisk $vmname 0 0 (“V:\”+$vmname+”\”+$vmname+”.vhd”)
# add disk which we had copied earlier to the VMs configuration

Add-VMDrive $vmname 1 0 -DVD
Start-VM $vmname
sleep 30

Now we can go and take us a loonnng break 😉 as the copy time of the MASTER-VHD (depends on size of MASTER.VHD) does take the most of the runtime of the script. My recommendation here would be to use dynamic disks but of course this depends on the performance requirements of disk I/O for these VMs.

PS: Of course there is room for improvements but this blog/script should “only” give you an idea how the powershell library can be used and with your own creativity there is really no borders for creating a customer friendly solution 🙂

If you have any further questions please let me know.



Hyper-V Powershell – Start VMs – Part 2

April 15, 2010

Um diese Reihe weiterzuführen, wende ich mich heute den Möglichkeiten eine Virtuelle Machienen automatisiert via Powershell zu starten.

Das dafür zur Verfügung stehende commandlet “START-VM”, kann in unterschiedlichen Scenarien eingesetzt werden, wie z.b. nach dem automatisierten Backup (Copy/Export) und dann das nachträgliche starten einer VM. Das Thema Backup einer VM werden wir uns dann im nächsten Blog ansehen – stay tuned 🙂Beispiele:Auf dem Hyper-V Server “HOST01” will ich nun VMs starten, die den Status “stopped” haben :Get-VM -server HOST01 -stopped | start-vmAuf dem Hyper-V Server “HOST01” will ich die VM mit dem Namen “VM01” starten :start-vm -server HOST01 -VM VM01 oder Get-VM -server HOST01 -name VM01 | Start-VMEin Script, welches die VM runterfährt, exportiert und dann wieder startet, könnte z.b. dann wie folgt aussehen :get-vm -server HOST01 | Invoke-VMShutdown export-VM -path C:\BACKUP\VM -Server HOST01 -VM VM01 -waitstart-vm -server HOST01 -VM VM01….Viel Spass beim Scripten ;-)Gruß

Hyper-V Powershell – Shutdown VMs – Part 1

March 26, 2010

Da in letzter Zeit die Anfragen in Bezug auf die Nutzung von Powershell für Hyper-V, erhöht haben, werde ich eine neue Serie zum Thema Powershell erstellen.

In erstent Part1, sehen wir uns speziell die Funktion zum herunterfahren einer VM an. Hierzu gibt es die powershell commandlets “Shutdown-VM” oder “Invoke-VMShutdown”. ACHTUNG : Beide commandlets funktionieren nur, wenn die Integration Components installiert sind.


Auf dem Hyper-V Server “HOST01” will ich alle VMs runterfahren, die den Status “running” haben :

Get-VM -server HOST01 -Running | Invoke-VMShutdown

Auf dem Hyper-V Server “HOST01” will ich die VM mit dem Namen “VM01” herunterfahren :

shutdown-vm -server HOST01 -VM VM01 oder Get-VM -server HOST01 -name VM01 | Invoke-VMShutdown

Das commandlet “SHUTDOWN-VM” kann z.b. eingesetzt werden, für automatisierten Backup. (Shutdown VM, Compact (Dynamic) Disk, Export-VM, Start-VM)

Die Powershell Library für Hyper-V kann direkt auf codeplex heruntergeladen werden –>