简体   繁体   English

如何从命令行将带括号的参数传递给 Powershell?

[英]How to pass a parameter with parentheses to Powershell from command line?

I have a Powershell script called MSSQLStartStopServices.ps1 used to stop some SQL Server services.我有一个名为MSSQLStartStopServices.ps1的 Powershell 脚本,用于停止一些 SQL 服务器服务。 This script is being called using a third-party vendor software.正在使用第三方供应商软件调用此脚本。 The parameters in question are Fully qualified instance name and Start|Stop有问题的参数是Fully qualified instance nameStart|Stop

eg例如

MSSQLStartStopServices.ps1 HOSTNAME\INSTANCENAME Start

For a default instance, the software passes (local) as the INSTANCENAME.对于默认实例,软件将(本地)作为 INSTANCENAME 传递。

MSSQLStartStopServices.ps1 HOSTNAME\(local) Start

But when I run this I get an error from Powershell:但是当我运行它时,我从 Powershell 收到一个错误:

The term 'local' is not recognized as the name of a cmdlet, function, script file, or operable program.术语“本地”不能识别为 cmdlet、function、脚本文件或可运行程序的名称。 Check the spelling of the name, or if a path was included, verify that the path is correct and try again.检查名称的拼写,或者如果包含路径,请验证路径是否正确并重试。

When I try and put the instance name in quotes it works fine in a Powershell window:当我尝试将实例名称放在引号中时,它在 Powershell window 中工作正常:

MSSQLStartStopServices.ps1 "HOSTNAME\(local)" Start

However the third party software calls Powershell from the commandline first, like so:然而,第三方软件首先从命令行调用 Powershell,如下所示:

powershell .\MSSQLStartStopServices.ps1 "HOSTNAME\(local)" Start

This causes the same error as if the quotes were not there.这会导致与引号不存在相同的错误。

How do I work around this issue?我该如何解决这个问题?

尝试将脚本调用括在双引号中,然后将每个参数括在单引号中:

".\MSSQLStartStopServices.ps1" 'HOSTNAME\(local)' 'Start'

Adding this information for any future people with a smiliar issue finding this page:为任何未来有类似问题的人添加此信息:

In case you want to use a variable as a parameter value that contains characters such as "(" or "|", you need to do it like this: -parameter_name ("'" + $variable + "'")如果您想使用包含“(”或“|”等字符的变量作为参数值,则需要这样做: -parameter_name ("'" + $variable + "'")

This worked for me since powershell would remove any double quotes added to the string when calling a non powershell method.这对我有用,因为 powershell 在调用非 powershell 方法时会删除添加到字符串中的任何双引号。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM