User command to rename file

English support forum

Moderators: white, Hacker, petermad, Stefan2

Pocus
Junior Member
Junior Member
Posts: 9
Joined: 2009-08-14, 05:44 UTC

User command to rename file

Post by *Pocus »

Could someone please help me with a user command to rename a file from filename.txt to filename_date.txt?

Manually I would do this as per below but how to enter it into the user command dialog in TC?

Code: Select all

C:\> ren filename.txt filename_%date%.txt
User avatar
Horst.Epp
Power Member
Power Member
Posts: 6482
Joined: 2003-02-06, 17:36 UTC
Location: Germany

Re: User command to rename file

Post by *Horst.Epp »

Use the Multirename command in a button and give the name of your saved rename rule as parameter.
The rename mask for example may be:
[N] ([YMD])
Windows 11 Home x64 Version 23H2 (OS Build 22631.3447)
TC 11.03 x64 / x86
Everything 1.5.0.1372a (x64), Everything Toolbar 1.3.3, Listary Pro 6.3.0.73
QAP 11.6.3.2 x64
User avatar
petermad
Power Member
Power Member
Posts: 14796
Joined: 2003-02-05, 20:24 UTC
Location: Denmark
Contact:

Re: User command to rename file

Post by *petermad »

2Pocus

You can use this button:

Code: Select all

TOTALCMD#BAR#DATA
%COMSPEC% /C
ren %N "%O_%%date%%.%E"
WCMICONS.DLL,63
Add date to the filename

1
-1
To make the button:
1. Mark the text in the box here above (click SELECT ALL).
2. Copy it to the ClipBoard (press Ctrl+C).
3. Right click on TC's buttonbar and choose "Paste".
License #524 (1994)
Danish Total Commander Translator
TC 11.03 32+64bit on Win XP 32bit & Win 7, 8.1 & 10 (22H2) 64bit, 'Everything' 1.5.0.1371a
TC 3.50 on Android 6 & 13
Try: TC Extended Menus | TC Languagebar | TC Dark Help | PHSM-Calendar
User avatar
Horst.Epp
Power Member
Power Member
Posts: 6482
Joined: 2003-02-06, 17:36 UTC
Location: Germany

Re: User command to rename file

Post by *Horst.Epp »

petermad wrote: 2020-07-28, 12:07 UTC 2Pocus

You can use this button:

Code: Select all

TOTALCMD#BAR#DATA
%COMSPEC% /C
ren %N "%O_%%date%%.%E"
WCMICONS.DLL,63
Add date to the filename

1
-1
To make the button:
1. Mark the text in the box here above (click SELECT ALL).
2. Copy it to the ClipBoard (press Ctrl+C).
3. Right click on TC's buttonbar and choose "Paste".
This solution has the disadvantage that the sort order will be wrong if a file with different dates exists.
Date should be ([YMD]) for correct sorting.
I prefer the context menu extension ShimExt for such renaming or copying.
https://www.8charmax.com/shimext/
Windows 11 Home x64 Version 23H2 (OS Build 22631.3447)
TC 11.03 x64 / x86
Everything 1.5.0.1372a (x64), Everything Toolbar 1.3.3, Listary Pro 6.3.0.73
QAP 11.6.3.2 x64
User avatar
Stefan2
Power Member
Power Member
Posts: 4157
Joined: 2007-09-13, 22:20 UTC
Location: Europa

PowerShell: Add current timestamp to file name: Base_Time.Ext

Post by *Stefan2 »

Pocus wrote: 2020-07-28, 11:25 UTC Could someone please help me with a user command to rename a file from filename.txt to filename_date.txt?

Manually I would do this as per below but how to enter it into the user command dialog in TC?

Code: Select all

C:\> ren filename.txt filename_%date%.txt


For example with PowerShell command from an button:

FROM:
abc.txt

TO:
abc_2020-07-28 172517.txt     (current time)

USE:

Code: Select all

Command:   PowerShell
Parameters: Get-Content '%WF'|ForEach{$FileName=(GCI $_);Rename-Item -Path $FileName -NewName $('{0}_{1}{2}' -f $FileName.BaseName,([datetime]::now).tostring('yyyy-MM-dd HHmmss'),$FileName.Extension)}
Start path:
Icon file:    PowerShell
Tooltip:     Rename with current timestamp: Base_Time.Ext

Code: Select all

TOTALCMD#BAR#DATA
PowerShell
Get-Content '%WF'|ForEach{$FileName=(GCI $_);Rename-Item -Path $FileName -NewName $('{0}_{1}{2}' -f $FileName.BaseName,([datetime]::now).tostring('yyyy-MM-dd HHmmss'),$FileName.Extension)}
C:\WINDOWS\System32\WindowsPowerShell\v1.0\powershell.exe
Rename with current timestamp: Base_Time.Ext

1
-1

Explanation>>> Button & Button code TOTALCMD#BAR#DATA >> viewtopic.php?p=390697#p390697




Adjust
tostring( ' yyyy-MM-dd HHmmss ' )
to get wanted time string format, f.ex.:
tostring( ' yyyy-MM-dd HHmm ' )
tostring( ' yyyy-MM-dd_HH-mm ' )
tostring( ' yyyy-MM-dd ' )
tostring( ' dd.MM.yyyy ' )


Adjust
$("""{0}_{1}{2}""" -f $FileName.BaseName,([datetime]::now).tostring('yyyy-MM-dd HHmmss'),$FileName.Extension)
abc_2020-07-28 172517.txt
to get the time into the wanted order, like
$("""{1}_{0}{2}""" -f $FileName.BaseName,([datetime]::now).tostring('yyyy-MM-dd HHmmss'),$FileName.Extension)
2020-07-28 172517_abc.txt
or
$("""{0}{2}_{1}{2}""" -f $FileName.BaseName,([datetime]::now).tostring('yyyy-MM-dd HHmmss'),$FileName.Extension)
abc.txt_2020-07-28 172517.txt


{0} ==> $FileName.BaseName
{1} ==> ([datetime]::now).tostring('yyyy-MM-dd HHmmss')
{2} ==> $FileName.Extension


"""...""" is need for use with TC, or try '...' if it works, but only for strings which doesn't need expansions.





And since I need that often too:

FROM:
TOTALCMD.EXE   4.848.656  25.03.2020 08:51   -a--
WINCMD.INI           36.493  28.07.2020 19:09  -a--

TO:
2020-03-25 0851_TOTALCMD.EXE    WriteTime, also possible CreationTime and LastAccessTime
2020-07-28 1909_WINCMD.INI

USE:

Code: Select all

TOTALCMD#BAR#DATA
PowerShell
Get-Content '%WF'|ForEach{$FileName=(GCI $_);Rename-Item -Path $FileName -NewName $('{1}_{0}{2}' -f $FileName.BaseName,(($FileName.LastWriteTime).tostring('yyyy-MM-dd HHmm')),$FileName.Extension)} #CreationTime #LastAccessTime
C:\WINDOWS\System32\WindowsPowerShell\v1.0\powershell.exe
Rename with LastWriteTime: Time_Base.Ext

1
-1



Short version for lame typer:
GC '%F'|%%{$WF=(GCI $_);RNI $F $('{1}_{0}{2}' -f $F.BaseName,(($F.LastWriteTime).tostring('yyyy-MM-dd HHmm')),$F.Extension)}
 
User avatar
petermad
Power Member
Power Member
Posts: 14796
Joined: 2003-02-05, 20:24 UTC
Location: Denmark
Contact:

Re: User command to rename file

Post by *petermad »

Horst.Epp wrote: 2020-07-28, 12:40 UTC
petermad wrote: 2020-07-28, 12:07 UTC 2Pocus

You can use this button:

Code: Select all

TOTALCMD#BAR#DATA
%COMSPEC% /C
ren %N "%O_%%date%%.%E"
WCMICONS.DLL,63
Add date to the filename

1
-1
To make the button:
1. Mark the text in the box here above (click SELECT ALL).
2. Copy it to the ClipBoard (press Ctrl+C).
3. Right click on TC's buttonbar and choose "Paste".
This solution has the disadvantage that the sort order will be wrong if a file with different dates exists.
Date should be ([YMD]) for correct sorting.

Then this should do it - IF the output format of the users %date% is DD-MM-YYYY (29-07-2020):

Code: Select all

TOTALCMD#BAR#DATA
%COMSPEC% /C
ren %N "%O_%%date:~6,4%%-%%date:~3,2%%-%%date:~0,2%%.%E"
WCMICONS.DLL,63
Add date to the filename

1
-1
But the output of %date% is different for different locales of Windows - In US English Windows for example it is: ddd MM/DD/YYYY (Wed 07/29/2020) - we need Pocus to tell us what he's is - and what format of the date he wants - but apparantly he has bee using plain %date% until now.


2Pocus
BTW, if you want it as a user command in stead of a button it would be:

Code: Select all

[em_addatetofilename]
cmd=%COMSPEC% /C
param=ren %N "%O_%%date:~6,4%%-%%date:~3,2%%-%%date:~0,2%%.%E"
iconic=1
Last edited by petermad on 2020-07-29, 16:38 UTC, edited 4 times in total.
License #524 (1994)
Danish Total Commander Translator
TC 11.03 32+64bit on Win XP 32bit & Win 7, 8.1 & 10 (22H2) 64bit, 'Everything' 1.5.0.1371a
TC 3.50 on Android 6 & 13
Try: TC Extended Menus | TC Languagebar | TC Dark Help | PHSM-Calendar
User avatar
MVV
Power Member
Power Member
Posts: 8702
Joined: 2008-08-03, 12:51 UTC
Location: Russian Federation

Re: User command to rename file

Post by *MVV »

Stefan2,
What's always dumb with PowerShell that there is no reliable way to pass filenames: single-quoted argument will fail if filename contains an apostrophe, and double-quoted argument can fail if filename contains a dollar sign...
NotNull
Senior Member
Senior Member
Posts: 269
Joined: 2019-11-25, 20:43 UTC
Location: NL

Re: User command to rename file

Post by *NotNull »

MVV wrote: 2020-07-29, 04:33 UTC Stefan2,
What's always dumb with PowerShell that there is no reliable way to pass filenames: single-quoted argument will fail if filename contains an apostrophe, and double-quoted argument can fail if filename contains a dollar sign...
... or a [ and ] ...

Powershell uses -literalpath for these cases. Try instead:

Code: Select all

gc .\filelist.txt | % { gi -LiteralPath $_ } | % { ren -literalpath $_ ($_.Basename + $_.LastWriteTime.Tostring(' yyyy-MM-dd') + $_.extension) -f }
(Written for and tested in Powershell prompt; adapt to integrate in TC: gc .\filelist.txt has to be replaced with something TC understands)


Stefan2 wrote: 2020-07-28, 15:27 UTC GCI $_
Not tested, but I suspect GCI (Get-ChildItem) goes horribly wrong when you selected a foldername in TC.
Use GI (Get-Item) instead.
User avatar
MVV
Power Member
Power Member
Posts: 8702
Joined: 2008-08-03, 12:51 UTC
Location: Russian Federation

Re: User command to rename file

Post by *MVV »

Well, as I understand, -LiteralPath is for wildcards, and you will not get ones from TC button. But it will not prevent PowerShell from expanding $vars in double-quoted string or confusing due to apostrophes in a single-quoted string. And, if you use $_ in a pipe, you will still need to somehow quote filelist path at the beginning of that pipe. Though, it may be easier since TC usually creates filelists in %TEMP% (of course if your %USERNAME% doesn't contain these problematic characters).

What could really help is supporting both inplace script and arguments in PowerShell command line but there is no such support.
NotNull
Senior Member
Senior Member
Posts: 269
Joined: 2019-11-25, 20:43 UTC
Location: NL

Re: User command to rename file

Post by *NotNull »

MVV wrote: 2020-07-29, 13:13 UTC Well, as I understand, -LiteralPath is for wildcards, and you will not get ones from TC button. But it will not prevent PowerShell from expanding $vars in double-quoted string or confusing due to apostrophes in a single-quoted string. And, if you use $_ in a pipe, you will still need to somehow quote filelist path at the beginning of that pipe. Though, it may be easier since TC usually creates filelists in %TEMP% (of course if your %USERNAME% doesn't contain these problematic characters).

What could really help is supporting both inplace script and arguments in PowerShell command line but there is no such support.

Do you have an example? This is what happens here when renaming the file some$var.txt:

Code: Select all

PS T:\rename-list> Out-File '.\some$var.txt'
PS T:\rename-list> $var = "foo"
PS T:\rename-list> (gi '.\some$var.txt').FullName > thislist.txt
PS T:\rename-list> gc .\thislist.txt
T:\rename-list\some$var.txt
PS T:\rename-list> gc .\thislist.txt | % { gi -LiteralPath $_ }


    Directory: T:\rename-list


Mode                LastWriteTime         Length Name
----                -------------         ------ ----
-a----        29-7-2020     16:02              2 some$var.txt


PS T:\rename-list> gc .\thislist.txt | % { gi -LiteralPath $_ } |  % { ren -literalpath $_ ($_.Basename + "bar"  + $_.extension) -f }
PS T:\rename-list> ls

    Directory: T:\rename-list

Mode                LastWriteTime         Length Name
----                -------------         ------ ----
-a----        29-7-2020     16:02              2 some$varbar.txt
-a----        29-7-2020     16:03             60 thislist.txt

PS T:\rename-list>
User avatar
Stefan2
Power Member
Power Member
Posts: 4157
Joined: 2007-09-13, 22:20 UTC
Location: Europa

Re: User command to rename file

Post by *Stefan2 »

NotNull wrote: 2020-07-29, 07:54 UTC ...
.....
Stefan2 wrote: 2020-07-28, 15:27 UTC GCI $_
Not tested, but I suspect GCI (Get-ChildItem) goes horribly wrong when you selected a foldername in TC.
Use GI (Get-Item) instead.
Huu :shock: thx

You're right, I have to remember to switch GCI by GI, as GI works for files and folder, good improvement!
I had always only the need to work on files.

- - -

My simple script above had no problems with ' and $ in file name.
But there is an problem with [..] and & in names, here helps -LiteralPath

Code: Select all

TOTALCMD#BAR#DATA
PowerShell 
GC '%F'|%%{$F=(GI -LiteralPath $_);RNI -LiteralPath $F $('{1}_{0}{2}' -f $F.BaseName,(($F.LastWriteTime).tostring('yyyy-MM-dd HHmmss')),$F.Extension)}
C:\WINDOWS\System32\WindowsPowerShell\v1.0\powershell.exe
Rename with LastWriteTime: Time_Base.Ext

1
-1




 
User avatar
MVV
Power Member
Power Member
Posts: 8702
Joined: 2008-08-03, 12:51 UTC
Location: Russian Federation

Re: User command to rename file

Post by *MVV »

Ah, I've googled a bit more and now I understood why '[', ']' don't work without -LiteralPath. Stupid M$ documentation on e.g. Get-Item only mentions '*' as a wildcard and doesn't link to about_Wildcards page where '[' and ']' are described.

But '&' doesn't look like a special symbol in PowerShell strings, both GI 'you & me' and GI "you & me" work fine in PowerShell. An ampersand can only cause troubles if it is used inside of a batch file or a cmd.exe command line where it is handled by cmd.exe interpreter internally and must be double-quoted or escaped with '^' to bypass special processing.

But nothing can help in case of e.g. "My $uper girl's photos" name, both quotings in TC button will fail. This name contains an apostrophe so won't work with GI '%N', also it contains a dollar sign so it won't work with GI "%N" too, and -LiteralPath can't do anything with it because PowerShell expands variables itself. This one can only work with GC %WF, but again, it is a question how to properly quote %WF here because it may behave differently depending on symbols in path to %TEMP%.
Last edited by MVV on 2020-07-30, 09:45 UTC, edited 1 time in total.
User avatar
Stefan2
Power Member
Power Member
Posts: 4157
Joined: 2007-09-13, 22:20 UTC
Location: Europa

Re: User command to rename file

Post by *Stefan2 »

Hi MVV :D

- The & is a PS command to execute a string as command.
https://ss64.com/ps/invoke-expression.html
$program = "Get-ChildItem"
Invoke-expression $program
& $program

Me guess that's why it fails without "_literalPath", same as [ and ] let the command fail.


- No problem here with ' and $ while reading from temp list file.
Since %F contains the path to the temporary list file only, and "Get-Content" read that file, and "$_" holds the current line from that list file.
So '%F' works fine, as do """%F""".
FROM: "My $uper girl's photos.txt"
TO . .: "2020-07-30 1015_My $uper girl's photos.txt"
GC '%F'|%%{$F=(GI -LiteralPath $_);RNI -LiteralPath $F $('{1}_{0}{2}' -f $F.BaseName,(($F.LastWriteTime).tostring('yyyy-MM-dd HHmm')),$F.Extension)}

- If you had meant GI '%N' instead (or GI """%N"""), then yes, file names which contains ' is an problem.
Me guess, if we utilize an external script, rather than a command in a button, it's still possible, by replacing the ' char temporarily? ...still to test
In TCs button it seems it's not possible? .... $_-replace(""" ' ""","""#""") .... "The string is missing the terminator: "." ...still to test some more




 
User avatar
MVV
Power Member
Power Member
Posts: 8702
Joined: 2008-08-03, 12:51 UTC
Location: Russian Federation

Re: User command to rename file

Post by *MVV »

But PowerShell will not interpret & inside of a string (regardless of quoting type) as an alias. In my tests this symbol in a filename haven't caused any problems.

Well, %F contains path to temp file, just like %WF mentioned in my previous post and has same problems (i.e. if you set TEMP to a path containing an apostrophe or a dollar sign, or if your USERNAME contains one of these symbols - just try it, it is possible). But %F also has a problem in case of Unicode names, so you should use %WF instead.
User avatar
Stefan2
Power Member
Power Member
Posts: 4157
Joined: 2007-09-13, 22:20 UTC
Location: Europa

Re: User command to rename file

Post by *Stefan2 »

&
Me think I have had an problem with an & in file name, but didn't can reproduce it now. (even w/o the use of -LiteralPath)

TEMP/USERNAME containing
Yes, ok, if somebody does THAT... , maybe then we must not use TCs internal %F parameter but export our own file list (if we feel the joy to do that)

%WF Unicode
Yes, same for German umlauts, so I should always use %WF / %WL from now on in all cases.


Thx :wink:
 
Post Reply