1

I would like to rename just the csv files in my H:/DMU folder. I tried the following code:

 Dir -filter *.csv | %{Rename-Item $_ -NewName ("fn*.csv" -f $nr++)}

I encountered the following error for every file I tried to convert. PowerShell Error Code

I know how to rename all the files in this folder to include the prefix "fn"

Get-ChildItem -Exclude "fn*" |rename-item -NewName {"fn" + $_.Name

, but I just don't know how to rename those of a particular extension.

1 Answer 1

2

Looks like you've copied some code that you don't really understand. Where is $nr & why is it being incremented? YOu don't mention wanting to number the files, just add a prefix.

To rename by adding a simple prefix:

gci -filter *.csv | Rename-Item -NewName { 'fn' +$_.Name }

If you want to number:

[ref]$i = 1
gci -filter *.csv | Rename-Item -NewName { 'fn' + $i.Value++ + $_.Name }

If you want 3-place numbering with preceding zeros:

[ref]$i = 1
gci -filter *.csv | Rename-Item -NewName { 'fn{0:d3}{1}' -f $i.Value++, $_.Name }
2
  • Thank you, I was trying to just add a prefix. I was using code that I modified from another website that referred to renaming a file with a specific extension, but it did not discuss how to prefix multiple files with a specific extension. I did not understand the role of the $nr. So gci is a shorter way of saying get-child-item--that's interesting. Additionally, I didn't know that double quotes and single quotes were interchangeable in PowerShell.
    – Paul NoCal
    Commented Feb 21, 2020 at 21:48
  • Yes, gci is an alias for Get-ChildItem. There are a number pre-defined & you can also define your own. Check the output of Get-Alias. Commented Feb 21, 2020 at 21:51

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .