如何将Intune PowerShell修复脚本的多用户输出整合到单个变量?
Intune Remediations多用户PowerShell脚本输出捕获问题解决
问题
在使用Intune Remediations结合PowerShell处理多用户场景时,脚本本地运行能正常输出所有180天内有活动的用户处理结果,但Intune仅返回单个用户的信息。需要调整脚本,将所有输出内容整合后统一返回,让修复任务能获取完整的多用户处理结果。
原脚本问题分析
- 脚本中使用
exit 0/exit 1会在处理第一个符合条件的用户时直接终止脚本,导致后续用户的处理逻辑和输出都无法执行 Write-Host的输出无法被Intune捕获,只有Write-Output的内容会被记录到修复任务结果中- 未将所有用户的处理结果统一收集,导致仅能返回单个用户的信息
修改后的脚本
# 初始化结果存储数组和修复标志 $outputResults = @() $needsRemediation = $false # 获取系统中所有用户配置文件,排除指定账户 $users = Get-ChildItem (Join-Path -Path $env:SystemDrive -ChildPath 'Users') -Exclude 'Public', 'Administrator','svc*' # 计算180天前的日期,用于判断用户是否活跃 $StaleAccountDate = (Get-Date).AddDays(-180) if ($null -ne $users) { # 检查并禁用所有阻止Teams的防火墙规则 $outputResults += "Checking for firewall rules that block Teams Access" $TeamsBlock = Get-NetFirewallRule -Name *Teams* | Where-Object {($_.action -eq "Block") -and ($_.Enabled -eq 'True')} If ($null -ne $TeamsBlock) { Foreach ($Rule in $TeamsBlock) { $outputResults += "Disabling blocking firewall rule $($Rule.DisplayName)" Set-NetFirewallRule $Rule.Name -Enabled False } } foreach ($user in $users) { # 获取用户目录下最后修改时间最新的文件 $LastAccessTime = Get-ChildItem $user.FullName | Sort-Object lastwritetime -Descending If ($LastAccessTime[0].LastWriteTime -le $StaleAccountDate) { $outputResults += "Skipping $($user.Name) because the last access time on the account is too old" continue } $outputResults += "Checking $($user.Name)" # 构建Teams可执行文件路径 $progPath = Join-Path -Path $user.FullName -ChildPath "AppData\Local\Microsoft\Teams\Current\Teams.exe" if (Test-Path $progPath) { # 检查对应路径的防火墙规则是否存在 $RuleCheck = Get-NetFirewallApplicationFilter -Program $progPath -ErrorAction SilentlyContinue if ($Null -eq $RuleCheck) { $outputResults += "Rules need adding for $($user.Name), proceed to remediate" $needsRemediation = $true } else { $outputResults += "Looks like there are already rules in place for $($user.Name), so we will not add any" } } else { $outputResults += "Looks like $($user.Name) has not launched Teams, we will be skipping" } # 清理当前用户相关变量 Clear-Variable RuleCheck, progPath -ErrorAction SilentlyContinue } # 清理全局变量 Clear-Variable TeamsBlock -ErrorAction SilentlyContinue } # 输出所有结果,供Intune捕获 Write-Output $outputResults # 根据是否需要修复返回对应退出码 if ($needsRemediation) { exit 1 } else { exit 0 }
关键改动说明
- 添加
$outputResults数组统一存储所有处理日志,最后通过Write-Output一次性输出,确保Intune能捕获完整内容 - 新增
$needsRemediation标志变量,用于跟踪是否存在需要修复的用户,避免中途退出脚本 - 将所有
Write-Host替换为向数组添加内容,确保所有日志都能被收集 - 移除中途的
exit 0/exit 1,改为在遍历完所有用户后统一返回退出码 - 使用
continue跳过非活跃用户的后续处理,提升脚本效率
内容的提问来源于stack exchange,提问作者Admaine
相关产品推荐
相关产品推荐

