冒号作为参数中的字符串

时间:2014-02-11 09:41:56

标签: powershell scripting

有没有办法排除冒号(:),所以你可以通过参数作为字符串打印它?

小例子:

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

3 个答案:

答案 0 :(得分:1)

问题不是结肠,而是空间。你需要使用反引号来逃避它:

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

答案 1 :(得分:0)

使用单引号'代替双引号",如此,

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

答案 2 :(得分:0)

你为什么这样运行?从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窗口,现在您应该能够毫无问题地运行本地创建的脚本。