在PowerShell中将一组对象解析为字符串

时间:2018-04-17 13:37:39

标签: arrays powershell

我这样叫Get-AdComputer

[string[]] $computer = Get-ADComputer -properties * -filter {(operatingsystem -like "*Windows 7*")} |
    Where-Object {$_.name -like "*-*"} |
    Where-Object {$_.name -NotLike "V7-*"} |
    Where-Object {$_.name -NotLike "*-NONE"} |
    Where-Object {$_.name -NotLike "*-ONCALL"} |
    Where-Object {$_.name -NotLike "*-BLACKBAUD"} |
    Where-Object {$_.name -NotLike "SC-WIN7-1"} |
    Where-Object {$_.name -NotLike "UT-SWCLIENT-01"} |
    Select-Object Name, LastLogonDate

这会创建一个字符串数组,我可以像这样访问它:

$computer[1]

返回

@{Name=W7-9HQPR3J; LastLogonDate=05/08/2017 09:45:13}

我需要将数据输出到两列Name, LastLogonDate

中的csv文件中

不幸的是,当我致电$Computer | out-file -filepath $ServiceTagsPath -Force -Width 200 -Encoding ascii

我得到一列,每行标题: enter image description here

我的另一个要求是能够在Web服务调用中使用Name列来获取保修信息......

所以我怎么能这样做?

1 个答案:

答案 0 :(得分:3)

我不会将输出转换为字符串[string[]]的数组,而是将转换保留为powershell。 然后你可以使用命令Export-Csv,它可以更好地处理对象数组。

$computer = Get-ADComputer -properties * -filter {(operatingsystem -like "*Windows 7*")} |
    Where-Object {$_.name -like "*-*"} |
    Where-Object {$_.name -NotLike "V7-*"} |
    Where-Object {$_.name -NotLike "*-NONE"} |
    Where-Object {$_.name -NotLike "*-ONCALL"} |
    Where-Object {$_.name -NotLike "*-BLACKBAUD"} |
    Where-Object {$_.name -NotLike "SC-WIN7-1"} |
    Where-Object {$_.name -NotLike "UT-SWCLIENT-01"} |
    Select-Object Name, LastLogonDate

 $computer | Export-Csv "test.csv" -NoTypeInformation