Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using PowerShell to add an extension to files

Tags:

powershell

I have a directory of files that I'd like to append file extension to as long as they don't have an existing, specified extension. So add .txt to all file names that don't end in .xyz. PowerShell seems like a good candidate for this, but I don't know anything about it. How would I go about it?

like image 908
John Sheehan Avatar asked Oct 30 '08 21:10

John Sheehan


People also ask

How do I add an extension to a file?

You can also do it by right-clicking on the unopened file and clicking on the “Rename” option. Simply change the extension to whatever file format you want and your computer will do the conversion work for you.

How do you append a file in PowerShell?

In PowerShell, the Add-Content cmdlet is used to append data in a file. The content which needs to be appended is specified in this command. Here, -Path tells the exact location of the file, and the -Value is the text which will be appended in it.

How do I get the file extension in PowerShell?

Use the Get-ChildItem cmdlet to get the file item and using its Extension property it returns the file name extension. The Get-ChildItem command accepts the file path as input and gets the file item. It then passes the output to the Select command to get file extension using the Extension property.

How do I add the file extensions to all files in a folder?

You can do this by going to My Computer and then going to Tools and Folder Options. In Windows 7, click on the Organize button and then click Folder and search options. In Windows 8, you just click on the View tab in Explorer and check the File name extensions box.


2 Answers

Here is the Powershell way:

gci -ex "*.xyz" | ?{!$_.PsIsContainer} | ren -new {$_.name + ".txt"}

Or to make it a little more verbose and easier to understand:

Get-ChildItem -exclude "*.xyz" 
    | WHere-Object{!$_.PsIsContainer} 
    | Rename-Item -newname {$_.name + ".txt"}

EDIT: There is of course nothing wrong with the DOS way either. :)

EDIT2: Powershell does support implicit (and explicit for that matter) line continuation and as Matt Hamilton's post shows it does make thing's easier to read.

like image 84
EBGreen Avatar answered Sep 19 '22 15:09

EBGreen


+1 to EBGreen, except that (at least on XP) the "-exclude" parameter to get-childitem doesn't seem to work. The help text (gci -?) actually says "this parameter does not work properly in this cmdlet"!

So you can filter manually like this:

gci 
  | ?{ !$_.PSIsContainer -and !$_.Name.EndsWith(".xyz") } 
  | %{ ren -new ($_.Name + ".txt") }
like image 34
Matt Hamilton Avatar answered Sep 20 '22 15:09

Matt Hamilton