2016-12-02 83 views
2

我一直在尝试编写一个脚本来删除文件名的末尾部分,并将其替换为版本号。我曾尝试修剪和拆分,但由于额外的点和正则表达式不好,即时通讯有问题。拆分并将文本/数字添加到文件名

这些文件的例子:

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

我想删除这些文件名0.1.18xx和变量添加一个版本号。这将是像1.0.1234.1233(major.minor.build.revision)

所以最终的结果应该是:

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

这是我尽量拆分,然后重命名。但它不起作用。

$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 
} 

回答

1

你快到了。这里用一个正则表达式的解决方案:

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

你可以删除你的地方,如果你在GCI – Esperento57

+0

指定-file @ Esperento57他还使用'PsIsContainer'在他的代码,因此他极有可能使用PowerShell的V2,其中'-file '开关丢失。所以我可能*无法删除在这里。 –

+0

他没有指定他的版本。也许他不知道 - 文件太;) – Esperento57

0

可能不是最简洁的方式做到这一点,但我会分裂基于字符串“”,获得数组(文件扩展名),然后通过各个数组元素的最后一个元素。如果它的非数字附加到一个新的字符串,如果数字中断循环。然后将新版本和文件扩展名附加到新字符串中。

$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 

很明显,它不是一个完整的解决方案,但您的问题已经足够了。