# Using Test-Path instead of Get-PSDrive and trying to map the drive without and then with credentials makes sure the script works in all circumstances:
# also when the drive was already mapped in Windows Explorer or in a PowerShell remoting session
# We map the drive with -Perist to make sure the drive is mapped in the Windows file explorer as well. Without -Persist the drive is only available in PowerShell.
# The -Scope Global parameter is used to make sure the drive is available outside of this script as well
$sharePath = "\\server\share\optional-path"
$mapDrive = "Z"
if(-not (Test-Path "${mapDrive}:")) {
# try to map the network drive without asking for credentials; this works on a local PowerShell session
New-PSDrive -Name $mapDrive -Root $sharePath -Persist -Scope Global -PSProvider "FileSystem" -ErrorAction SilentlyContinue | Out-Null
}
if(-not (Test-Path "${mapDrive}:")) {
# ask for credentials; we need this when the current user does not have rights to use the network share, or when on a PowerShell remoting session
New-PSDrive -Name $mapDrive -Root $sharePath -Persist -Scope Global -PSProvider "FileSystem" -Credential (whoami) | Out-Null
}
if(Test-Path "${mapDrive}:") {
# Show how the Z drive is mapped
Get-PSDrive $mapDrive | Select-Object -Property @('Root', 'DisplayRoot')
}