Search code examples
loopsparsingpowershellsysinternals

Powershell with Psloggedon to see who last logged on a remote host (from a list of hosts)


I am having trouble using powershell and pslogged on to pull the information of "the last logged on user" and the "logged on timestamp" from the psloggedon tool. Basically what I am trying to do is to read from a text file with all the list of the servers'name, and then use pslogged on on them to get the info. So if I run the following command separately, it works

psloogedon \\server1

but when I do this in powershell it doesn't work

$content = [IO.File]::ReadAllText("C:\assets.txt")
Foreach($computer in $content)
{
Invoke-Expression "psloggedon -x -l \\$computer"
} Export-Csv -NoTypeInformation loggedon.csv

and in the assets.txt we have the following content:

server1
server2
server3
etc...

How can i build based on this to 1) make the script work to use psloggedon to get the information 2) parse the loggedon user, the computer name and the timestamp into a CSV with 3 columns file?

Any help is appreciated....


Solution

  • this worked for me

    get-content 'C:\assets.txt' | % {
        $computer = $_
        . 'c:\pstools\PsLoggedon.exe' -accepteula -x -l \\$Computer 2>$null |
            ? {$_ -match '^\s{2,}((?<domain>\w+)\\(?<user>\S+))|(?<user>\S+)'} |
            Select-Object `
                @{n='Computer';e={$Computer}},
                @{n='Domain';e={$matches.Domain}},
                @{n='User';e={$Matches.User}} |
            ? user -notmatch '^Connecting$|^Users$|^NT$'
    } | epcsv 'c:\loggedon.csv' -not
    

    another example

    gc 'C:\assets.txt' | % {
        $computer = $_
        . 'c:\pstools\PsLoggedon.exe' -accepteula -l \\$Computer 2>$null |
            ? {$_ -match '^\s{2,}(?<time>.*)\s{2,}(?<user>.*)'} | % {
                New-Object psobject -prop @{
                    Computer = $computer
                    Time = $Matches.time.Trim()
                    User = $Matches.user.Trim()
                }
            } | ? user -notmatch '^Connecting$|^Users$|^NT$'
    } | epcsv 'c:\loggedon.csv' -not
    

    if you're using a csv, you would just replace the first two lines like this

    import-csv 'C:\assets.csv' | % {
        $computer = $_.computers
    

    or this

    import-csv 'C:\assets.csv' | select -exp computers -u | % {
        $computer = $_