Script Library

Reviewed PowerShell Automation

Map a Network Drive

Validates a UNC path and maps it to an available drive letter with an optional persistent sign-in mapping.

ConfigurationWindowsPowerShellModerate riskStandard userDry-run documented

What it does

  • Validates the requested drive letter is available
  • Tests whether the UNC path is reachable
  • Creates only the requested mapping after confirmation

Required inputs

-DriveLetter Required

One unused letter from D through Z.

-NetworkPath Required

Approved UNC path such as \\server\share.

-Persist Optional

Keeps the mapping across future sign-ins.

What it changes

  • Adds a network-drive mapping for the current user
  • Can persist the mapping across sign-ins when -Persist is supplied
Complete source
Read the entire script before copying or downloading it.
[CmdletBinding(SupportsShouldProcess=$true, ConfirmImpact="Medium")]
param(
    [Parameter(Mandatory=$true)][ValidatePattern("^[D-Zd-z]$")][string]$DriveLetter,
    [Parameter(Mandatory=$true)][ValidatePattern("^\\\\[^\\]+\\[^\\]+")][string]$NetworkPath,
    [switch]$Persist
)
$ErrorActionPreference = "Stop"
$name = $DriveLetter.ToUpperInvariant()
if (Get-PSDrive -Name $name -ErrorAction SilentlyContinue) { throw "Drive $name`: is already in use. Choose another letter." }
if (-not (Test-Path -LiteralPath $NetworkPath)) { throw "The network path is unavailable or this account does not have access: $NetworkPath" }
$description = if ($Persist) { "Create persistent network-drive mapping" } else { "Create network-drive mapping for this session" }
if ($PSCmdlet.ShouldProcess("$name`: -> $NetworkPath", $description)) {
    New-PSDrive -Name $name -PSProvider FileSystem -Root $NetworkPath -Persist:$Persist -Scope Global -ErrorAction Stop | Format-Table Name, Root, Description
    Write-Host "To remove this mapping later, run: Remove-PSDrive -Name $name"
}