Get-ActiveUser.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
function Get-ActiveUser
{
    <#
    .SYNOPSIS
        Retrive list of active users on windows machine
     
    .DESCRIPTION
        Uses WMI, CIM or Query.exe
 
        This module was created with a powershell.org blogpost in mind
        http://powershell.org/wp/2015/08/28/list-users-logged-on-to-your-machines/
        Created by Jonas Sommer Nielsen
     
    .PARAMETER ComputerName / CN / IP / Hostname
        Optional: Specifies a remote computer to target
     
    .PARAMETER Method
        Optional: Specifies the method to retrieve logged on users. Query, CIM, WMI
     
    .PARAMETER Credential
        Optional: Specifies alternative credentials to use for the WMI connection
     
    .EXAMPLE
        Get-ActiveUser
        Retrieves all users currently logged into the local machine
     
    .EXAMPLE
        Get-ActiveUser -ComputerName TestComputer -Method CIM
        Retrieves all users currently logged into the remote machine "TestComputer" using CIM
 
    .EXAMPLE
        Get-ActiveUser -ComputerName TestComputer -Method WMI -Credential (Get-Credential)
        Retrieves all users currently logged into the remote machine "TestComputer" using WMI.
        This will prompt for credentials to authenticate the connection.
 
    .ExternalHelp
        https://github.com/mrhvid/Get-ActiveUser
         
    .NOTES
        Author: Jonas Sommer Nielsen
        Revised: Ian Mott
    #>
 

    [CmdletBinding(DefaultParameterSetName='Standard Parameters', 
                SupportsShouldProcess=$false, 
                PositionalBinding=$false,
                HelpUri = 'https://github.com/mrhvid/Get-ActiveUser',
                ConfirmImpact='Medium')]
    [Alias()]
    [OutputType([string[]])]
    Param
    (
        # Computer name, IP, Hostname
        [Parameter(Mandatory=$false,
                   ValueFromPipelineByPropertyName=$true,
                   HelpMessage="Default set to localhost",
                   Position=0)]
        [Alias("CN","IP","Hostname")]
        [String]
        $ComputerName = $ENV:COMPUTERNAME,

        # Choose method, WMI, CIM or Query
        [Parameter(Mandatory=$false,
            ValueFromPipelineByPropertyName=$true,
            HelpMessage="Default set to WMI",
            Position=1)]
        [ValidateSet('WMI','CIM','Query')]
        [String]
        $Method = "WMI",

        # Specify Credentials for the remote WMI/CIM queries
        [Parameter(Mandatory=$false,
            ValueFromPipelineByPropertyName=$true,
            HelpMessage="This is only required for WMI connections. Try the Query or CIM method?",
            Position=2)]
        [pscredential]
        $Credential
    )

    Begin
    {
        Write-Verbose -Message "VERBOSE: Starting Begin"

        $Params = @{}

        if ($ComputerName -notin ($ENV:COMPUTERNAME,"localhost", "127.0.0.1")) {
            if ($Method -in ("WMI","CIM")) {
                $Params.Add("ComputerName",$ComputerName)
                
                if ($Credential -and $Method -eq "WMI") {
                    $Params.Add("Credential",$Credential)
                }
            }

            if (Test-Connection -ComputerName $ComputerName -Count 1 -Quiet) {
                Write-Verbose -Message "VERBOSE: Confirmed $ComputerName is reachable by ping"

                if (Test-WSMan @Params -ErrorAction SilentlyContinue -ErrorVariable error_WSMan) {
                    Write-Verbose -Message "VERBOSE: Successfully connected with WSMan"
                } else {
                    Write-Error -Message "ERROR: Failed to connect with WSMan. ErrorMessage: $error_WSMan" -RecommendedAction Stop
                }
                
            } else {
                Write-Error -Message "ERROR: Could not reach $ComputerName by ping. Confirm the computer is reachable." -RecommendedAction Stop
            }
            
        } else {
            Write-Verbose -Message "VERBOSE: ComputerName not set to a remote machine. No need to check for connectivity."
        }
    
        Write-Verbose -Message "VERBOSE: Ending Begin"
    }
    Process
    {
        Write-Verbose -Message "VERBOSE: Starting Process"

        Write-Verbose "$Method selected as method"

        switch ($Method)
        {
            'WMI' 
            {
                Write-Verbose "Contacting $ComputerName via WMI"
        
                $WMI = (Get-WmiObject Win32_LoggedOnUser @Params).Antecedent

                $ActiveUsers = @()
                foreach($User in $WMI) {
                    $StartOfUsername = $User.LastIndexOf('=') + 2
                    $EndOfUsername = $User.Length - $User.LastIndexOf('=') -3
                    $ActiveUsers += $User.Substring($StartOfUsername,$EndOfUsername)
                }
                $ActiveUsers = $ActiveUsers | Select-Object -Unique

            }
            'CIM' 
            {
                Write-Verbose "Contacting $ComputerName via CIM"
                $ActiveUsers = (Get-CimInstance Win32_LoggedOnUser @Params).antecedent.name | Select-Object -Unique

            }
            'Query' 
            {
                Write-Verbose "Contacting $ComputerName via Query"
                $Template = @'
 USERNAME SESSIONNAME ID STATE IDLE TIME LOGON TIME
>{USER*:jonas} console 1 Active 1+00:27 24-08-2015 22:22
 {USER*:test} 2 Disc 1+00:27 25-08-2015 08:26
>{USER*:mrhvid} rdp-tcp#2 2 Active . 9/1/2015 8:54 PM
'@


                $Query = query.exe user /server $ComputerName
                $ActiveUsers = $Query | ConvertFrom-String -TemplateContent $Template | Select-Object -ExpandProperty User
            }

        }

        Write-Verbose -Message "VERBOSE: Ending process"
    }
    End
    {
        Write-Verbose -Message "VERBOSE: Starting End"

        # Create nice output format
        $UsersComputersToOutput = @()
        foreach($User in $ActiveUsers) {
             $UsersComputersToOutput += New-Object psobject -Property @{ComputerName=$ComputerName;UserName=$User}   
        }

        # output data
        $UsersComputersToOutput
        
        Write-Verbose -Message "VERBOSE: Ending End"
    }
}