PowerShell Foreach导出Excel数据被覆盖问题及解决方法
PowerShell脚本导出Excel仅保留最后一条结果的解决方法
问题描述
编写的PowerShell脚本在控制台能正常输出所有符合条件的用户信息,但导出到Excel文件时仅保留最后一条结果,之前的内容被覆盖。原脚本如下:
Import-Module ImportExcel $FolderPath = "\\clalit\dfs$\HomeFS\Ram Idan Scripts" $Acl = Get-Acl -Path $FolderPath $AccessRules = $Acl.Access foreach ($Rule in $AccessRules) { try{ $Username = ($Rule.IdentityReference.Tostring().split("\")[1]) $Permissions = ($Rule.FileSystemRights.Tostring().split(",")[0]) $Email = (Get-ADUser $Username -Properties mail).mail $all = Get-ADUser $Username -Properties DisplayName,SamAccountName,mail if( $Permissions -match "Modify"){ $all | Select DisplayName,SamAccountName,mail } else{} }catch{$nul} } $all | Select DisplayName,SamAccountName,mail | Export-Excel "$FolderPath\tests.xlsx" -FreezeTopRow -AutoSize
问题原因
原脚本中$all变量在每次循环时都会被重新赋值为单个AD用户对象,而非累积存储所有符合条件的对象。最后执行导出操作时,$all仅保存了最后一次循环的结果,导致Excel中只有最后一条数据。
解决方法
将整个foreach循环的输出收集到变量中,让变量存储所有符合条件的用户对象集合,再统一导出。以下是两种可行的修改方式:
方式1:初始化数组并追加结果
Import-Module ImportExcel $FolderPath = "\\clalit\dfs$\HomeFS\Ram Idan Scripts" $Acl = Get-Acl -Path $FolderPath $AccessRules = $Acl.Access # 初始化空数组用于存储所有符合条件的结果 $all = @() foreach ($Rule in $AccessRules) { try{ $Username = ($Rule.IdentityReference.ToString().split("\")[1]) $Permissions = ($Rule.FileSystemRights.ToString().split(",")[0]) # 仅获取一次AD用户信息,避免重复调用 $user = Get-ADUser $Username -Properties DisplayName,SamAccountName,mail if( $Permissions -match "Modify"){ # 将符合条件的用户对象添加到数组中 $all += $user | Select DisplayName,SamAccountName,mail } }catch{$null} } $all | Export-Excel "$FolderPath\tests.xlsx" -FreezeTopRow -AutoSize
方式2:直接将foreach循环输出赋值给变量
Import-Module ImportExcel $FolderPath = "\\clalit\dfs$\HomeFS\Ram Idan Scripts" $Acl = Get-Acl -Path $FolderPath $AccessRules = $Acl.Access # 直接收集foreach循环的所有输出结果 $all = foreach ($Rule in $AccessRules) { try{ $Username = ($Rule.IdentityReference.ToString().split("\")[1]) $Permissions = ($Rule.FileSystemRights.ToString().split(",")[0]) $user = Get-ADUser $Username -Properties DisplayName,SamAccountName,mail if( $Permissions -match "Modify"){ $user | Select DisplayName,SamAccountName,mail } }catch{$null} } $all | Export-Excel "$FolderPath\tests.xlsx" -FreezeTopRow -AutoSize
更新:已解决,需将整个foreach循环放入变量中即可正常运行
内容的提问来源于stack exchange,提问作者Mr.RamGoat
相关产品推荐
相关产品推荐

