I am trying to write an automation such that I can given an input as described below and get indicated output and I am using Powershell to do this.
INPUT : Song name in the format given below
Artist Name - Song Name.mp3
OUTPUT : Rename the song file in the format given below
Song Name - Artist Name.Mp3
I understand there are OTS tools for this, but I am trying to ddo this using PowerShell as part of bigger solution.
I have single line PowerShell cmdlet to Get items and then rename them. So I tried this:
Get-ChildItem *.mp3 | Rename-Item -NewName {$_.Name.Substring($_.Name.IndexOf("-")+2, $_.Name.IndexOf(".")) +" - " + $_.Name.Substring(0, ($_.Name.IndexOf("-"))) + ".mp3"}
And here is the problem. The second IndexOf in the substring section gets a null value as it is being used twice in the same (substring) operation twice.
$_.Name.Substring($_.Name.IndexOf("-")+2, $_.Name.IndexOf("."))
This seems to be a thing with PowerShell. Take below lines for example:
Get-ChildItem *.mp3 | Select-Object {$_.Name.Substring($_.Name.IndexOf("-")+2)}
Get-ChildItem *.mp3 | Select-Object {$_.Name.Substring($_.Name.IndexOf(".mp3"))}
When they are separately, Ps gives an output for each run. However, if I run both cmdlets together, only the first line gives an output, second one returns NULL.
How to get an output for the below logic (I am doing a Select here just to troubleshoot as I do not want to actually rename when troubleshooting)
Get-ChildItem *.mp3 | Select-Object {$_.Name.Substring($_.Name.IndexOf("-")+2, $_.Name.IndexOf(".mp3"))}
I can use variables and join strings, but trying to keep the process in one line if possible without writing custom code/module.