PowerShell ForEach遍历数组与CSV运行差异问题求助
问题根因
报错和ForEach循环结构无关,核心是循环块内的变量引用错误:
- 你定义的
$Yammer是存储全部查询结果的数组对象,不是单条组记录 ForEach-Object遍历过程中,代表当前正在处理的单条元素的内置变量是$_(别名$PSItem)。你在循环块内全程使用$Yammer.id、$Yammer.DisplayName取属性时,PowerShell会自动提取数组内所有元素的对应属性,拼成一个ArrayList集合传给命令,和Set-UnifiedGroup要求的单个Identity参数类型不匹配,因此抛出类型转换错误。- 之前CSV导入版本能正常运行,是因为当时循环内用
$_引用了当前遍历的CSV行,切换到数组版本时没有同步修改循环内的变量引用。
修复后的脚本
把循环块内所有引用数组对象$Yammer的位置替换为当前对象变量$_即可,修复后完整代码如下:
Write-Host "Please wait whilst Data is collected ... This may take a while ........" -NoNewline -ForegroundColor Green # 直接查询结果存入数组,不需要中转CSV [array]$Yammer = Get-UnifiedGroup -ResultSize Unlimited | Where-Object {$_.GroupSku -eq "Yammer"} $yammer | ForEach-Object { Write-Host "`n*** Task 1 *** Setting Group Hidden From Address List Attribute" -NoNewline -ForegroundColor Green Set-UnifiedGroup -Identity $_.id -HiddenFromAddressListsEnabled $true Write-Host "`n*** Task Custom *** Setting Custom Attribute" -NoNewline -ForegroundColor Green Set-UnifiedGroup -Identity $_.id -CustomAttribute1 "test" Write-Host "`n*** Task 3 *** Appending -Yammer To Group Name" -NoNewline -ForegroundColor Green if (! ($_.DisplayName.ToLower().EndsWith("-yammer")) ) { Set-UnifiedGroup -Identity $_.id -DisplayName ($_.DisplayName + "-Yammer") } } Write-Host "`nProcess is now Complete" -NoNewline -ForegroundColor Green
补充说明
- PowerShell原生支持数组属性枚举:对数组变量直接用
数组名.属性名的写法,会返回数组中所有元素对应属性值组成的新集合,这个行为对直接查询得到的对象数组、导入CSV得到的对象数组完全一致,不存在两种遍历逻辑的差异。 - 编写
ForEach-Object遍历逻辑时,脚本块{}内要操作当前遍历项,统一使用$_即可,不要直接引用外层存储整个集合的数组变量。
内容的提问来源于stack exchange,提问作者wolfmaster74
相关产品推荐
相关产品推荐

