Oltre al semplice NET USE, in PowerShell è possibile usare il ComObject “WScript.Network” per gestire la mappatura di un disco di rete (map network drive).

Questo semplice script serve per mappare un disco di rete e per rimuovere la mappatura:

Write-Host "] Mapping Network Drive . . ."

# Credentials
$serverName = 'TESTPC01'
$userName = 'TESTPC01\Administrator'
$serverPwdSec = Read-Host -assecurestring "] Server password" # Ask for the user password
$serverPwd = [System.Runtime.InteropServices.Marshal]::PtrToStringAuto([System.Runtime.InteropServices.Marshal]::SecureStringToBSTR($serverPwdSec))

$network = New-Object -ComObject WScript.Network

try {
    # Previous method: NET USE T: \\$serverName\folderTest /USER:$userName $serverPwd
    $network.MapNetworkDrive("T:", "\\$serverName\folderTest", $false, "$userName", "$serverPwd")
    # $network.MapNetworkDrive("T:", "\\$serverName\folderTest") # Without credential
    Write-Host "] Network Drive mapped!`n" -BackgroundColor Green -ForegroundColor Black;
} catch {
    Write-Host "[An error occurred in drive mapping!]" -BackgroundColor Red -ForegroundColor Black;
    Write-Host "[Error message:" $_.Exception.Message "`n" -BackgroundColor Red -ForegroundColor Black;
}
Write-Host "] Remove Network Drive . . ."

try {
    $network.RemoveNetworkDrive("T:")
    # Previous method: NET USE T: /delete
} catch {
    Write-Host "[An error occurred in drive unmapping!]`n" -BackgroundColor Red -ForegroundColor Black;
}