1
votes

I want to create an AutoHotKey script which will open powershell console (in the same folder opened in file explorer window) and execute the following code:

$nrRef = [ref] 0
Get-ChildItem -Filter *.jpg | Rename-Item -Newname {
'{0}_{1:d3}.jpg' -f (Split-Path -Leaf $_.DirectoryName), ++$nrRef.Value}

then close powershell console window.

Note: Shortcut to start AHK script: Ctrl + Shift + LeftMouseButton being pressed in the specific folder in explorer window.

1
Alternatively, you could call the script using a Context Menu handler so that you can right click on the folder and select something like "Rename JPG files". This saves running your AHK file in the background all the time.samthecodingman

1 Answers

0
votes
#NoEnv
#SingleInstance Force

#IfWinActive, ahk_class CabinetWClass ; explorer

    ; Ctrl + Shift + LeftMouseButton
    ^+LButton::
        ActivePath := GetExplorerActivePath()
        code =
        (
        $nrRef = [ref] 0
        Get-ChildItem -Filter *.jpg | Rename-Item -Newname {
        '{0}_{1:d3}.jpg' -f (Split-Path -Leaf $_.DirectoryName), ++$nrRef.Value}
        )
        Run powershell.exe -windowstyle hidden -Command &{%code%}, %ActivePath%
    return

#IfWinActive

; get the path of the active file explorer:
GetExplorerActivePath(){
    WinGetTitle, ActiveTitle, A
    If InStr(ActiveTitle, "\")  ; If the full path is displayed in the title bar (Folder Options)
        ActivePath := ActiveTitle
    else
    If InStr(ActiveTitle, ":") ; If the title displayed is something like "DriveName (C:)"
    {
        ActivePath := SubStr(ActiveTitle, -2)
        ActivePath := SubStr(ActivePath, 1, -1)
    }
    else ; If the full path is NOT displayed in the title bar 
    ; https://autohotkey.com/boards/viewtopic.php?p=28751#p28751
    for window in ComObjCreate("Shell.Application").Windows
    {
        try ActivePath := window.Document.Folder.Self.Path
        SplitPath, ActivePath, title
        If (title = ActiveTitle)
            break
    }
    return ActivePath
}

https://autohotkey.com/docs/commands/_IfWinActive.htm