powershellnetwork-drive

PShell script works in ISE, but when running .ps1


I wrote a script to map a Network Drive (NAS) if not mapped, or unmap it if mapped.

# NAS.ps1
If (!(Test-Path N:)) {
    $User = "User"
    # Pwd in script will be removed later
    $Pwd = ConvertTo-SecureString -String "Password" -AsPlainText -Force
    
    $Credential = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $User, $Pwd

    New-PSDrive -Name "N" -PSProvider "FileSystem" -Root "\\192.168.1.100\NAS" -Persist -Credential $Credential
} else {
    Remove-PSDrive -Name "N"
}

I edit it using the Windows Powershell ISE. When I run it, I see the drive appearing or disappearing in my Windows Explorer window. That's perfect.

Run with Powershell

However, when I right click NAS.ps1 > "Run with Powershell", the PS window quickly appear/disappear and the drive is neither mapped/unmapped (nothing changes).

Run Powershell, then ./NAS.ps1

If I try to run Powershell, cd to the folder with my scripts, and run it manually, it keeps mounting the drive:

PS C:\Users\User\Desktop> .\NAS.ps1

Name           Used (GB)     Free (GB) Provider      Root                                               CurrentLocation
----           ---------     --------- --------      ----                                               ---------------
N                1150.44       3201.81 FileSystem    \\192.168.1.100\NAS

PS C:\Users\User\Desktop> .\NAS.ps1

Name           Used (GB)     Free (GB) Provider      Root                                               CurrentLocation
----           ---------     --------- --------      ----                                               ---------------
N                1150.44       3201.81 FileSystem    \\192.168.1.100\NAS

Run Powershell as Admin., then ./NAS.ps1

If I launch Powershell as an administrator, and run my scripts, nothing is shown:

PS C:\Windows\system32> cd C:\Users\User\Desktop
PS C:\Users\User\Desktop> .\NAS.ps1
PS C:\Users\User\Desktop> .\NAS.ps1
PS C:\Users\User\Desktop> .\NAS.ps1

Using Get-PSDrive it appear as mounted, I can cd into it, but from the Win. Explorer window it does not appear


Solution

  • The solution was to use -Scope Global when mapping the drive, and to use net use to un map it.

    Working code:

    # NAS
    Set-StrictMode -Version 2.0
    If (!(Test-Path N:)) {
    
        $User = "user"
        $Pswd = ConvertTo-SecureString -String "Password" -AsPlainText -Force
    
        $Credential = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $User, $Pswd
    
         New-PSDrive -Name "N" -Root "\\192.168.1.100\NAS" -Credential $Credential -PSProvider "FileSystem" -Persist -Scope Global
    } else {
        Net Use "N:" /delete
    }