【问题标题】:Keep quotes in $args using PowerShell使用 PowerShell 在 $args 中保留引号
【发布时间】:2014-04-08 16:53:34
【问题描述】:

是否可以在$args 中保留引号?

脚本是这样调用的:

.\test1.ps1 a=application o="this object" msg_text="this is a text"

报价对于进一步处理是强制性的。有没有办法将它们保留在$args 中?

【问题讨论】:

  • 这些字符串总是需要被引用吗?

标签: powershell command-line-arguments


【解决方案1】:

您可以在 PowerShell 中使用反引号转义引号:

.\test1.ps1 a=application o="`"this object`"" msg_text="`"this is a text`""

您也可以将双引号嵌套在单引号内(反之亦然),但请注意变量不会在单引号分隔的字符串中计算。

.\test1.ps1 a=application o='"this object"' msg_text='"this is a text"'

另外,为什么要使用$args?为什么不使用强大的内置参数系统?

进一步阅读:

Get-Help About_Quoting_Rules

Stack Overflow - How to Handle Command Line Arguments in PowerShell

TechNet Magazine - Windows PowerShell: Defining Parameters

【讨论】:

  • 我尝试使用内置系统,但我只提供脚本,不影响参数的格式
  • +1 这是一个很好的答案,比我的更详细(就附加引用和 Powershell 的脚本参数功能而言。我将根据无法执行的附加要求删除/替换我的答案修改脚本的输入。
  • @CJBS 直到我发布了我的答案后我才看到你的答案(我想我们彼此在一两分钟内发布了)。 +1 对您的新答案,我认为这是解决 OP 问题的一个非常聪明的方法。
  • 如何从命令行传递字符串并避免 powershell 进行变量替换...例如:show-string.ps1 \\pc2(share1) 如果我将参数括在单引号中可以正常工作...但我不希望用户担心这个...并且 powershell 在第 1 行立即失败...不给我机会 '''work''' 论点...
【解决方案2】:

我能想到的唯一方法是不能修改输入参数,但仍然需要修改调用的命令。

为了保留引号,或许可以尝试捕获调用 PowerShell 脚本时使用的完整命令行。

所以我把它放在 test1.ps1 脚本中:

Write-Host (Get-WmiObject -Query "select CommandLine from Win32_Process where CommandLine like '%test1%'").CommandLine

如果以这种方式调用脚本,则返回如下:

PS C:\temp> powershell .\test1.ps1 a=application o="this object" msg_text="this is a text"
"C:\Windows\system32\WindowsPowerShell\v1.0\powershell.exe"  .\test1.ps1 a=application "o=this object" "msg_text=this is a text"

这只有在调用新的 PowerShell 实例时才有可能,否则此方法将无法使用参数:

PS C:\temp> .\test1.ps1 a=application o="this object" msg_text="this is a text" > zzz3.txt

PS C:\temp>

当然,如果采用这种方法,您将需要手动解析输入参数,您可以借助 $args 对象来完成。这是一个远射,但确实保留了引号。

【讨论】:

  • 见上面的评论 ;) 不幸的是,我无法影响参数的格式
  • 我修改了答案以从 WMI 获取完整的命令行。这是一个远射,但可能会让你朝着正确的方向前进。
猜你喜欢
  • 1970-01-01
  • 2017-06-24
  • 2017-04-22
  • 1970-01-01
  • 2021-09-28
  • 1970-01-01
  • 2021-07-15
  • 1970-01-01
  • 2013-12-04
相关资源
最近更新 更多