首页 > 解决方案 > 使用 AutoHotKey 和 Windows 终端通过“-Command”参数将参数传递给 PowerShell

问题描述

我的问题更多地与 PowerShell 相关,但为了完整起见,我使用 AutoHotKey 来运行 PowerShell 命令。

我正在尝试使用“-Command”参数将一些参数传递给 PowerShell,但如果参数包含“特殊”字符,则会遇到问题。

例如,我有三个文件夹:

c:\folder that works
c:\folder doesn't work
c:\[01] folder not working either

我还在使用 Windows 终端 (wt.exe) 测试 PowerShell 5.1(内置于 Windows 10)和新的 PowerShell 7.0.1(便携版)。这些是我尝试使用 AutoHotKey 的命令:

Run, powershell.exe -NoExit -ExecutionPolicy Bypass -Command "Get-ChildItem -Path '%Clipboard%'"
Run, wt.exe "c:\ps7\pwsh.exe" -NoExit -ExecutionPolicy Bypass -Command "Get-ChildItem -Path '%Clipboard%'"

PowerShell 的任何一种用法都适用于不包含特殊字符的文件夹。

对于名称中包含撇号(视为单引号)的文件夹,例如c:\folder doesn't workPowerShell 5.1 会引发以下错误:

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

PowerShell 7.0.1 甚至不会引发错误。它并没有真正显示任何东西。

对于带有方括号“[]”的文件夹,PowerShell 5.1 和 7.0.1 都不会显示任何内容。甚至没有错误。

我认为我在转义字符或正确引用它时遇到了问题。

我非常感谢任何关于如何让我的代码工作的意见。

编辑:忘了提,我正在为 PowerShell 7.0.1 使用 Windows 终端(wt.exe)。

标签: powershellautohotkeywindows-terminal

解决方案


这至少在 cmd 中有效。如果目录为空,则不会显示任何内容。

powershell dir -literal (get-clipboard)
pwsh -c dir -literal (get-clipboard)

推荐阅读