dragonspeed
dragonspeed

Reputation: 276

Why does output differ based on what comes before my command

The commands

Write-Host "`r`nSource Hosts" -BackgroundColor Green
$myEvents | Group-Object Host -NoElement | Sort-Object Count -Descending
Write-Host "`r`n`r`nAccounts" -BackgroundColor Green
$myEvents | Group-Object User -NoElement | sort-object Count -Descending

create nice, tabulated output when handed a nice array of PSObjects

The entire script is quite short:

(Get-Date)
$Events= Get-WinEvent -ComputerName MYDC -FilterHashtable  @{Logname='Security';id=4740;StartTime=(Get-Date).AddMinutes(-30)}
$TargetEvents=@()
function OutputEvents($myEvents) {

    Write-Host "`r`nSource Hosts" -BackgroundColor Green
    $myEvents | Group-Object Host -NoElement | Sort-Object Count -Descending
    Write-Host "`r`n`r`nAccounts" -BackgroundColor Green
    $myEvents | Group-Object User -NoElement | sort-object Count -Descending
}
foreach ($Event in $Events)
{

    $obj=[PSCustomObject]@{
        Host=$Event.Properties[1].value.ToString()
        User=$Event.Properties[0].value.ToString()
    }
    $TargetEvents+=$obj
}
(Get-Date)
OutputEvents $TargetEvents

The problem is that when it runs in this context, I end up with

Source Hosts

Values : {HOSTNAME}
Count  : 5
Group  : {}
Name   : HOSTNAME
...etc

Accounts

Values : {Username}
Count  : 5
Group  : {}
Name   : Username
...etc

But after the code has run I can copy and paste the output lines and get:

Source Hosts

Count Name                     
----- ----                     
5 APSPRW7082  
...etc

Accounts
5 SVOL.EM       
...etc

Two completely differing formats

I don't understand why, and quite frankly, I'd like it to stop.

Upvotes: 0

Views: 36

Answers (2)

dragonspeed
dragonspeed

Reputation: 276

It turns out the way to ensure that the format works correctly is to take the output lines:

$myEvents | Group-Object Host -NoElement | Sort-Object Count -Descending

and convert them to:

$myEvents | Group-Object Host -NoElement | Sort-Object Count -Descending | ft

Thereby ensuring that the output is table formatted and not let PS make some arbirtrary "helpful" decision for me.

Upvotes: 0

js2010
js2010

Reputation: 27566

The script runs through format-table implicitly. With another set of properties output by get-date, powershell tries to handle the output in a different way.

Upvotes: 1

Related Questions