Created
January 12, 2023 17:50
-
-
Save tkuennen/096ff41cc4ddaf7132f57486383a7cdd to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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