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

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