I am trying to rename or remove part of a filename. I have a scheduled job that moves an updated file from one server to another. Once the file is moved it need to be renamed. For example: Filename_01-23-AB.exe
to Filename.exe
I want to remove everything from the "_" to the "." and leave the extension intact. I found the following code that should do this but I can't seem to get it to work. Am I headed down the right path here?
## Removes the build number from the filename of "Filename_XX-XX-XX.exe" leaving the new filename to be "Filename.exe" ##
$File = -Path "C:\Temp\TestPath\"
foreach ($File in gci *.exe) {
$Fname = ($File.name).split('.')[0] ## item before the '.' ##
$Prefix = $Fname.split('_')[0] ## item before the '_' ##
$Newname = $Prefix + '.exe'
Rename-Item $file $Newname
}