Get-RemoteMappedDrive.psm1

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
$moduleDefinition =
{
    Function GetUsersList()
    {
            Param([String]$ComputerName)
                 
                #Open HKLM Key.
                $Reg = [Microsoft.Win32.RegistryKey]::OpenRemoteBaseKey('LocalMachine', $ComputerName)
                $RegPath = "Software\Microsoft\Windows NT\CurrentVersion\ProfileList";
                $RegKey= $Reg.OpenSubKey($RegPath);

                $userList = @();

                #Enumerate User Profiles
                ForEach($Profile in $RegKey.GetSubKeyNames())
                {
                    #GetSID
                    $SID = $Profile.ToString()

                    #GetUsername
                    $subkey = $RegKey.OpenSubKey($Profile)
                    $bytes = [System.Text.Encoding]::Ascii.GetBytes($subkey.GetValue("ProfileImagePath")) 
                    $username = ([System.Text.Encoding]::ASCII.GetString($bytes)).Split("\")[2]

                    #Create a psobject (associative array) and assign values.
                    $item = New-Object psobject
                    $item | Add-Member -NotePropertyName "ComputerName" -NotePropertyValue $ComputerName
                    $item | Add-Member -NotePropertyName "SID" -NotePropertyValue $SID
                    $item | Add-Member -NotePropertyName "USERNAME" -NotePropertyValue $username

                    $userList += $item;
            }
            return $userList;
    }

    Function GetMappedDrives()
    {    
        Param([String]$ComputerName)
         
        $DrivesScanResults = @()
        $userList = GetUsersList -ComputerName $ComputerName

        ForEach($UserProfile in $userList)
        {
                    try
                    {
                        #Open User's Registry Hive.
                        $Reg = [Microsoft.Win32.RegistryKey]::OpenRemoteBaseKey('Users', $UserProfile.ComputerName)
                        $RegPath = "$($UserProfile.SID)\NETWORK";
                        $RegKey= $Reg.OpenSubKey($RegPath);
                    }
                    catch
                    {
                        continue;
                    }

                    #If the key is not null.
                    if($RegKey)
                    {
                        #Iterate over all subkeys.
                        ForEach($key in $RegKey.GetSubKeyNames())
                        {
                            try
                            {
                                $DriveKey = $Reg.OpenSubKey("$($RegPath)\$($key)");

                                #Create a psobject (associative array) and assign values.
                                $item = New-Object psobject;
                                $item | Add-Member -NotePropertyName "ScanDate" -NotePropertyValue (Get-Date -Format yyyy-MM-dd-HH-mm-ss).ToString() 
                                $item | Add-Member -NotePropertyName "UserName" -NotePropertyValue $UserProfile.USERNAME;
                                $item | Add-Member -NotePropertyName "SID" -NotePropertyValue $UserProfile.SID;
                                $item | Add-Member -NotePropertyName "ComputerName" -NotePropertyValue $UserProfile.ComputerName;
                                $item | Add-Member -NotePropertyName "Letter" -NotePropertyValue $key;
                                $item | Add-Member -NotePropertyName "RemotePath" -NotePropertyValue $DriveKey.GetValue("RemotePath");
                                                              
                                #Append to the array of Results.
                                $DrivesScanResults += $item;
                            }
                            catch
                            {
                                continue;
                            }
                        }
                    }

                    if($Reg)
                    {
                        $Reg.Close();
                    }
                    else
                    {
                        #nothing;
                    }
            
        }
        return $DrivesScanResults;
    }
}

Function PrintStatus()
{
    Param([int]$NumOfItems,
    [Parameter(Mandatory = $false)][int]$runningjobsCount)

    $completedjobs = (get-job -State Completed).Count

    if(!$runningjobsCount)
    {
        $runningjobsCount = (get-job -State Running).Count
    }

    Write-Host "[Running Jobs: $($runningjobsCount)]/[Completed Jobs: $($completedjobs)])" 
}

Function ThrottleJobs()
{
    Param([Parameter(Mandatory=$true)][int]$NumOfItems,
    [Parameter(Mandatory=$true)][int]$maxConcurrentJobs,
    [Parameter(Mandatory=$true)][int]$timeLimitperJob)

    while((Get-Job -State Running).Count -ge $maxConcurrentJobs)
    {               
        $runningjobs = get-job -State Running

        PrintStatus -NumOfItems $NumOfItems

        foreach($job in $runningjobs)
        {
            #dispose of jobs that are stuck. Time limit is defined at start of script.
            if(((get-date).AddMinutes(-$timeLimitperJob) -ge $job.PSBeginTime))
            {
                $job.StopJob();
                $job.Dispose();
            }
        }
        start-sleep 1
    }
}

function WaitforCompletion()
{
    Param([Parameter(Mandatory=$true)][int]$NumOfItems,
    [Parameter(Mandatory=$true)][int]$timeLimitperJob,
    [Parameter(Mandatory=$true)][bool]$showStatus)

    #Wait for running jobs to complete.
    while(get-job -State Running)
    {
        $runningjobs = (get-job -State Running)

        if($showStatus)
        {
            PrintStatus -NumOfItems $NumOfItems -runningjobsCount ($runningjobs).Count
        }

        foreach($job in $runningjobs)
        {
            #dispose of jobs that are stuck. Time limit is defined at start of script.
            if(((get-date).AddMinutes(-$timeLimitperJob) -ge $job.PSBeginTime))
            {
                $job.StopJob();
                $job.Dispose();
            }
        }
        Start-Sleep 1
    }
}

Function CancelOutStandingJobs()
{
    $runningjobs = get-job -State Running

    foreach($job in $runningjobs)
    {
        $job.StopJob();
        $job.Dispose();
    }
    get-job | remove-job
}

Function Get-RemoteMappedDrive()
{
<#
        .SYNOPSIS
        Enumerate user profiles on local and remote computers, and retrieve the users' mapped drives.
 
        .DESCRIPTION
        Enumerate user profiles on local and remote computers, and retrieve the users' mapped drives.
 
        Author: Richard West
 
        Contact: richard@premiumsource.solutions
 
        .INPUTS
        [String[]] #Computer Name(s).
 
        .OUTPUTS
        [PSOBJECT]
            #Properties:
                [String]ScanDate #Format yyyy-MM-dd-HH-mm-ss
                [String]UserName
                [String]SID
                [String]ComputerName
                [String]Letter
                [String]RemotePath
 
        .PARAMETER ComputerList
        String, or String[] of computer names.
 
        .PARAMETER maxConcurrentJobs
        [int]Max number of allowed parallel background jobs. Default value is 20.
 
        .PARAMETER timeLimitperJob
        [int]Max number of minutes allowed for each background job. Jobs that exceed threshold are cancelled. Default value is 1.
 
        .PARAMETER showStatus
        [switch]Write scan status to console.
 
        .EXAMPLE
        Get All Users' Mapped Drives on Computer, "MyComputerName". Format output as a table.
     
        PS> Get-RemoteMappedDrive -ComputerName "MyComputerName"| Select-Object UserName, ComputerName, Name, Value, ScanDate | Format-Table
 
 
        .EXAMPLE
        Get All Users' Mapped Drives on Computers, "ComputerName1" and "ComputerName2".
     
        PS> Get-RemoteMappedDrive -ComputerName "ComputerName1", "ComputerName2" | Select-Object UserName, ComputerName, Name, Value, ScanDate | Format-Table
 
 
        .EXAMPLE
        Get All Users' Mapped Drives on Computers, "ComputerName1" and "ComputerName2". Export to CSV.
     
        PS> Get-RemoteMappedDrive -ComputerName "ComputerName1", "ComputerName2" | Select-Object UserName, ComputerName, Name, Value, ScanDate | Export-CSV -NoTypeInformation -Path "$($PSScriptRoot)\drives.csv"
 
 
        .EXAMPLE
        Get All Users' Mapped Drives on Computers, "ComputerName1" and "ComputerName2". Configure [int]maxConcurrentJobs and [int]timeLimitperJob.
     
        PS> Get-RemoteMappedDrive -ComputerName "ComputerName1", "ComputerName2" -maxConcurrentJobs 10 -timeLimitperJob 2
 
        .EXAMPLE
        Pipe computer names into Get-RemoteMappedDrive
     
        PS> $ComputerList = "Computer1", "Computer2", "Computer3"
        PS> $ComputerList | Get-RemoteMappedDrive -showStatus
 
        .LINK
        Project URI: 'https://github.com/richardwestseattle/Get-RemoteMappedDrive'
        Website: 'http://premiumsource.solutions'
        Contact: 'richard@premiumsource.solutions'
 
#>



    [cmdletbinding()]

    Param([Parameter(Mandatory=$true,ValueFromPipelineByPropertyName = $True)][Alias('Computer','MachineName','NetBiosName')][String[]]$ComputerName,
    [Parameter(Mandatory=$false)][int]$maxConcurrentJobs,
    [Parameter(Mandatory=$false)][int]$timeLimitperJob,
    [switch]$showStatus)

    Begin
        {
        if(!$maxConcurrentJobs)
        {
            [int]$maxConcurrentJobs = 20
        }
        if($null -eq $showStatus)
        {
            $showStatus = $FALSE;
        }
        if(!$timeLimitperJob)
        {
            [int]$timeLimitperJob = 1
        }

        $arrayofJobs = @();
        $arrayofData = @();      

        CancelOutStandingJobs
    }
    Process
        {
        ForEach($computer in $ComputerName)
        {
            if(Test-Connection $computer -Quiet -Count 1)
            {
                if($showStatus -and ($computer.Length)%5 -eq 0)
                {
                   PrintStatus -NumOfItems $ComputerName.Length
                }

                #Call function to assess job count, and throttle if applicable.
                ThrottleJobs -NumOfItems $ComputerName.Length -maxConcurrentJobs $maxConcurrentJobs -timeLimitperJob $timeLimitperJob

                #Call the GetMappedDrives function.
                    $arrayofJobs += 
                    Start-Job -Name $computer -ScriptBlock{
                        $modDef = [ScriptBlock]::Create($Using:moduleDefinition)    
                        New-Module -Name MyFunctions -ScriptBlock $modDef | out-null; 

                        GetMappedDrives @args
                    } -ArgumentList $computer
            }
            else
            {
                if($showStatus)
                {
                    Write-Host "`nComputer: '$($computer)' is offline"
                }
                
                continue;
            }
        }
    }
    End
        {
        WaitforCompletion -NumOfItems ($ComputerName.Length) -timeLimitperJob $timeLimitperJob -showStatus $showStatus;

        if($showStatus)
        {
            PrintStatus -NumOfItems $ComputerName.Length
        }

            foreach($job in $arrayofJobs)
            {
            
                $arrayofData += Receive-Job -Name $job.Name       
            }
    
        CancelOutStandingJobs
        return $arrayofData | Select-Object UserName, SID, ComputerName, Letter, RemotePath, ScanDate;
    }
}

Export-ModuleMember -Function Get-RemoteMappedDrive