Powershell 参数缺少终止符:“

问题描述 投票:0回答:1

我在 powershell arg 设计方面遇到问题,如下 powershell.exe -NoProfile -ExecutionPolicy Bypass -Command "& { $scriptContent = Get-Content -Path 'C:\path o\your\script.ps1' -Raw; $command = "`$scriptContent -key 'BlRznMbcP5azbwi4' -filePath 'C:\path o\your ile.txt'"; 调用表达式 $command }" 我遇到了一些错误,比如 该字符串缺少终止符:“.

  • CategoryInfo:ParserError:(:) [],ParentContainsErrorRecordException
  • FullyQualifiedErrorId:TerminatorExpectedAtEndOfString

因为使用 powershell 在屏幕上输入它们,所以我不喜欢那样使用。但他们按照命令工作 $scriptContent = Get-Content -Path '{0}' -Raw;调用表达式“& {{ $scriptContent }} -key 'BlRznMbcP5azbwi4' -filePath '{1}'” 在我的 .net 应用程序上执行。

我需要有人纠正我的论点

.net powershell
1个回答
0
投票
  • 您的命令行设计为从外部 PowerShell 执行,例如从

    cmd.exe
    或通过直接、无 shell 执行,例如通过
    System.Diagnostics.Process
    .NET API。

    • 在这种情况下,嵌入在整体
      "
      "..."
      参数中的
      -Command
      字符需要转义为
      \"
      ,如您的命令中所示。
  • 不幸的是,从
  • inside

    PowerShell 中,您需要 additional 转义才能满足 PowerShell 的字符串文字语法: \`" - 忽略这样做会导致您看到错误消息。

    
    然而,

      这个
    • double

      转义应该不是必要的,而且实际上不再存在于PowerShell(Core)7(其CLI是pwsh.exe)的v7.3+中 - 请参阅

      这个答案
      了解背景信息。

    • 因此,并且因为从 PowerShell 调用时可能需要对
    • cmd.exe

      /无 shell 命令行进行额外的语法修改,所以最好将命令传递为

      脚本块
      来执行,您只需要满足PowerShell的语法;例如,powershell.exe { "Nat “国王
      " Cole" }
      但请注意,此技术
      仅适用于 PowerShell。
      更根本的是,仅当您需要进程隔离时才需要从PowerShell调用PowerShell CLI,并且调用它涉及启动成本很高的PowerShell子进程。

  • 您的特定命令可以大大简化,这也可以绕过转义要求,并产生可从
both

cmd.exe / 无 shell 调用和 PowerShell 内部运行的命令行:

powershell.exe -NoProfile -ExecutionPolicy Bypass -File "C:\path\to\your\script.ps1" -key "BlRznMbcP5azbwi4" -filePath "C:\path\to\your\file.txt"

请注意使用
-File
参数来传递目标脚本路径,后跟传递参数,以及所有参数如何包含在

"..."

 中(
'...'
 不适用于 
-File
)。
	

© www.soinside.com 2019 - 2024. All rights reserved.