Script output that will work on the console as wel

2020-04-30 01:24发布

I'm working on a basic PowerShell script that inputs a pair of dates then gets all accounts with passwords expiring between those times. I'd like to output the data to the console in a way that is compatible with Export-Csv. That way the person running the script can either just view in the console, or get a file.

Here is my script:

[CmdletBinding()]
param(
    [string]$StartDate = $(throw "Enter beginning date as MM/DD/YY"),
    [string]$EndDate = $(throw "Enter end date as MM/DD/YY")
)

$start = Get-Date($StartDate)
$end = Get-Date($EndDate)

$low = $start.AddDays(-150)
$high = $end.AddDays(-150)

$passusers = Get-ADUser -Filter { PasswordLastSet -gt $low -and PasswordLastSet -lt $high -and userAccountControl -ne '66048' -and userAccountControl -ne '66080' -and enabled -eq $true} -Properties PasswordLastSet,GivenName,DisplayName,mail,LastLogon | Sort-Object -Property DisplayName

$accts = @()

foreach($user in $passusers) {
    $passLastSet = [string]$user.PasswordLastSet
    $Expiration = (Get-Date($passLastSet)).addDays(150)

    $obj = New-Object System.Object
    $obj | Add-Member -MemberType NoteProperty -Name Name -Value $user.DisplayName 
    $obj | Add-Member -MemberType NoteProperty -Name Email -Value $user.mail
    $obj | Add-Member -MemberType NoteProperty -Name Expiration -Value $expiration

    $accts += $obj
}

Write-Output ($accts | Format-Table | Out-String)

This prints to the console perfectly:

Name                 Email                   Expiration
----                 -----                   ----------
Victor Demon         demonv@nsula.edu      1/3/2016 7:16:18 AM

However when called with | Export-Csv it doesn't:

#TYPE System.String
Length
    5388

I've tried multiple variations using objects, and data tables, however it seems like I can only get it to work for console or for CSV, not for both.

2条回答
冷血范
2楼-- · 2020-04-30 01:58
$accts | ConvertTo-Csv | Tee -File output.csv | ConvertFrom-Csv
查看更多
够拽才男人
3楼-- · 2020-04-30 02:20

Replace

Write-Output ($accts | Format-Table | Out-String)

with

$accts

That way your users can run your script any way they like, e.g.

.\your_script.ps1 | Format-Table
.\your_script.ps1 | Format-List
.\your_script.ps1 | Export-Csv
.\your_script.ps1 | Out-GridView
...

Format-Table | Out-String converts your output to a single string whereas Export-Csv expects a list of objects as input (the object properties then become the columns of the CSV). If Export-Csv is fed a string, the only property is Length, so you get a CSV with one column and one record.

查看更多
登录 后发表回答