简体   繁体   English

在Powershell中按版本号对文件进行排序

[英]Files sorting with version number in Powershell

I have this folder in a directory. 我在目录中有此文件夹。 With different version on them. 在它们上面有不同的版本。

CD1,CD2,CD3,CD4,CD5,CD6,CD7,CD8,CD9,CD11,CD12

I'm new to powershell, can anyone help me to get the latest version folder from the above folders? 我是Powershell的新手,有人可以帮助我从上述文件夹中获取最新版本的文件夹吗? Here CD12 is the latest folder. CD12是最新的文件夹。 I can't use last modified time because I copy them at the same time. 我不能使用上次修改时间,因为我同时复制了它们。

$FolderName=(Get-ChildItem C:\Current\CD |Where-Object {$_.name -like "*CD*"}| sort{$_.name.Substring(2,2)}|Select-Object Name -Last 1).Name)
Write-Host "$FolderName"

I tried the above script and it did not help. 我尝试了上述脚本,但没有帮助。 Can anyone help me? 谁能帮我? The next new version is CD13 , and the script should get that folder 下一个新版本是CD13 ,脚本应获取该文件夹

You can try something like below 您可以尝试以下类似的方法

$max_version = Get-ChildItem "C:\Current\" | Where-Object {$_.PSIsContainer} 
| Foreach-Object {$_.Name} | Foreach-object {$_ -replace "CD", ""} 
| measure -maximum | Select-Object -expand Maximum

Write-host ("CD" + $max_version)

Which will result in CD12 这将导致CD12

You almost have it. 差不多了 When I tried to run your code, I ran into two errors. 当我尝试运行您的代码时,遇到两个错误。 First, you have an extra ')' at the end of the line causing a syntax error. 首先,在行尾有一个额外的')',导致语法错误。 Second, your 'SubString()' call is failing because you're trying to get the 3rd and 4th characters of a string without a 4th character ("CD1"). 其次,您的“ SubString()”调用失败,因为您试图获取不带第四个字符(“ CD1”)的字符串的第三个和第四个字符。 You don't need the scriptblock to your Sort command, though. 但是,您不需要脚本块来执行Sort命令。 You can just sort on the Name field. 您可以仅在“名称”字段上排序。

$FolderName = Get-ChildItem C:\7005\Hot-Fix\CD | where Name -like "CD*" | sort Name | Select-Object -Last 1 -ExpandProperty Name

As a side note, this uses the PowerShell 3 syntax for Where-Object and Sort-Object to omit the {} . 附带说明一下,此方法将PowerShell 3语法用于Where-ObjectSort-Object来省略{} And it uses the -ExpandProperty parameter to Select-Object , so you don't have to wrap the whole thing in parens to get the Name property. 并且它对Select-Object使用-ExpandProperty参数,因此您不必将整个内容包装在parens中即可获得Name属性。

You could try this: 您可以尝试以下方法:

#requires -v 3
$baseFolder='C:\7005\Hot-Fix\CD'
$folder=dir $baseFolder\CD* -Directory | 
    ? basename -CMatch 'CD\d{1,}' | 
    sort @{e={'{0:0000}' -f [int]($_ -replace '\D')}} -Descending | 
    select -First 1

Notice, I'm considering case sensitive matching; 注意,我正在考虑区分大小写的匹配; also, $folder contains what you're looking for. 同样, $folder包含您要查找的内容。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM