脚本输出可在控制台以及Export-Csv上使用 [英] Script output that will work on the console as well as with Export-Csv
问题描述
我正在处理一个基本的PowerShell脚本,该脚本输入一对日期,然后获取所有密码在这些时间之间到期的帐户.我想以与Export-Csv
兼容的方式将数据输出到控制台.这样,运行脚本的人就可以只在控制台中查看或获取文件.
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.
这是我的剧本:
[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
但是,当用| Export-Csv
调用时却没有:
However when called with | Export-Csv
it doesn't:
#TYPE System.String
Length
5388
我已经尝试过使用对象和数据表进行多种变体,但是似乎只能使它同时适用于控制台或CSV,而不能同时适用于两者.
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.
推荐答案
替换
Write-Output ($accts | Format-Table | Out-String)
使用
$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
将您的输出转换为单个字符串,而Export-Csv
希望将对象列表作为输入(对象属性随后成为CSV的列).如果为Export-Csv
提供了字符串,则唯一的属性是Length
,因此您将获得一个包含一列和一条记录的CSV.
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.
这篇关于脚本输出可在控制台以及Export-Csv上使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!