tacosnooper
tacosnooper

Reputation: 73

Exporting Net Use results in PowerShell

I have a log off script that saves mapped network shares to a txt file:

#File path for save
$TxtPath = "C:\temp\" + "$env:UserName" + ".txt"

#Clear existing entries in file
Clear-Content -Path $TxtPath

#Return drive letters
$DriveList = Get-PSDrive | Select-Object -ExpandProperty 'Name' | Select-String -Pattern '^[a-b:d-g:i-z]$'

#Get path for each drive letter and save in specific format (letter;path)
Foreach($Item in $DriveList){
$DrivePath = (Get-PSDrive $Item).DisplayRoot
$Entry = -join($Item, ":", ";", $DrivePath)
Add-Content -Path $TxtPath -Value ($Entry)
}

I then have a logon script that resets and maps these drives:

#File path for user drive paths
$TxtPath = "C:\temp\" + "$env:UserName" + ".txt"

#Get current drives
$DriveList = Get-PSDrive | Select-Object -ExpandProperty 'Name' | Select-String -Pattern '^[a-b:d-g:i-z]$'

#Remove current drives
ForEach($Item in $DriveList){
    $Drive = -join($Item, ":")
    net use $Drive /delete
}

#Map network drives from file
ForEach($Line in Get-Content $TxtPath) {
    $DriveLetter,$DrivePath = $Line.split(';')
    net use $DriveLetter $DrivePath
}

My issue is that, because I am using net use to delete and map the drives (in the logon script), that the Get-PSDrive function in the logoff script does not return a drive path. The reason I am using net use over Remove-PSDrive is due to the drive not being fully removed (still shows on the users device).

Is anyone able to tell me how I can capture the Remote Name value for a network share when I look it up using net use (net use Z:)? If I can simply capture this path (and only this path) I will be able to write that to the text file along with the drive letter and thus solve my issue.

I know I can capture the results of net use by saving the data to a file:

net use x: > C:\Temp\output.txt

However I am unable to save this data / single line of required information to a variable. Any help would be much appreciated.

Upvotes: 0

Views: 2373

Answers (1)

boxdog
boxdog

Reputation: 8442

One way to do this is look directly in the registry:

Get-ChildItem "HKCU:Network\" |
    ForEach-Object {
        [PsCustomObject]@{
            DriveLetter = $_.PSChildName
            RemotePath = (Get-ItemProperty $_.PSPath).RemotePath
        }
    }

This will give output like this:

DriveLetter RemotePath                
----------- ----------                
M           \\server1\share1 
N           \\server2\share2   
O           \\server3\share3

To save to file, I'd recommend CSV format by adding this after the last bracket:

| Export-Csv <path>\MappedDrive.csv

You can then easily import the data again with Import-Csv.

Upvotes: 1

Related Questions