PowerShell如何将对象数组解析为字符串?附AD计算机查询代码
把AD计算机对象数组转成字符串的几种方法
嘿,我来帮你搞定这个问题!你现在通过Get-ADComputer拿到的是包含Name和LastLogonDate属性的对象数组,直接赋值给[string[]]变量只会得到对象的类型名称(比如Microsoft.ActiveDirectory.Management.ADComputer),根本不是你要的实际内容。下面给你几种实用的转换方式,按需选择:
1. 提取单个属性生成纯字符串数组
如果你只需要计算机名称的字符串数组,可以用Select-Object -ExpandProperty直接提取属性值,同时优化一下原代码(没必要用-Properties *,只指定需要的LastLogonDate能大幅提高查询效率):
[string[]] $computerNames = Get-ADComputer -Properties LastLogonDate -Filter {OperatingSystem -like "*Windows 7*"} | Where-Object { $_.Name -like "*-*" -and $_.Name -notlike "V7-*" -and $_.Name -notlike "*-NONE" -and $_.Name -notlike "*-ONCALL" -and $_.Name -notlike "*-BLACKBAUD" -and $_.Name -notlike "SC-WIN7-1" -and $_.Name -notlike "UT-SWCLIENT-01" } | Select-Object -ExpandProperty Name
这样$computerNames就是纯计算机名称的字符串数组了。
2. 自定义拼接属性为结构化字符串
如果需要把Name和LastLogonDate组合成自定义格式的字符串(比如“计算机名:最后登录时间”),用ForEach-Object拼接即可:
[string[]] $computerStrings = Get-ADComputer -Properties LastLogonDate -Filter {OperatingSystem -like "*Windows 7*"} | Where-Object { $_.Name -like "*-*" -and $_.Name -notlike "V7-*" -and $_.Name -notlike "*-NONE" -and $_.Name -notlike "*-ONCALL" -and $_.Name -notlike "*-BLACKBAUD" -and $_.Name -notlike "SC-WIN7-1" -and $_.Name -notlike "UT-SWCLIENT-01" } | ForEach-Object { "$($_.Name): $($_.LastLogonDate)" }
运行后$computerStrings里的每一项都是你自定义格式的字符串。
3. 转成CSV/JSON等结构化字符串
如果需要保留完整的属性结构,方便后续解析,可以转成CSV或JSON格式的字符串:
CSV格式
$csvString = Get-ADComputer -Properties LastLogonDate -Filter {OperatingSystem -like "*Windows 7*"} | Where-Object { $_.Name -like "*-*" -and $_.Name -notlike "V7-*" -and $_.Name -notlike "*-NONE" -and $_.Name -notlike "*-ONCALL" -and $_.Name -notlike "*-BLACKBAUD" -and $_.Name -notlike "SC-WIN7-1" -and $_.Name -notlike "UT-SWCLIENT-01" } | Select-Object Name, LastLogonDate | ConvertTo-Csv -NoTypeInformation
$csvString是包含表头和所有数据的CSV字符串,能直接保存为.csv文件或者用于其他系统解析。
JSON格式
$jsonString = Get-ADComputer -Properties LastLogonDate -Filter {OperatingSystem -like "*Windows 7*"} | Where-Object { $_.Name -like "*-*" -and $_.Name -notlike "V7-*" -and $_.Name -notlike "*-NONE" -and $_.Name -notlike "*-ONCALL" -and $_.Name -notlike "*-BLACKBAUD" -and $_.Name -notlike "SC-WIN7-1" -and $_.Name -notlike "UT-SWCLIENT-01" } | Select-Object Name, LastLogonDate | ConvertTo-Json
$jsonString是标准的JSON字符串,适合跨平台或API场景使用。
内容的提问来源于stack exchange,提问作者Our Man in Bananas
相关产品推荐
相关产品推荐

