PowerShell: Mount A Remote SMB/CIFS/NFS Share as a Specific User

This function is useful in scenarios where a separate user account is needed to mount and made it available to the current login user.

# short version

# Input variable to mount remote UNC Path as a local drive
$mountAsUser='domain\account'
$mountAsPassword='somepassword'
$uncPath='\\fileserver\sharename'
$firstAvailableDriveLetter='a'

net use "$firstAvailableDriveLetter`:" "$uncPath" /user:$mountAsUser '$mountAsPassword' /persistent:Yes
# 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
# Longer version

$directory='C:\Temp'
$mountAsDriveLetter='A'
$username=$null
$password=$null

function mountPathAsDrive($path,$driveLetter,$mountAsUser,$mountAsPassword){

  function convertPathToUnc($path,$computername=$env:computername,$credentials=$null){
    $pathIsUnc=$path -match '^\\\\'
    $pathIsReachable=if($credentials){test-path $path -credentials $credentials}else{test-path $path}
    if($pathIsUnc -and $pathIsReachable){
        return $path
    }elseif(!$pathIsUnc){
        $convertedPath=.{
                    $x=$path -replace "^([a-zA-Z])\:","\\$computername\`$1`$";
                    if($x -match '\\$'){return $x.Substring(0,$x.length-1)}else{return $x}
                    }
        $validUnc=if($convertedPath){test-path $convertedPath -ErrorAction SilentlyContinue}else{$false}
        if($validUnc){
            write-host "$path has been converted to $convertedPath, and it is reachable"
            return $convertedPath
        }else{
            write-warning "$path has been converted to $convertedPath, but it is NOT unreachable"
            return $null
        }            
    }else{
        write-warning "Path is invalid"
        return $null
    }
  }

  $pathIsUnc=$path -match '^\\\\'
  $credentials = if($mountAsUser -and $mountAsPassword){
        $password = "$mountAsPassword" | ConvertTo-SecureString -AsPlainText -Force
        New-Object System.Management.Automation.PSCredential ("$mountAsUser", $password )
    }else{
        $null
    }
  $driveLetter=if($driveLetter){
    $driveLetter
  }else{
    $unavailableDriveLetters=(Get-Volume).DriveLetter|sort
    $availableDriveLetters=.{(65..90|%{[char]$_})|?{$_ -notin $unavailableDriveLetters}}
    [char]($availableDriveLetters[0])
  }

  if($pathIsUnc){
    if($credentials){
        $null=net use "$driveLetter`:" "$path" /user:$mountAsUser "'$mountAsPassword'"
    }else{
        $null=net use "$driveLetter`:" "$path"
    }      
  }else{
      $pathAsUnc=convertPathToUnc $path
      if($credentials){
        $null=net use "$driveLetter`:" "$pathAsUnc" /user:$mountAsUser "'$mountAsPassword'"
      }else{
        $null=net use "$driveLetter`:" "$pathAsUnc"
      }
  }

  $reachable=if($credentials){test-path "$driveLetter`:\" -credentials $credentials}else{test-path "$driveLetter`:\"}
  return $(if($reachable){"$driveLetter`:\"}else{$false})
}

mountPathAsDrive $directory $mountAsDriveLetter $mountAsUser $mountAsPassword

Leave a Reply

Your email address will not be published. Required fields are marked *