将参数带有一个引用中的参数到.ps1脚本



我正在测试一个将放入win10右键单击上下文菜单中的PS脚本,该脚本只需接受路径信息,然后将其与我的终端窗口相呼应。注册表的关键如下: ComputerHKEY_CLASSES_ROOT*shellMyScriptcommand @="powershell.exe -window hidden -command .'"G:\path to my script\MyScript.ps1"' '%V'"

脚本只是$args

对于大多数常规路径,它的运行良好。现在,我陷入了文件名中包含一个单一报价的情况,例如"D:John's file.txt"

它引发错误:

The string is missing the terminator: '. + CategoryInfo : ParserError: (:) [], ParentContainsErrorRecordException + FullyQualifiedErrorId : TerminatorExpectedAtEndOfString

我该怎么解决此问题?

我自己找到了解决方案。

  1. 根据这篇文章,必须将注册表条目修改为:ComputerHKEY_CLASSES_ROOT*shellMyScriptcommand @="powershell.exe -window hidden -file "G:\path to my script\MyScript.ps1" "%V""

使用-file代替-command,围绕%V的单引号应为双引号。

2.要获取完整的路径,您必须使用-join操作员像这样(如果路径包含空格(连接空间分隔的字符串:

$path = $args -join " "

PowerShell V6用户可以使用join-string CMDLET。

最新更新