Mapping Network Drives Using PowerShell and SID

Overview

In this post, I'll walk you through the process of mapping a network drive using PowerShell and a Security Identifier (SID), which uniquely identifies a user in Windows. The primary benefit of this method is that it allows you to perform the operation without being logged in as the specific user.

PowerShell Script

 1# Variables
 2$networkDriveLetter = "Z:"
 3$networkPath = "\\servername\sharename"
 4$userSID = "S-1-5-21-xxxxxxxxxx-xxxxxxxxxx-xxxxxxxxx-xxxx" # Replace with the user's SID
 5$netUseKeyPath = "Registry::\HKEY_USERS\$userSID\Network\$($networkDriveLetter.TrimEnd(':'))"
 6
 7# Check if network drive registry key already exists
 8if(Test-Path -Path $netUseKeyPath) {
 9    Write-Host "The network drive is already mapped in the registry."
10} else {
11    # Create new registry keys for mapping network drive
12    New-Item -Path $netUseKeyPath -Force
13    New-ItemProperty -Path $netUseKeyPath -Name RemotePath -Value $networkPath -PropertyType String -Force
14    New-ItemProperty -Path $netUseKeyPath -Name UserName -Value "" -PropertyType String -Force # Empty, as this will use the user's current logon credentials
15    New-ItemProperty -Path $netUseKeyPath -Name ProviderName -Value 'Microsoft Windows Network' -PropertyType String -Force
16    New-ItemProperty -Path $netUseKeyPath -Name ConnectionType -Value 1 -PropertyType DWord -Force
17
18    Write-Host "Network drive mapped successfully in the registry."
19}

Please remember to replace "S-1-5-21-xxxxxxxxxx-xxxxxxxxxx-xxxxxxxxx-xxxx" with the SID of the user you're modifying the registry for.

Obtaining the User's SID

If you're unsure about how to get the user's SID, you can use the following PowerShell command:

1$objUser = New-Object System.Security.Principal.NTAccount("domainname", "username")
2$strSID = $objUser.Translate([System.Security.Principal.SecurityIdentifier])
3$strSID.Value

Replace "domainname" and "username" with the respective values for your user.

Alternatively, this can be condensed into a one-liner:

1(New-Object System.Security.Principal.NTAccount("domainname", "username")).Translate([System.Security.Principal.SecurityIdentifier]).Value

Post Mapping Procedure

Be aware that post mapping, the network drive will not be instantly accessible to the user. Visibility is only updated after the user has logged out and back in again, or after manually terminating the explorer.exe task and restarting it.