2

I have been trying to write a script to remove end part of the filename and replace it with a version number of a build. I have tried trim and split but because of extra dots and not good with regex, im having problems.

These are file examples:

Filename.Api.sow.0.1.1856.nupkg
something.Customer.Web.0.1.1736.nupkg

I want to remove 0.1.18xx from these filenames and add a build number from variable. which would be something like 1.0.1234.1233 (major.minor.build.revision)

so the end result should be:

Filename.Api.sow.1.0.1234.1233.nupkg
something.Customer.Web.1.0.112.342.nupkg

Here is my try to split and then rename. But it doesnt work.

$files = Get-ChildItem -Recurse | where {! $_.PSIsContainer}
foreach ($file in $files)
{
$name,$version = $file.Name.Split('[0-9]',2)
Rename-Item -NewName "$name$version" "$name".$myvariableforbuild
}
Martin Brandl
  • 56,134
  • 13
  • 133
  • 172
spiceitup
  • 132
  • 10

2 Answers2

1

You are almost there. Here a solution with regex:

$myVariableForBuild = '1.0.1234.1233'
Get-ChildItem 'c:\your_path' -Recurse | 
    where {! $_.PSIsContainer} | 
    Rename-Item -NewName { ($_.BaseName -replace '\d+\.\d+\.\d+$', $myVariableForBuild) + $_.Extension }
Martin Brandl
  • 56,134
  • 13
  • 133
  • 172
0

Probably not the most concise way to do it, but I would split the string based on ".", get the last element of the array (the file extension), then iterate through each array element. If its non-numeric append it to a new string, if numeric break the loop. Then append the new version and file extension to the new string.

$str = "something.Customer.Web.0.1.1736.nupkg"
$arr = $str.Split(".")

$extension = $arr[$arr.Count - 1]
$filename = ""
$newversion = "1.0.112.342"

for ($i = 0 - 1; $i -lt $arr.Count; $i++)
{
    if ($arr[$i] -notmatch "^[\d\.]+$")
    {
        # item is not numeric - add to string
        $filename += $arr[$i] + "."
    }
    else
    {
        # item is numeric - end loop
        break
    }    
}

# add the new version
$filename += $newversion + "."

# add the extension
$filename += $extension

Obviously its not a complete solution to your problem, but there is enough there for you to get going.

Asnivor
  • 266
  • 1
  • 8