将命令从 Autohotkey 传递到 PowerShell 的路径问题

Path issue with passing a command from Autohotkey to PowerShell

Mypath := "C:\temp\example1.txt"
Run, powershell -command "get-content -path %Mypath% | Set-Clipboard"

上面的工作正常,内容被 PowerShell 复制到剪贴板但是当我做同样的事情但是文件名中有 space 时它无法 运行在 PowerShell 中。

运行低于

Mypath := "C:\temp\example 1.txt"
Run, powershell -command "get-content -path %Mypath% | Set-Clipboard"

我在 PowerShell 中遇到此错误

Get-Content : A positional parameter cannot be found that accepts argument '1.txt'.

我也试过在每一边都使用双引号,并像这样使用 Autohotkeys 转义符号:

Mypath = "`"C:\temp\example 1.txt`""
Run, powershell -command "get-content -path %Mypath% | Set-Clipboard"

以及

Mypath = ""C:\temp\example 1.txt""
Run, powershell -command "get-content -path %Mypath% | Set-Clipboard"

但在这两种情况下,PowerShell 都会抛出此错误;

The string is missing the terminator: ".

我做错了什么?任何帮助将不胜感激。

这很奇怪,但可以让它工作。真的是逃脱地狱
让我们来看看你的每一次尝试都出了什么问题。


Mypath := "C:\temp\example 1.txt"
Run, powershell -command "get-content -path %Mypath% | Set-Clipboard"

这里你不是使用遗留语法为变量Mypath赋值,你应该这样做。
不再使用遗留语法是件好事。
但是,由于您没有使用旧语法,而是使用现代赋值运算符 :=(docs),因此您没有任何额外的引号 " 围绕字符串。
因此,您正在使用以下开关执行 PowerShell:
-command "get-content -path C:\temp\example 1.txt | Set-Clipboard".
正如您猜到的那样,这是错误的,因为您的文件名未被引用。


Mypath = "`"C:\temp\example 1.txt`""
Run, powershell -command "get-content -path %Mypath% | Set-Clipboard"

您又在使用旧语法。所以任何字符串都是按字面解释的。因此,首先没有理由试图转义引号 ",其次你 don't escape quotes in AHK with `.
因此,在这次尝试中,您将使用以下开关执行 PowerShell:
-command "get-content -path ""C:\temp\example 1.txt"" | Set-Clipboard".
这并不好,因为首先 "" 被评估为单个 ",然后你有
-command "get-content -path "C:\temp\example 1.txt" | Set-Clipboard"
在另一个引号内有未转义的引号 ",所以这样不好。


Mypath = ""C:\temp\example 1.txt""
Run, powershell -command "get-content -path %Mypath% | Set-Clipboard"

然后你遇到了与上一个问题完全相同的问题。因为,正如我们所确定的,您不能使用 ` 转义引号。此代码与上面的代码完全相同。


那么,应该怎么做呢?

您要么需要在文件路径周围再添加一对转义引号 ",要么只对内引号使用单引号。


所以在旧语法中你可能想要:

Mypath = """"C:\temp\example 1.txt""""
Run, powershell -command "get-content -path %Mypath% | Set-Clipboard"

Mypath = 'C:\temp\example 1.txt'
Run, powershell -noexit -command "get-content -path %Mypath% | Set-Clipboard"

并且在 现代表达式语法 中,您需要:

Mypath := """""""""C:\temp\example 1.txt"""""""""
Run, % "powershell -noexit -command ""get-content -path " Mypath " | Set-Clipboard"""

Mypath := "'C:\temp\example 1.txt'"
Run, % "powershell -noexit -command ""get-content -path " Mypath " | Set-Clipboard"""