原文:
AutoHotkey官方论坛:
FileToCMD: Pass selected files as variables to CMD - AutoHotkey Community
作者:william_ahk
译文:
问题:
通常,我们需要使用命令行实用程序(如Image Magick、ffmpeg等)来处理一些文件。每次都使用略微或完全不同的参数(或者您键入的速度非常快,所以即使每次参数相同也没关系)。将文件粘贴到CMD中很容易,但将文件路径作为静态参数放置在命令行中很不方便,因为它很长,很难在每个参数之间导航。因此,最好将文件路径设置为环境变量。
方案:
GetActiveExplorerPath()它在Windows资源管理器(或Ctrl-C产生文件路径的任何文件资源管理器)中检索所选文件,将其拆分为文件名、扩展名、不带扩展名的名称和目录,并将它们设置为相应的变量。
GetSelectedFilePaths() 还可以选择多个文件,将文件列表填充到了for循环集合中。
#SingleInstance Force
#Requires AutoHotkey v2.0
!s::FileToCMD()
FileToCMD() {
static echolim := 80
cli := "cmd.exe"
cd := GetActiveExplorerPath()
if InStr(cd, "\") {
sel := GetSelectedFilePaths()
if (sel != "") {
cli .= ' /k "'
vars := Map()
StrReplace(sel, "`r`n", , , &cnt)
input := RTrim(sel, "`r`n")
if (cnt = 1) {
SplitPath(input, &file, &dir, &ext, &name)
vars["%input%"] := '"' input '"'
vars["%file%"] := file
vars["%name%"] := name
vars["%dir%"] := dir
vars["%ext%"] := "." ext
} else {
input := '"' StrReplace(input, '`r`n', '" "') '"'
vars["%count%"] := cnt
vars["%~ff"] := "Full path of the iterated file."
vars["%~f"] := "Name of the iterated file with extension."
vars["%~nf"] := "Name of the iterated file without extension."
vars["%~pf"] := "Directory of the iterated file."
vars["%~xf"] := "Extension of the iterated file with dot."
vars["%each%"] := "for %f in (" input ") do"
}
for var, val in vars {
if (A_Index != 1)
cli .= "&&"
if (SubStr(var, -1) == "%")
cli .= "set " Trim(var, "%") "=" val "&&"
cli .= '@echo ' var ' = ' StrReplace(StrLen(val) > echolim ? SubStr(val, 1, echolim - 3) '...' : val, '"', '^"')
}
cli .= '"'
}
workingdir := cd
} else {
workingdir := A_Desktop
}
Run(cli, workingdir)
}
GetActiveExplorerPath() {
explorerHwnd := WinActive("ahk_class CabinetWClass")
if explorerHwnd
for window in ComObject("Shell.Application").Windows
if (window.hwnd == explorerHwnd)
return window.Document.Folder.Self.Path
}
GetSelectedFilePaths() { ; Thanks to teadrinker https://www.autohotkey.com/boards/viewtopic.php?t=60403#p255169
winClass := WinGetClass("ahk_id" . hWnd := WinExist("A"))
result := ""
if (winClass ~= "Progman|WorkerW|(Cabinet|Explore)WClass") {
shellWindows := ComObject("Shell.Application").Windows
if (winClass ~= "Progman|WorkerW")
shellFolderView := shellWindows.Item( ComValue(VT_UI4 := 0x13, SWC_DESKTOP := 0x8) ).Document
else {
for window in shellWindows
if (hWnd = window.HWND) && (shellFolderView := window.Document)
break
}
for item in shellFolderView.SelectedItems
result .= item.Path "`r`n"
} else {
ClipSave := ClipboardAll()
A_Clipboard := ""
SendInput("^c")
ClipWait(2)
result := A_Clipboard
A_Clipboard := ClipSave
}
return result
}
以Image Magick为例:
将选定的png文件转换为jpg。
magick convert %input% "%name%.jpg"
将所有选定的文件转换为jxl。
%each% magick convert "%~f" "%~nf.jxl"
- end ^_^