5

I have a problem with change extension of a file. I need to write a script which is replicating data, but data have two files. Filename is not a string, so we can't use normal -replace

I need to get from

filename.number.extension

this form

filename.number.otherextension

We try to use a split, but this command show us things like below

filename
number
otherextension

Thanks for any ideas,

5 Answers5

7
[System.IO.Path]::ChangeExtension("test.old",".new")
Florian Wachs
  • 101
  • 1
  • 6
3

You probably want something like the -replace operator:

'filename.number.extension' -replace 'extension$','otherextension'
  • The $ is regular expression syntax meaning end of line. This should ensure that the -replace does not match "extension" appearing elsewhere in the filename.
veefu
  • 2,820
  • 1
  • 19
  • 29
1

A simple Utility Function

<#
 # Renames all files under the given path (recursively) whose extension matches $OldExtension.
 # Changes the extension to $NewExtension
 #>
function ChangeFileExtensions([string] $Path, [string] $OldExtension, [string] $NewExtension) {
    Get-ChildItem -Path $Path -Filter "*.$OldExtension" -Recurse | ForEach-Object {
        $Destination = Join-Path -Path $_.Directory.FullName -ChildPath $_.Name.Replace($OldExtension, $NewExtension)
        Move-Item -Path $_.FullName -Destination $Destination -Force
    }
}

Usage

ChangeFileExtensions -Path "c:\myfolder\mysubfolder" -OldExtension "extension" -NewExtension "otherextension"

But it can do more than just this. If you had the following files in the same folder as your script

    example.sample.csv
    example.txt
    mysubfolder/
        myfile.sample.csv
        myfile.txt

this script would rename all the .sample.csv files to .txt files in the given folder and all subfolders and overwrite any existing files with those names.

# Replaces all .sample.csv files with .txt extensions in c:\myfolder and in c:\myfolder\mysubfolder
ChangeFileExtensions -Path "c:\myfolder" -OldExtension "sample.csv" -NewExtension "txt"

If you don't want it to be recursive (affecting subfolders) just change

"*.$OldExtension" -Recurse | ForEach-Object

to

"*.$OldExtension" | ForEach-Object
TxRegex
  • 2,347
  • 21
  • 20
1

This could work:

Get-ChildItem 'C:\Users\Administrator\Downloads\text files\more text\*' *.txt | rename-item -newname { [io.path]::ChangeExtension($_.name, "doc") }
techguy1029
  • 743
  • 10
  • 29
0

You can remove the last item with the the [0..-1] slice and add the new extension to that

(("filename.number.extension" -split "\.")[0..-1] -join '.') +".otherextension"
Jim W
  • 421
  • 5
  • 6