powershell - Find Available Drive Letter and Change -
i trying create powershell script find available drive letter, map network drive, , change mapped drive. found following mapped \\server\share
d:
drive:
$drive = new-psdrive -name $(for($j=67;gdr($d=[char]$j++)2>0){}$d) -psprovider filesystem -root \\server\share\
i can manually enter d:
, how can change in script? thinking along lines of this:
$drive = $drive.trim(":")
but statement above throws following error:
method invocation failed because [system.management.automation.psdriveinfo] not contain method named 'trim'. @ line:1 char:1 + $drive = $drive.trim(":") + ~~~~~~~~~~~~~~~~~~~~~~~~~ + categoryinfo : invalidoperation: (:) [], runtimeexception + fullyqualifiederrorid : methodnotfound
you check list of potential drive letters against list of assigned drive letters , use first unused one:
$used = get-psdrive | select-object -expand name | where-object { $_.length -eq 1 } $drive = 90..65 | foreach-object { [string][char]$_ } | where-object { $used -notcontains $_ } | select-object -first 1 new-psdrive -name $drive -psprovider filesystem -root \\server\share set-location "${drive}:"
or random 1 list:
$used = get-psdrive | select-object -expand name | where-object { $_.length -eq 1 } $unused = 90..65 | foreach-object { [string][char]$_ } | where-object { $used -notcontains $_ } $drive = $unused[(get-random -minimum 0 -maximum $unused.count)] new-psdrive -name $drive -psprovider filesystem -root \\server\share set-location "${drive}:"
Comments
Post a Comment