Reputation: 53
I am creating a mapped network drive with a random letter like this:
$drive = Get-ChildItem function:[f-z]: -n | Where { !(Test-Path $_) } | select -First 1
$PsDrive = New-PSDrive -Name ($drive)[0] -PSProvider "FileSystem" -Root $somePath
This code works fine. I have a problem when want to remove the newly created mapped drive at the end of my script. How I do it:
$someEnv = Remove-PSDrive -Name $drive
The problem here is that $drive adds the colon after the name ':'. For example if $drive is called M, it will be "M:" and Remove-PsDrive fails.
Probably it will be removed automatically when the session is over, but I want to remove it explicitly.
Do you guys have an idea how I can remove this drive?
Thanks
Upvotes: 0
Views: 652
Reputation: 7479
here is another, somewhat different way to do it that uses just powershell. [grin]
what it does ...
F
thru Z
.'F'[0]
to convert the letter string to a character'F'..'Z'
. [grin] the code ...
$CandidateDriveLetters = [char[]]('F'[0]..'Z'[0])
$InUseDriveLetters = (Get-PSDrive -PSProvider FileSystem).Name
$1stAvailableDL = ($CandidateDriveLetters |
Where-Object {
$_ -notin $InUseDriveLetters
})[0]
$TargetDriveRoot = $env:TEMP
$NewDrive = New-PSDrive -Name $1stAvailableDL -PSProvider FileSystem -Root $TargetDriveRoot
$NewDrive.Name
'=' * 30
Get-ChildItem -Path ('{0}:' -f $NewDrive.Name) |
Select-Object -First 3
'=' * 30
Remove-PSDrive -Name $NewDrive.Name
(Get-PSDrive -PSProvider FileSystem).Name
output ...
H
==============================
Directory: C:\Temp
Mode LastWriteTime Length Name
---- ------------- ------ ----
d----- 2020-04-21 6:39 PM 2ccdytd4
d----- 2020-04-21 6:39 PM 30u23uyw
d----- 2020-04-21 6:39 PM 55zoq3fj
==============================
C
D
E
F
G
R
S
Z
Upvotes: 2
Reputation: 486
You can remove the ':' from the $drive variable using Replace
$drive.Replace(':','')
So your code to remove the drive looks like this
$someEnv = Remove-PSDrive -Name $drive.Replace(':','')
Upvotes: 1