根据基本名称的x个数字字符分组项目 [英] Group items based on x number characters of basename
问题描述
我得到了帮助来设置一个巧妙的脚本,该脚本根据基本名称和LastWriteTime对文件夹中的项目进行分组,它使我可以删除除给定数量的文件(即5个版本)以外的所有内容.现在,我想将基本名称分组限制为8个字符.
I got help to setup a clever script that groups items in a folder based on basename and LastWriteTime it lets me delete everything except given number of files (i.e 5 versions). Now I'd like to limit basename grouping to 8 characters.
gci C:\test\ |
where{-not $_.PsIsContainer} |
$file = basename
Group-Object $file.substring(8) |
foreach {
$_.Group |
sort LastWriteTime -Descending |
Select -Skip 5 |
foreach { Remove-Item $_.fullname -Force -WhatIf }
}
由于我真的是Powershell的新手,所以不确定上面的方法是否正确.
As I'm really new to powershell I'm not sure if above is correct approach.
推荐答案
如果要按前8个字符分组,则需要 Substring(0,8)
. Substring(8)
将产生从第9个字符到字符串结尾的子字符串.另外,如果要按当前对象的属性分组,则可以在脚本块中定义它们.
If you want to group by the first 8 characters, you need Substring(0, 8)
. Substring(8)
will produce the substring from the 9th character to the end of the string. Also, if you want to group by properties of the current object, you define them in a scriptblock.
更改此:
gci C:\test\ |
where{-not $_.PsIsContainer} |
$file = basename
Group-Object $file.substring(8) | ...
对此:
Get-ChildItem 'C:\test' |
Where-Object {-not $_.PSIsContainer} |
Group-Object { $_.Basename.Substring(0,8) } | ...
请注意,如果基本名称少于8个字符,则 Substring(0,8)
将引发错误.例如,可以通过将长度定义为最小值8和字符串长度来避免这种情况:
Note that Substring(0,8)
will throw an error if the basename is shorter than 8 characters. You can avoid that for instance by defining the length as the minimum of 8 and string length:
$_.Basename.Substring(0, [Math]::Min(8, $_.Basename.Length))
这篇关于根据基本名称的x个数字字符分组项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!