Loop through files and remove part of filename

I need to remove the first 3 chars of every file in my directory. Here is my code:

Get-ChildItem "D:\New Folder" -Filter *.txt |
foreach-object -process {rename-item -path $_.FullName -newname ($_.Remove(0,3))}

I do not understand why this is not working. Can somebody help me?

1 Answer

$_ refers to the file object. Not to the file's name. I suspect that this just slipped your mind since you do refer to $_.Fullname for the -Path. Try referencing the name instead of the object when you rename it:

Get-ChildItem "D:\New Folder" -Filter *.txt |
foreach-object -process {rename-item -path $_.FullName -newname ($_.Name.Remove(0,3))}
1

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

You Might Also Like