I have three files named First_File.txt Second_File.txt Thrid_File.txt in a folder named C:\01Source I want to add the current date to the filenames so they look like this: First_File_20220909.txt
The terminal output is this:
What if: Performing the operation "Rename File" on target "Item: C:\01Source\First_File.txt Destination: C:\01Source\First_File_20220909.txt". (runs for all three files names)
BUT... when I look in the C:\01Source folder the filenames are not changed, they are still First_File.txt
What did I miss?
This is my code:
$Path = "C:\01Source\"
write-host $Path
$curDateTime = Get-Date -Format yyyyMMdd
Get-ChildItem $Path -Recurse |
Rename-Item -NewName {$_.Basename + '_' + $curDateTime + $_.Extension } -WhatIf
Abraham Zinala has provided the crucial pointer:
The
-WhatIfcommon parameter in the command above only previews the operation without actually performing it.-WhatIfis to do a "dry run" that allows you to confirm that the command will work as intended when actually run, so as to prevent potentially costly mistakes.That is, the message you saw,
What if: Performing the operation "Rename File" on ..., tells you what would happen if you re-ran the command WITHOUT-WhatIf.-WhatIffrom the end of yourRename-Itemcall in order to perform actual renaming.Note that not all cmdlets support
-WhatIf- generally only those with potentially destructive consequences.Cmdlets that support
-WhatIfalso support the common-Confirmparameter (and vice versa), which requests that a per-input-object confirmation prompt be shown before processing.To see whether a given cmdlet supports
-WhatIf/-Confirm, look for[-WhatIf]/[-Confirm]in the syntax diagrams output byGet-Helpor when you pass the-?switch, or when you useGet-Command-Syntax; e.g.,Rename-Item -?orGet-Command -Syntax Rename-Item.Alternatively, as you're typing a command, try tab completion (type something like
-Wha, then press Tab to see if it auto-completes to-WhatIf).It is possible to implement support for
-WhatIfand-Confirmin your own functions and scripts, as long as they are advanced ones, as the following example shows:Sample call after defining the above function: