I’ve been working on some WMI functions for disks recently. First off setting the disk drive letter.
function set-driveletter { [CmdletBinding()] param ( [string]$computer=".", [parameter(Mandatory=$true)] [string] [ValidatePattern("^[A-Z]{1}:{1}`$")] $olddrive, [parameter(Mandatory=$true)] [string] [ValidatePattern("^[A-Z]{1}:{1}`$")] $newdrive ) Get-WmiObject -Class Win32_Volume -ComputerName $computer -Filter "DriveLetter='$olddrive'" | Set-WmiInstance -Arguments @{DriveLetter=$newdrive} }
The difficult bit was getting the regular expression correct. It tests that we have a single letter and a colon. The old and new drives are mandatory parameters
Simple call to Get-WmiObject and pipe to Set-WmiInstance.
Use it like this:
set-driveletter -olddrive z: -newdrive i:
Jobs a good un.
under: PowerShell and WMI
By: Chris Warwick on August 6, 2011 at 5:49 am
Hi Richard,
In the regex you don’t need to put a count of 1 (that’s implicit if you don’t specify a repetition (or use *, +, ?))
Also, use single quotes to avoid problems with the $:
‘^[A-Z]:$’
…will do it.
Cheers,
Chris
By: RichardSiddaway on August 7, 2011 at 3:49 am
Thanks Chris
The single quotes I remembered after I’d posted.
I prefer to use the counter because it helps me remember what the regex is supposed to do. I still don’t like regex & only use it when I have to