I've been trying to wrap my brain around this behaviour for a while.
I have a PowerShell script within a module that's supposed to map a drive, then open it in file explorer.
The mapping part works, but it falls over when trying to open the drive with the error:
ii : Cannot find drive. A drive with the name 'L' does not exist. At line:41 char:9 + ii "$($global:mapping_letter):" + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : ObjectNotFound: (L:String) [Invoke-Item], DriveNotFoundException + FullyQualifiedErrorId : DriveNotFound,Microsoft.PowerShell.Commands.InvokeItemCommand
Strangely, running the final command ii "$($global:mapping_letter):"
directly after running the script seems to work without issue. I thought that the net use
command might be async and tried using Start-Sleep
before the ii
command, but this prevents the drive from even mapping until it's woken up again.
Code as below:
function MapDrive {
Param(
[Parameter(Mandatory=$true,Position=0)]
[string] $DrivePath,
[Parameter(Mandatory=$false,Position=1)]
[int] $notadmin,
[Parameter(Mandatory=$false,Position=2)]
[int] $disp
)
if (($admin-eq 0) -or ($admin-eq $null)) {
if (-not $adminCredential) {
GetadminCredentials
}
}
#Find an available letter to map with
[array]$letters = "A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"
$currentdrives = Get-PSDrive
foreach ($letter in $letters) {
if ($letter -notin $currentdrives.Name) {
[array]$potential_letters += $letter
}
}
$global:mapping_letter = $potential_letters | Get-Random -Count 1
#Map the Drive
$Uri = New-Object System.Uri($DrivePath)
$IpAddress = Test-Connection ($Uri.Host) -Count 1 | Select -Expand IPV4Address | %{$_.ToString()}
$PathName = $Uri.LocalPath -Replace $Uri.Host, $IpAddress
#Remove Any Current Mapped Drive
if (Test-Path "$($global:mapping_letter):") {
Remove-PsDrive -Name $($global:mapping_letter) -PSProvider FileSystem -Scope Global -Force | Out-Null
Start-Sleep -m 500
}
#Map the New Drive
if (($notadmin -eq 0) -or ($notadmin -eq $null)) {
#New-PsDrive -Name $($global:mapping_letter) -PSProvider FileSystem -Root $PathName -Credential $adminCredential -Scope Global -Persist | Out-Null
net use "$($global:mapping_letter):" $PathName /user:$($adminCredential.username) /persistent:no | Out-Null
} elseif ($notadmin -eq 1) {
#New-PsDrive -Name $($global:mapping_letter) -PSProvider FileSystem -Root $PathName -Scope Global -Persist | Out-Null
net use "$($global:mapping_letter):" $PathName /persistent:no | Out-Null
}
if (($disp -eq 1) -or ($disp -eq $null)) {
ii "$($global:mapping_letter):"
}
}