Invoke-Command执行外部脚本文件报错的原因及解决方法
问题分析与解决:从外部TXT文件执行PowerShell脚本报错
问题描述
- 直接在PowerShell中可正常运行的代码:
Get-ItemProperty HKLM:\Software\Microsoft\Windows\CurrentVersion\Uninstall\* | Select-Object DisplayName, DisplayVersion, Publisher, InstallDate | Format-Table –AutoSize
- 将上述代码存入
script.txt后,执行以下命令时报错:
$stdout = Invoke-Command -ScriptBlock ([ScriptBlock]::Create((Get-Content 'script.txt'))) *>&1
- 报错信息:
Exception calling "Create" with "1" argument(s): "At line:1 char:163
- ... me, DisplayVersion, Publisher, InstallDate | Format-Table –AutoSize
~~~~~~~~~The string is missing the terminator: "."
报错原因
核心问题是Format-Table后的–AutoSize参数用了中文全角破折号(–),而非PowerShell识别的英文半角减号(-)。直接在PowerShell输入时会自动转换为合法符号,但存入TXT文件后可能保留了全角符号,导致[ScriptBlock]::Create()解析时误判为未闭合的字符串终止符,触发报错。
解决方法
方法1:修正脚本文件的符号
打开script.txt,将–AutoSize替换为-AutoSize(确保是英文减号),保存后重新执行原命令即可。
方法2:优化文件读取逻辑
使用Get-Content的-Raw参数读取整个文件为单个字符串,避免换行或编码拆分导致的解析问题:
$scriptContent = Get-Content 'script.txt' -Raw $stdout = Invoke-Command -ScriptBlock ([ScriptBlock]::Create($scriptContent)) *>&1
方法3:更简洁的执行方式
如果无需跨会话执行,可直接用以下方式:
# 直接执行文件内容 & ([ScriptBlock]::Create((Get-Content 'script.txt' -Raw))) *>&1 # 或把文件后缀改为.ps1,直接运行脚本 .\script.ps1 *>&1
内容的提问来源于stack exchange,提问作者Ωmega
相关产品推荐
相关产品推荐

