Find-ServiceUser.ps1

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
Function Find-ServiceUser {
    #[CmdletBinding()]
    param (
        [parameter(mandatory = $true, position = 0)]
        [string[]]
        $computer,

        [parameter(mandatory = $false, position = 1)]
        [string]
        $user,

        [parameter(Mandatory = $false, HelpMessage = 'Turns on the search after the exact username.')]
        [switch]
        $Strict
    )
    $user = $user.trim()
    $computer = $computer.trim()
    $service_ = $false

    try {
        Test-Connection -ComputerName $computer -Count 1 -Quiet -ErrorAction SilentlyContinue | Out-Null
    }
    catch {
        Write-Verbose -Message "$computer offline?"
        Write-Information -MessageData "$computer offline?" -InformationAction Continue
        return $null
    }
    if ($Strict) {
        $filter = "startname = '$($user)'"
        #Write-Information $filter -InformationAction Continue
    }
    else {
        $filter = "startname LIKE '%$($user)%'"
    }
    Write-Verbose -Message "WMI query for system services."
    #if computer is localhost then WMI query has no -computername
    if ($computer -eq $env:COMPUTERNAME) {
        try {
            $service_ = Get-CimInstance -classname win32_service -filter "$filter" -ErrorAction Stop
        } 
        catch {
            Write-Error -Message "Failed WMI query for system services with Service Logon Account as ""$user"": $_"
        }
        #Write-Debug ((get-variable "service_").value)
        #(get-variable "service_").value
        if ($service_) {
            Write-Verbose -Message "Return WMI query data"
            return $service_
        } else {
            Write-Verbose -Message "NO WMI query data"
            $out_variable = (Get-Variable service_).Value
            Write-Debug -message "Return data from inside 'Find-ServiceUser': $out_variable" -InformationAction Continue
            return $false
            #$service_
        }
    }  else {
        try {
            $service_ = Get-CimInstance -classname win32_service -filter "$filter" -ComputerName $computer -ErrorAction Stop
        } 
        catch {
            Write-Error -Message "Failed WMI query for system services with Service Logon Account as ""$user"": $_"
        }
        #Write-Debug ((get-variable "service_").value)
        #(get-variable "service_").value
        if ($service_) {
            Write-Verbose -Message "Return WMI query data"
            return $service_
        } else {
            Write-Verbose -Message "NO WMI query data"
            $out_variable = (Get-Variable service_).Value
            Write-Debug -message "Return data from inside 'Find-ServiceUser': $out_variable" -InformationAction Continue
            return $false
        }
    }
}# end function Find-ServiceUser