How to remotely map a network share with powershell

Having ongoing issues determining where the issue is with a certain user who for one reason or another, either loses the mappings to a network share, or just does not receive them.

And so, with no time for them to assist you with troubleshooting and needing a quick fix. I decided to work out an alternative method of getting the network shares mapped with minimal effort.

So i turned to the mighty powershell.

So what will you need to make this script work for you?
1 – The target computer name
2 – The target drive letter you want to map the share to
3 – The location of the share that you want to map to the drive letter.

Below is an image of the code with comments on the lines that you will need to make changes to with your desired variables. The source code is also below.

Script to remotely map network drives

#####! Computer name for the user who needs this drive mapped #####!
$ComputerName = "LENOVOPC01"
# Get users that are logged in
$Sessions = Get-WmiObject -ComputerName $ComputerName -Class win32_process | Where-Object {$ -eq "explorer.exe"}
# Get SID of users
$sid = $Sessions.GetOwnerSid().sid
# See which user is being modified
$user = $Sessions.GetOwner().user
Invoke-Command -ComputerName $ComputerName {
    $sid = $Using:sid 
    #####! What drive do you want to map the share to? #####!
    $DriveLetter = "p"
    #####! What is the location of the share you want to map? #####!
    $DrivePath = "\\companya\files\Commercial\"
    $Path = "REGISTRY::HKEY_USERS\$sid\Network"

    New-Item -Path $Path -Name $DriveLetter
    New-ItemProperty -Path $Path\$DriveLetter\ -Name ConnectFlags -PropertyType DWORD -Value 0
    New-ItemProperty -Path $Path\$DriveLetter\ -Name ConnectionType -PropertyType DWORD -Value 1
    New-ItemProperty -Path $Path\$DriveLetter\ -Name DeferFlags -PropertyType DWORD -Value 4
    New-ItemProperty -Path $Path\$DriveLetter\ -Name ProviderName -PropertyType String -Value "Microsoft Windows Network"
    New-ItemProperty -Path $Path\$DriveLetter\ -Name ProviderType -PropertyType DWORD -Value 131072
    New-ItemProperty -Path $Path\$DriveLetter\ -Name RemotePath -PropertyType String -Value "$DrivePath"
    New-ItemProperty -Path $Path\$DriveLetter\ -Name UserName -PropertyType String


Leave a Reply

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