What if you needed to map network drives during log-on? You could use fixed drive letters, but what if those drive letters are already in use? Here is a clever way of finding available drive letters:
function Get-NextFreeDrive {
68..90 | ForEach-Object { "$([char]$_):" } |
Where-Object { 'h:', 'k:', 'z:' -notcontains $_ } |
Where-Object {
(new-object System.IO.DriveInfo $_).DriveType -eq 'noRootdirectory'
}
}
68..90 | ForEach-Object { "$([char]$_):" } |
Where-Object { 'h:', 'k:', 'z:' -notcontains $_ } |
Where-Object {
(new-object System.IO.DriveInfo $_).DriveType -eq 'noRootdirectory'
}
}
It starts by enumerating ASCII codes for letters D: through Z:. The pipeline will then convert those ASCII codes into drive letters. Next, check out how the pipeline uses an exclusion list with drives you do not want to use for mapping (optional). In this example, drive letters h:, k:, and z: are never used. Finally, the pipeline uses a .NET DriveInfo object to check whether the drive is in use or not.
Try this to get the first available drive letter for drive mapping:
net use (Get-NextFreeDrive)[0] '\\127.0.0.1\c$'