【问题标题】:Colon as string in parameters冒号作为参数中的字符串
【发布时间】:2014-02-11 09:41:56
【问题描述】:

有没有办法排除冒号(:),这样就可以通过参数把它打印成String?

小例子:

PowerShellTest.ps1:

param (
    [string]$message="Error: No message defined!"
);
"Info: Test-Information"
$message;

如果您现在通过 powershell 启动此脚本:

powershell.exe D:\PowerShellTest.ps1 -message "Error: Test-Error"

现在你只得到输出字符串Error:,其余的将被截断

我该怎么做才能得到整个字符串Error: Test-Error

【问题讨论】:

标签: powershell scripting


【解决方案1】:

问题不是冒号,而是空格。您需要使用反引号将其转义:

powershell.exe D:\PowerShellTest.ps1 -message 'Error:` Test-Error'

【讨论】:

  • 就是这样! Ty 但是为什么要排除一个空白呢?其背后的逻辑是什么?
  • 我想这与您处于 powershell 进程并使用这些参数启动另一个进程有关。第一个 shell 需要转义所有数据才能正确地将其发送到新的 shell。正如 vonPryz 建议的那样,如果从普通的 cmd 命令提示符运行,使用单引号就足够了。
【解决方案2】:

像这样使用单引号'而不是双引号"

C:\temp>powershell c:\temp\test.ps1 -message 'Error: Test-Error'
Info: Test-Information
Error: Test-Error

【讨论】:

  • 在 PowerShell 中这有效(没有中断):.\Test.ps1 -message 'Error: Test-Error' 但在 PowerShell 中,这也不起作用(切断):powershell.exe Test.ps1 -message '错误:测试错误'
【解决方案3】:

你为什么这样运行它?当您从 Powershell 内部运行 powershell.exe 时,您将强制参数通过旧的 Windows cmd.exe 样式命令行处理。

您应该直接调用您的脚本:

PS C:\scripts> .\PowershellTest.ps1 -message "Error: Test-Error"
Info: Test-Information
Error: Test-Error

这样,所有参数都将直接通过,而无需转换为字符串,去掉双引号,然后重新解析。

如果由于不允许运行脚本而出现错误,那么答案是更改执行策略,而不是启动 powershell.exe 的另一个副本:

PS C:\scripts> .\PowershellTest.ps1  -message "Error: Test-Error"
.\PowershellTest.ps1 : File C:\scripts\PowershellTest.ps1 cannot be loaded because running scripts is disabled on this
system. For more information, see about_Execution_Policies at http://go.microsoft.com/fwlink/?LinkID=135170.
At line:1 char:1
+ .\PowershellTest.ps1  -message "Error: Test-Error"
+ ~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : SecurityError: (:) [], PSSecurityException
    + FullyQualifiedErrorId : UnauthorizedAccess

如果您看到此错误,请使用“以管理员身份运行”选项启动 Powershell 窗口并输入命令:

Set-ExecutionPolicy RemoteSigned

关闭管理员 powershell 并重新启动您正在运行的任何其他 powershell 窗口,现在您应该能够毫无问题地运行本地创建的脚本了。

【讨论】:

  • 这很清楚。我只是将我的问题减少到最低限度。在现实世界中,它将通过 Java 应用程序执行和监控。
  • @5im 我认为在减少您的问题时,您将其更改为另一个问题。遗留程序通过单个字符串接收它们的参数。当您使用 Powershell 调用此类程序时,您必须考虑 PS 如何将命令参数转换为命令行字符串,然后再考虑命令如何解析该字符串。当您从 Java 运行它时,您需要考虑将一组完全不同的转换为命令行字符串,然后进行相同的解析。任何逃避例如两者之间的空间可能会有所不同。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-11-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-05-18
  • 1970-01-01
相关资源
最近更新 更多