如何在自动热键中执行Powershell (.ps1)文件?


Run, powershell.exe C:Usersuser1PoweShellDuplicate Selected Files.ps1

运行上面的例子只是打开蓝色的powershell CMD窗口,它快速闪烁,脚本不运行。

运行下面的示例打开蓝色powershell CMD窗口并保持打开状态,脚本不会运行。

Run, powershell.exe /k C:Usersuser1AppLibExecutablesPoweShellDuplicate Selected Files.ps1

我应该在文件资源管理器中提到,双击.ps1文件在记事本中打开它,我想保持这种行为。我可以在自动热键中实现相同的功能:

Run, C:Usersuser1AppLibExecutablesPoweShellDuplicate Selected Files.ps1

我可以执行.ps1脚本文件在文件资源管理器通过丰富的点击和选择Run with Powershell。如何在自动热键中实现相同的结果?

PS:我知道我可以运行powershell直接在Autohotkey与RunWait, powershell.exe -NoExit -Command "Something here..."我真的需要如何执行.ps1文件保存到文件夹。

任何帮助都将非常感激!我也冒昧地在其他论坛上交叉提问了这个问题。

First Way创建一个变量来存储ps1脚本的路径。

strPsScriptFile := "F:psScripttest.ps1"

如下所示运行powershell脚本,使用Runwait命令使shell保持打开状态

Run, PowerShell.exe  -NoExi  -ExecutionPolicy Bypass -Command %strPsScriptFile%

如果你想传递参数给ps1脚本。例如:传递Name作为第一个,age作为第二个

Run, PowerShell.exe  -NoExi  -ExecutionPolicy Bypass -Command %strPsScriptFile% " Chanu 10"

第二种方式

; hide the terminal
DetectHiddenWindows, On
;path to ps1
Path_To_File := "test.ps1"
Target := "PowerShell.exe -ExecutionPolicy Bypass -File " PathToFile
; terminal location
vComSpec := A_ComSpec ? A_ComSpec : ComSpec
;run the terminal
Run, % vComSpec,, Hide, vPID
WinWait, % "ahk_pid " vPID
DllCall("kernel32AttachConsole", "UInt",vPID)
oShell := ComObjCreate("WScript.Shell")
oExec := oShell.Exec(Target)
vStdOut := ""
while !oExec.StdOut.AtEndOfStream{
; you can read the the output till the execution ends 
}
DllCall("kernel32FreeConsole")
Process, Close, % vPID

参考:

https://www.autohotkey.com/docs/https://www.reddit.com/r/AutoHotkey/comments/ey3pmb/get_hidden_cmdpowershell_output/

最新更新