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

PowerShell命令手动运行正常 存为ps1脚本报语法错误的原因及解决

PowerShell 脚本执行异常问题排查结果
  • 相同PowerShell命令手动复制粘贴到已打开的终端窗口运行完全正常
  • 代码保存为.ps1格式脚本文件后,右键选择「使用PowerShell运行」时抛出语法错误

问题代码示例:

$confirmation = Read-Host "Change DNS?"
if ($confirmation -eq 'y') 
{
    Set-DNSClientServerAddress "Ethernet" –ServerAddresses ("1.1.1.1","8.8.8.8")
}
pause

问题根源为复制代码时带入了非标准特殊字符:Set-DNSClientServerAddress 命令的ServerAddresses参数前的短横线为非标准的Unicode特殊短横线,PowerShell脚本解析器无法识别该字符,因此抛出语法错误。手动粘贴到终端时系统会自动做字符兼容转换,因此不会触发报错。

解决方案

  • 找到脚本中Set-DNSClientServerAddress行–ServerAddresses前的非标准短横线
  • 删除该符号后手动输入标准半角短横线-

修正后可正常运行的代码:

$confirmation = Read-Host "Change DNS?"
if ($confirmation -eq 'y') 
{
    Set-DNSClientServerAddress "Ethernet" -ServerAddresses ("1.1.1.1","8.8.8.8")
}
pause

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 19:36:02