Friday, September 26, 2008

Moving my power to other blog

Hi there, fortunately I found out that in the Czech Republic (where I live) is free the domain powershell.cz. Therefore I registered it and moved my power to localization of PS scripts to Czech language. I'll be publishing more posts here but now I'll maily focus to PowerShell.cz.

Saturday, September 6, 2008

Available drive letters

My colleague needed to run subst command and therefore was looking for available drive letters. During the script creating I found out that running simple InStr() function is slower then to use Dictionary object (maybe it's a tip for other blogpost). Anyway I used InStr() because I stopped the script after first match.

Const wbemFlagReturnImmediately = &h10
Const wbemFlagForwardOnly = &h20
Set WshNetwork = WScript.CreateObject("WScript.Network")
Computer = WshNetwork.ComputerName
Set objWMIService = GetObject("winmgmts:\\" & Computer & "\root\CIMV2")
Set colItems = objWMIService.ExecQuery("SELECT * FROM Win32_LogicalDisk", "WQL", wbemFlagReturnImmediately + wbemFlagForwardOnly)

For Each objItem In colItems
Disks = Disks & lcase(left(objItem.DeviceID,1))
Next

For I = 122 To 97 Step -1
Character = Chr(i)
If InStr (Disks, Character) Then
Else
Result = Character
Exit For
End If
Next

WScript.Echo "Available drive letter: " & Result

The script connects to WMI and query all available logical disks. Then is stores the drive letter in string named Disks. As the drive letter is stored in DeviceID in form C: I converted it to lowercase and remove the colon. After the whole WMI part the Disks looks like this: "cdehpvx".

Then in For loop I am going thru alphabet from the end to the beginning (to say it exactly - from 'z' to 'i') and after first non-match exit the loop and return the letter.