如何在PowerShell脚本中嵌套foreach循环批量检查域服务器文件夹
解决方法:遍历多文件夹检查域内服务器
修改后的脚本可从文本文件读取目标文件夹列表,通过嵌套遍历实现逐个检查,同时记录服务器名称和存在的具体文件夹,结果更直观:
function Find-ComputersWithFolders { param( # 指定存储文件夹名的文本文件路径 [Parameter(Mandatory=$true)] [string]$FolderListPath ) # 读取文本文件中的文件夹名,自动过滤空行 $folderNames = Get-Content $FolderListPath | Where-Object { $_ -notmatch '^\s*$' } # 获取域内目标服务器列表(可根据需要调整Filter条件) $computers = Get-ADComputer -Filter { Name -like 'servernamehere' } # 初始化结果数组,存储自定义对象 $results = @() # 外层循环:遍历每个服务器 foreach ($computer in $computers) { $computerName = $computer.Name $basePath = "\\$computerName\C$\Windows\WinSxS\" # 内层循环:遍历每个要检查的文件夹 foreach ($folderName in $folderNames) { $fullPath = Join-Path -Path $basePath -ChildPath $folderName # 检查文件夹是否存在(明确指定路径类型为容器) if (Test-Path -Path $fullPath -PathType Container) { # 记录服务器名和对应的文件夹路径 $results += [PSCustomObject]@{ ComputerName = $computerName ExistingFolder = $fullPath } } } } return $results } # 脚本使用示例 $folderList = "C:\scripts\paths.txt" $checkResults = Find-ComputersWithFolders -FolderListPath $folderList # 输出结果 Write-Output "服务器及存在的目标文件夹:" $checkResults
关键细节说明:
- 路径拼接优化:用
Join-Path替代手动字符串拼接,自动处理路径分隔符,避免格式错误 - 嵌套循环逻辑:外层遍历服务器、内层遍历文件夹,确保每个服务器都会检查所有目标路径
- 结构化结果:返回包含服务器名和文件夹路径的自定义对象,方便后续筛选、导出(比如导出CSV:
$checkResults | Export-Csv -Path "C:\results.csv" -NoTypeInformation) - 无效内容过滤:读取文件夹列表时自动跳过空行,避免无效检查
paths.txt格式要求:
每行一个目标文件夹名,示例:
folder1 folder2 test_folder_001
内容的提问来源于stack exchange,提问作者Martyn Jeffrey
相关产品推荐
相关产品推荐

