I'm new to PowerShell, and have written the following script, using ISE, trying to rename a bunch of folders in the same directory, that strictly have the date format 20201130 into 2020-11-30 (simply adding dashes) the script kinda works, but I have 3 problems with it.
1- when it ran it threw a bunch of errors relating to Rename-Item
the error:
Rename-Item : Source and destination path must be different.
At line:13 char:25
+ ... ChildItem | Rename-Item -NewName { $_.Name -replace $file, $MyNewName ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : WriteError: (D:\Google Drive...Term 2\testings:String
) [Rename-Item], IOException
+ FullyQualifiedErrorId : RenameItemIOError,Microsoft.PowerShell.Commands.Renam
eItemCommand
2- when I tested it with a folder named (234567890) it still worked although the lenght of this folder is not eq to 8!
3- when the above renaming happened the resulting name was "1234-56-7890" which is strange since $MyNewName
should end with 2 characters! $file.Substring( 6 , 2 )
the script:
$FileNameArr_All = (Get-ChildItem).Name
$i = 0
foreach($file in $FileNameArr_All){
if ( ($file -match "^\d+$") -and ($file.Length -eq 8) ){
[string] $MyNewName = $file.Substring( 0 , 4 )+"-"+$file.Substring( 4 , 2 )+"-"+$file.Substring( 6 , 2 )
#the actual renamining of the item, where the error is:
Get-ChildItem | Rename-Item -NewName { $_.Name -replace $file, $MyNewName }
$message = "the item " + $file + " has been renamed : " + $MyNewName
Write-Output $message
$i ++
Write-Output $file.Length
}
}
if ($i -eq 0){
Write-Output "No mathcing items found."
}
else{
$message2 = "total of items affected: " + $i
Write-Output $message2
}
I know that's a lot but its my first post, and my first script, I appreciate helping with any of the points.
Many thanks :)