You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

多计算机特定文件夹检测脚本优化:输出Test-Path结果至文件

修改后的PowerShell脚本

以下是满足需求的修改版脚本,会直接输出你指定格式的检测结果到文件:

Invoke-Command -ComputerName (Get-Content C:\temp\servers.txt) -ScriptBlock {
    # 遍历注册表中的用户配置项
    Get-ChildItem 'HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion\ProfileList' | ForEach-Object {
        $profilePath = (Get-ItemProperty $_.PSPath).ProfileImagePath
        # 只处理C盘用户目录下的配置文件
        if ($profilePath -like "C:\users*") {
            # 拼接目标文件夹路径
            $targetFolder = Join-Path -Path $profilePath -ChildPath "appdata\Local\Packages\ActiveSync"
            # 转换为示例格式的路径(添加计算机名前缀,替换盘符冒号为$)
            $formattedPath = "\$env:COMPUTERNAME\$($profilePath -replace ':','$')\appdata\Local\Packages\ActiveSync"
            # 检测路径是否存在
            $exists = Test-Path -Path $targetFolder -PathType Container
            # 输出指定格式的内容
            "$formattedPath $exists"
        }
    }
} | Out-File C:\temp\ProfileSyncCheck.txt -Encoding UTF8
关键改动说明
  • 把路径检测逻辑移到远程脚本块内执行:避免本地处理远程路径的权限问题,直接在目标机器上完成检测,结果更准确
  • 按要求格式化输出字符串:将本地路径转换为带计算机名的格式(和你给出的示例一致),后面紧跟True或False的检测结果
  • 一步生成目标文件:无需先导出CSV再二次处理,直接输出符合要求的文本内容
可选优化建议
  • 如果需要标记远程连接失败的计算机,可以改用循环逐个处理,并补充错误判断:
    $computers = Get-Content C:\temp\servers.txt
    foreach ($computer in $computers) {
        $result = Invoke-Command -ComputerName $computer -ScriptBlock {
            # 内部逻辑同上面的脚本块
            Get-ChildItem 'HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion\ProfileList' | ForEach-Object {
                $profilePath = (Get-ItemProperty $_.PSPath).ProfileImagePath
                if ($profilePath -like "C:\users*") {
                    $targetFolder = Join-Path -Path $profilePath -ChildPath "appdata\Local\Packages\ActiveSync"
                    $formattedPath = "\$env:COMPUTERNAME\$($profilePath -replace ':','$')\appdata\Local\Packages\ActiveSync"
                    $exists = Test-Path -Path $targetFolder -PathType Container
                    "$formattedPath $exists"
                }
            }
        } -ErrorAction SilentlyContinue
        
        if (-not $result) {
            "\$computer 远程连接失败" | Out-File C:\temp\ProfileSyncCheck.txt -Encoding UTF8 -Append
        } else {
            $result | Out-File C:\temp\ProfileSyncCheck.txt -Encoding UTF8 -Append
        }
    }
    

内容的提问来源于stack exchange,提问作者user2591459

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.11 14:50:43