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
https://weblogs.asp.net/soever/archive/2006/11/29/powershell-calling-a-function-with-parameters.aspx

PowerShell Tutorial 10: Functions and Filters
https://www.powershellpro.com/powershell-tutorial-introduction/powershell-functions-filters/

Stay tuned for further PS examples Winking smile

Regards

Ramazan

Comments

  • Anonymous
    September 22, 2011
    Thanks for posting the example scripts. I wonder if you have any inputs on handling non-english version of OS. "DVD Drive" could be localized. I'm curios. I'm using following to detect vm with physical diskPS C:UsersAdministrator> $HDs=Get-vm -Name VMWithPhyDisk | get-vmdiskPS C:UsersAdministrator> $HDs[1]DriveName : Passthrough DiskDiskPath : Physical drive: Disk 6 1536.00 GB Bus 0 Lun 0 Target 5DiskImage : Physical drive: Disk 6 1536.00 GB Bus 0 Lun 0 Target 5DiskName : Hard DriveDiskInstanceID : Microsoft:4BC86DEF-398D-46D5-8E36-EB00FDE23A2E83F8638B-8DCA-4152-9EDA-2CA8B33039B41DHow can grep for "Passthrough Disk" in non-english version of OS.