Skip to content

Instantly share code, notes, and snippets.

@tkuennen
Created January 12, 2023 17:50
Show Gist options
  • Save tkuennen/096ff41cc4ddaf7132f57486383a7cdd to your computer and use it in GitHub Desktop.
Save tkuennen/096ff41cc4ddaf7132f57486383a7cdd to your computer and use it in GitHub Desktop.
# Long version
# Input variable to mount remote UNC Path as a local drive
$mountAsUser='domain\serviceAccount'
$mountAsPassword='somecomplexpassword'
$uncPath='\\server009\share01\public'
# Scan for next available drive letter, excluding D "CD Rom" and H "Home"
$unavailableDriveLetters=(Get-Volume).DriveLetter|sort
$availableDriveLetters=.{(65..90|%{[char]$_})|?{$_ -notin $unavailableDriveLetters}}
[char]$firstAvailableDriveLetter=$availableDriveLetters[0]
function mountDriveAsUser($username,$password,$driveLetter,$uncPath){
if(get-psdrive $driveLetter -ea SilentlyContinue){
#Remove-PSDrive $firstAvailableDriveLetter -ea SilentlyContinue #This does not affect drives being mounted by 'net use' command
net use /delete ($driveLetter+':')
}
try{
# This command cannot persist when out of scope of function; hence, net use is required
# New-PSDrive –Name $mountLetter –PSProvider FileSystem –Root $uncPath –Persist -Credential $mountAsCred|out-null
$result=net use "$driveLetter`:" "$uncPath" /user:$username $password /persistent:Yes
if($result -match 'The command completed successfully.'){
write-host "$driveLetter`: has successfully mounted.";
return $true;
}
else{
return $false
}
}
catch{
write-warning "$error"
return $false
}
}
mountDriveAsUser $mountAsUser $mountAsPassword $uncPath
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment