I've tried looking for an answer for couple of days with no luck...
I have a powershell (v3.0) script that checks for a Network drive and maps it if it is not already mapped. The script itself works just fine to a certain point, drive is mapped and accessible during script execution but when the script ends, the mapped drive is disconnected. I am using the -Persist option which should preserve the drive mapping.
If I run the same commands from PowerShell prompt the drive is mapped and stays mapped even when exiting PowerShell prompt.
Sample code below
# Drive letter to map to
$destinationDriveLetter = "G"
# Username to map the network drive
$userName = "username"
# Password to use when mapping
$userPass = ConvertTo-SecureString "password" -AsPlainText -Force
#check if Drive is already mapped
if ( Test-Path -LiteralPath $destinationDriveLetter":" -ErrorVariable errVar ) {
Write-Host "Drive already mapped.`r`n"
Write-Host "Exiting script`r`n"
exit
}
Write-Host "Destination Driveletter $destinationDriveLetter not mapped. Doing it...`r`n"
$Credential = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $userName, $userPass
Write-Debug "Command: New-PSDrive -Persist -Name $destinationDriveLetter -PSProvider FileSystem -Root '\\server\share' -Credential $Credential -ErrorVariable errVar"
New-PSDrive -Persist -Name $destinationDriveLetter -PSProvider FileSystem -Root '\\server\share' -Credential $Credential -ErrorVariable errVar
if ( $errVar ) {
Write-Error "`r`nError mapping destination drive $destinationDriveLetter. Check!`r`n"
}
else {
Write-Host "Destination drive mapped successfully.`r`n"
# test if drive truly mapped and destination folder exist
Test-Path -LiteralPath $destinationDriveLetter":" -ErrorVariable errVar
# debugging, roar!
Write-Host "Drives during script:`r`n"
Get-PSDrive
}
# dirty fix to actually confirm that the drive is mapped during script execution
pause
Clearly the issue here is in running the commands in a script but how to fix this? I need to get the drive mapped automatically after server restart. Using UNC paths won't work since the software I'm using doesnt understand them.
EDIT: Forgot to say that OS I'm running is Windows Server 2012
I found that even with the -Persist
parameter the drive mappings would disappear when run from a logon script.
The problem was resolved by adding the -Scope "Global"
parameter as well.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With