Powershell-获取固定数量的文件并将其移动到新文件夹
我正在寻找类似我找到的powershell脚本:Powershell-获取固定数量的文件并将其移动到新文件夹,powershell,Powershell,我正在寻找类似我找到的powershell脚本: Get-ChildItem -File | # Get files Group-Object { $_.Name -replace '_.*' } | # Group by part before first underscore ForEach-Object { # Create directory $dir = New-Item -Type Directory -Name $_.Name # Move fi
Get-ChildItem -File | # Get files
Group-Object { $_.Name -replace '_.*' } | # Group by part before first underscore
ForEach-Object {
# Create directory
$dir = New-Item -Type Directory -Name $_.Name
# Move files there
$_.Group | Move-Item -Destination $dir
}
但不同的是,组对象应该从文件夹a中获取固定数量的5个文件,创建一个以第一个文件命名的新文件夹,并将5个文件移动到新文件夹中。请参见下面的示例图片(文件名不同)。
我是powershell中的一个该死的新手,所以如果可能的话,请保持简单的建议;)
谢谢和问候 谢谢@tessellingheckler,它工作得很好
$n = 0; Get-ChildItem -File | Group-Object -Property {$script:n++; [math]::Ceiling($n/5)} |
ForEach-Object {
$dir = New-Item -Type Directory -Name $_.Name # Create directory
$_.Group | Move-Item -Destination $dir # Move files there
}
对于重命名部分,我使用@Dennis van Gils()中的批处理
我相信有一种方法可以与powershell部分一起使用,但这个解决方案适合我
你好。如果要创建以第一个文件命名的新文件夹,也可以尝试此操作:
谢谢@Vitaly!该解决方案运行良好。
以下是完整的脚本:
$n = 0; Get-ChildItem -File | Group-Object -Property {$script:n++; [math]::Ceiling($n/5)} |
ForEach-Object {
$dname = $_.group.name
$fname=$dname
$fl = $fname[0].Split(".")[0]
$dir = New-Item -Type Directory -Name $fl
$_.Group | Move-Item -Destination $dir
}
@Paul:
组对象
根据文件名中(第一个)\uu
之前的共享文件名前缀对输入文件进行分组。然后,ForEach对象
对每个结果组进行操作,创建一个以共享前缀命名的目录,并将组中的所有文件移动到该新目录中。@nosdaver:您只想从每个组中获取前5个文件吗?如果您想跨组进行分区,则不清楚您想要的是什么逻辑。请通过直接更新您的问题来澄清。将分组更改为计数器除以5,并四舍五入到最接近的整数$n=0;获取ChildItem-File | Group Object-Property{$script:n++;[math]::天花($n/5)}ForEach Object{这里的代码}
可以it@TessellatingHeckler:谢谢。它缝起来了,有点用。结果:脚本列出的文件是正确的,但命名是错误的,它只以数字5开头(下一个GROUP 6等等),没有字母。新项目有一些错误:+$dir=New Item-Type Directory-Name$\ Name+CategoryInfo:ResourceExists:(“路径”)[New-Item],IOException+FullyQualifiedErrorId:DirectoryExist,Microsoft.PowerShell.Commands.newitemcond,第一个错误导致移动项目无法工作。很抱歉,错过了第一个,组的编号从1开始,而不是像我写的那样从5开始!非常感谢你。工作完美!它只需要删除以foldernames结尾的文件。如果不需要使用文件扩展名,可以替换此$fname=$dname。替换(“.”,“”)$fl=$fname[0]上的:$fname=$dname$fl=$fname[0]。拆分(“.”[0]
$n = 0; Get-ChildItem -File | Group-Object -Property {$script:n++; [math]::Ceiling($n/5)} |
ForEach-Object {
$dname = $_.group.name
$fname=$dname
$fl = $fname[0].Split(".")[0]
$dir = New-Item -Type Directory -Name $fl
$_.Group | Move-Item -Destination $dir
}