title: Mapped network drive via New-PSDrive disappears after exiting powershell script
body: <p>I've tried looking for an answer for couple of days with no luck...</p>
  
  <p>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.</p>
  
  <p>If I run the same commands from PowerShell prompt the drive is mapped and stays mapped even when exiting PowerShell prompt.</p>
  
  <p>Sample code below</p>
  
  <pre><code># 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
  </code></pre>
  
  <p>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.</p>
  
  <p>EDIT: Forgot to say that OS I'm running is Windows Server 2012</p>