简体   繁体   中英

Passing arguments to PowerShell with “-Command” parameter using AutoHotKey and Windows Terminal

My question pertains more toward PowerShell, but for completeness I am using AutoHotKey to run the PowerShell command.

I'm trying to pass some arguments to PowerShell with the "-Command" parameter, but running into issues if the arguments contain "special" characters.

For example, I have three folders:

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

I am also testing both PowerShell 5.1 (built-in to Windows 10) and new PowerShell 7.0.1 (portable version) with Windows Terminal (wt.exe). These are the commands I have tried using 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%'"

Either usage of PowerShell works with folders that don't contain special characters.

With a folder that has an apostrophe (seen as a single quote) in the name, such as c:\folder doesn't work , PowerShell 5.1 throws the following error:

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

PowerShell 7.0.1 doesn't even throw an error. It doesn't show anything really.

With a folder that has square brackets "[]", both PowerShell 5.1 and 7.0.1 don't show anything either. Not even an error.

I think I have an issue with escaping the characters or quoting it properly.

I would really appreciate any input on how I can get my code to work.

EDIT: Forgot to mention, I am using Windows Terminal ( wt.exe ) for PowerShell 7.0.1.

This works in cmd at least. If the directory is empty, it won't show anything.

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

With some experimentation, I have a partial answer to my own problem. Both PowerShell 5.1 and 7.0.1, by themselves ( without the use of Windows Terminal ), work when using the following commands in AutoHotKey:

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

For some reason, I had to escape the quotes surrounding the AutoHotKey's %Clipboard% , three times using `" (backtick/grave and double quote)

But once I added Windows Terminal (wt.exe) to AutoHotKey's Run command, it would fail on all three folders in some way. I think I'll create a separate question just for Windows Terminal.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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