Debbie.S
Debbie.S

Reputation: 167

How can i concatenate a string to a file name in Powershell?

I have the following in powershell to rename

$version = "2.1.1.1"

But i want to make a copy or rename in the same directory as

myprogram_2.1.1.1.exe

The below doesnt work

Rename-Item -Path "C:\myprogram.exe" -NewName "myprogram.exe" + $version

Any help with this ?

Upvotes: 1

Views: 3299

Answers (4)

big J88
big J88

Reputation: 21

Try this:

Rename-Item -Path "c:\myprogram.exe" -NewName "myprogram${version}.exe" 

When including a variable in a double-quoted string without trailing spaces, you can use ${variable} to enclose it.

Upvotes: 1

js2010
js2010

Reputation: 27428

Or:

$version = '2.1.1.1'
dir myprogram.exe | rename-item -newname { $_.BaseName + $version + $_.Extension } -whatif

What if: Performing the operation "Rename File" on target "Item: 
C:\Users\js\myprogram.exe Destination: 
C:\Users\js\myprogram2.1.1.1.exe".

Upvotes: 0

Volkan Paksoy
Volkan Paksoy

Reputation: 6937

You can simply do this:

Rename-Item -Path "C:\myprogram.exe" -NewName "myprogram_$version.exe"

Upvotes: 0

wasif
wasif

Reputation: 15470

Try this:

$version = "2.1.1.1"
$NewName = (Get-Item "C:\myprogram.exe").Basename + "_" + $version + (Get-Item "C:\myprogram.exe").Extension
Rename-Item -Path "C:\myprogram.exe" -NewName "$NewName"

Upvotes: 1

Related Questions