Simple Mount:
# Mapping a drive
$username='domain\testAdmin'
$password='PASSWORD'
$remotePath='\\UNCSERVER\SHAREPATH\Backup'
$unavailableDriveLetters=(Get-Volume).DriveLetter|sort
$availableDriveLetters=.{(65..90|%{[char]$_})|?{$_ -notin $unavailableDriveLetters}}
[char]$firstAvailableDriveLetter=$availableDriveLetters[0]
$command="net use $firstAvailableDriveLetter`: $remotePath $password /USER:$username /persistent:Yes"
write-host $command
Invoke-Expression $command
# Copying a file
$localFile='X:\backup\TEST_DB.bak'
robocopy $(split-path $localFile -parent) "$firstAvailableDriveLetter`:\" $(split-path $localFile -leaf)
# Removing mapped drive
net use /del "$firstAvailableDriveLetter`:" /y
Copying a Script File:
$remoteFile='\\REMOTESERVER\C$\Scripts\somescripts.ps1'
$localPath='C:\Scripts'
$remoteAdminUser='REMOTESERVER\Admin'
$remoteAdminPass='WHATPASSWORD'
$remotePath=split-path $remoteFile -parent
# Try to copy file from remote UNC path to Local. If that fails, then perform the mount drive method
try{
Import-Module bitstransfer
Start-BitsTransfer -Source $scriptFile -Destination $localPath -Credential $adminCredential -ea Stop
}catch{
# Option 1: deterministic method of discovering unavailable drive letters
# $unavailableDriveLetters=(Get-Volume).DriveLetter|sort # This only works on Windows 8/2012 or higher
$unavailableDriveLetters=(Get-WmiObject -Class Win32_Volume).DriveLetter|sort
$availableDriveLetters=.{(65..90|%{[char]$_})|?{"$_`:" -notin $unavailableDriveLetters}}
[char]$firstAvailableDriveLetter=$availableDriveLetters[0]
net use $firstAvailableDriveLetter $remotePath /USER:$user "$password" /persistent:Yes 2>&1>null
Copy-Item $remoteFile $localPath
}
# Option 2: Blanket test path approach, which will yield False Positives with read-only drives such as CD-ROM
# This is backward compatible to PowerShell 3.0
#[char]$firstAvailableDriveLetter=.{$letters=(65..90|%{[char]$_});foreach ($letter in $letters){if(!(test-path "$letter`:")){return $letter} }}
#net use $firstAvailableDriveLetter $remotePath /USER:$user "$password" /persistent:Yes 2>&1>null
Categories: