#PSTip One way to change a file extension

Modifying a file always brings a risk of corrupting it; making a backup copy whenever possible is one of the file manipulation best-practices. One way of doing it is to create a copy with the same name and appropriate extension like ‘bak’. This task can be finished in a few different ways. Here is my favorite–using the Copy-Item cmdlet and the ChangeExtension() method of the System.IO.Path class:

$path = 'C:\temp\ImportantFile.txt'
Copy-Item -Path $path –Destination ([io.path]::ChangeExtension($path, '.bak')) -Verbose
Filed in: Columns, Tips and Tricks Tags: ,

4 Responses to "#PSTip One way to change a file extension"

  1. peSHIr says:

    .NET Framework method System.IO.Path.ChangeExtension() is a great way to safely change the extension of a path string. However, for the purpose stated here, I’d rather add “.bak” to the end of a filename path to create a backup file name instead of replacing the existing extension with “bak”.

    Consider this: you have files test.dat, test.txt and test.docx in the same folder, and you proces test.data. This gives you a backup file test.bak, but which file would that backup be from? I’d rather have my script resulting in a file named “test.data.bak”…

Leave a Reply

Submit Comment

© 8165 PowerShell Magazine. All rights reserved. XHTML / CSS Valid.
Proudly designed by Theme Junkie.
%d bloggers like this: