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

PowerShell脚本无法将远程执行结果输出至TXT文件求助

解决PowerShell远程收集域内设备信息并保存到本地TXT的问题

你的脚本存在几个关键问题,导致无法正确将结果保存到本地文件,以下是问题分析和修正方案:

问题点分析

  1. 变量作用域错误:远程脚本块(-ScriptBlock)运行在目标计算机上,无法直接访问本地的$ADC变量,必须使用$using:前缀引用本地变量。
  2. 文件写入位置错误:脚本块内的Out-File会在远程计算机上创建文件,而非你的本地机器,这不是你想要的结果。
  3. 语法错误:Get-computerinfo与Out-File之间缺少管道符|,导致PowerShell解析时出现“An empty pipe element is not allowed.”错误。

修正后的脚本

# Name: 
# Date: 02/10/2023
# Desc: Runs remote commands for every computer within domain to collect general information

# 从指定文件读取域内计算机名列表
$ADCS = Get-Content -Path "C:\computers.txt"
# 定义本地输出文件路径
$outputFilePath = "C:\Users\aembrey\Documents\ComputerInfo.txt"

# 可选:清空输出文件,避免旧内容干扰
Clear-Content -Path $outputFilePath -ErrorAction SilentlyContinue

# 遍历每台计算机执行远程命令
foreach ($ADC in $ADCS) {
    try {
        # 执行远程命令,获取计算机信息
        $remoteResult = Invoke-Command -ComputerName $ADC -ScriptBlock {
            # 使用$using:ADC引用本地的计算机名变量
            Write-Output "=== 计算机信息: $using:ADC ==="
            # 获取完整计算机信息
            Get-ComputerInfo
        } -ErrorAction Stop

        # 将远程返回的结果追加到本地文件
        $remoteResult | Out-File -FilePath $outputFilePath -Append
    }
    catch {
        # 捕获远程连接失败的错误,记录到输出文件
        Write-Output "=== 计算机 $ADC 连接失败: $_ ===" | Out-File -FilePath $outputFilePath -Append
    }
}

关键修改说明

  • 变量引用:用$using:ADC替代直接的$ADC,让远程脚本块能识别本地的计算机名变量。
  • 本地写入:将远程执行的结果返回到本地后,再通过Out-File -Append追加到本地文件,确保所有计算机的信息都保存在同一个文件中。
  • 错误处理:添加try-catch块捕获远程连接失败、权限不足等错误,并将错误信息写入文件,方便排查问题。
  • 语法修复:确保Get-ComputerInfo与输出命令之间通过管道符|正确连接,避免语法错误。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.31 15:40:37