1

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
mklement0
  • 382,024
  • 64
  • 607
  • 775
  • When using file explorer as an Admin you need to use a dollar sign instead of a colon to have Admin rights. So when you check the drive use z$. Also need to use the -Persist option : https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.management/new-psdrive?view=powershell-7.3 – jdweng Dec 21 '22 at 03:05
  • The $ sign doesnt mean "admin rights". It signifies a hidden (administrative) share/drive. Drive rights are controlled by permissions/ACL – Scepticalist Dec 21 '22 at 08:55

1 Answers1

0

You can try this:

New-ItemProperty -Path 'HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System' -name EnableLinkedConnections -value 0x1

The following link from Microsoft provides the explanation

Mike
  • 33
  • 4