Scenario:
I have created a scheduled task that executes the following PowerShell script with the intention of automating mapping a network drive (I have substituted sensitive values in some parts):
Write-Output "Made it to the start of the function" > C:\Temp3\result.txt
$connectTestResult = Test-NetConnection -ComputerName foo.file.core.windows.net -Port 445
if ($connectTestResult.TcpTestSucceeded) {
# Save the password so the drive will persist on reboot
Write-Output "The test connection succeeded" > C:\Temp3\testconnection.txt
cmd.exe /C "cmdkey /add:`"foo.file.core.windows.net`" /user:`"localhost\foo`" /pass:`"storageAccountPassword`"" > C:\Temp3\cmdresult.txt
# Mount the drive
New-PSDrive -Name Z -PSProvider FileSystem -Root "\\foo.file.core.windows.net\foofs" -Scope Global -Persist > C:\Temp3\mapdrive.txt
}
else {
Write-Error -Message 'Unable to reach the Azure storage account via port 445. Check to make sure your organization or ISP is not blocking port 445, or use Azure P2S VPN, Azure S2S VPN, or Express Route to tunnel SMB traffic over a different port.'
}
Problem:
I can execute the script "successfully", however the mapped drive does not persist. For example, if I open a new Windows Explorer window after it runs, I cannot see the drive. However, I can browse to the UNC path manually without having to authenticate?
What I have tried:
If I run the script manually (e.g. from PowerShell ISE), it works perfectly and I can see the mapped drive (Z:) via Windows Explorer. As you can see from the script, I have added some logging to verify the output of each command. I cannot see any errors. Is there something obvious I am missing? I have also dot sourced the script within the scheduled task action (something advised on https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.management/new-psdrive?view=powershell-7.3):
e.g.
. C:\Temp3\mapNetworkFileShare.ps1