【问题标题】:Script output that will work on the console as well as with Export-Csv可在控制台以及 Export-Csv 上运行的脚本输出
【发布时间】:2015-12-15 15:42:51
【问题描述】:

我正在编写一个基本的 PowerShell 脚本,该脚本输入一对日期,然后获取密码在这些时间之间到期的所有帐户。我想以与Export-Csv 兼容的方式将数据输出到控制台。这样,运行脚本的人既可以在控制台中查看,也可以获取文件。

这是我的脚本:

[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)

这完美地打印到控制台:

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

但是,当使用 | Export-Csv 调用时,它不会:

#TYPE System.String
Length
    5388

我尝试过使用对象和数据表的多种变体,但似乎我只能让它在控制台或 CSV 上工作,而不是同时用于两者。

【问题讨论】:

    标签: powershell export-to-csv


    【解决方案1】:

    替换

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

    $accts
    

    这样您的用户可以按照他们喜欢的任何方式运行您的脚本,例如

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

    Format-Table | Out-String 将您的输出转换为单个字符串,而Export-Csv 需要一个对象列表作为输入(对象属性然后成为 CSV 的列)。如果给Export-Csv 输入一个字符串,则唯一的属性是Length,因此您会得到一个包含一列和一条记录的CSV。

    【讨论】:

    • 谢谢!显然,当我试图设置我的对象时,我把自己弄糊涂了,再也没有回去尝试过基本的方法。只需执行$accts 就可以将其正确打印到控制台,现在管道到Export-Csv 也可以。
    【解决方案2】:
    $accts | ConvertTo-Csv | Tee -File output.csv | ConvertFrom-Csv
    

    【讨论】:

    • 如果需要,您可以删除最后一个 |convertfrom-csv
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-28
    • 1970-01-01
    • 1970-01-01
    • 2018-05-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多