shell - 如何在没有硬编码变量的情况下移动项目
问题描述
我想移动带有.txt扩展名的项目,但不是这样,硬编码。我想从一个文件夹中选择所有具有某些扩展名的文件并将它们移动到一个与扩展名同名的文件夹中。我想对目录中的所有扩展都这样做。
有任何想法吗?谢谢!
看看我的代码,但我是用硬编码的变量来做的
$variable=Get-ChildItem -Path "C:\somePath"
foreach ($variables in $variable)
{
if($extension=($variables | Where {$_.extension -like ".txt"}))
{
New-Item -ItemType Directory -Path "C:\somePath\text"
$extension | Move-Item -Destination "C:\somePath\text"
}
}
解决方案
尽管此解决方案不像其他解决方案那样简洁,但它确实可以处理目标文件夹不存在的情况。它还会移动可能包含特殊字符的文件,例如[]
. 它还明确忽略没有扩展名的文件,因为没有对这些文件给出要求。通过使用Group-Object
.
$Path = "C:\Somepath"
$files = Get-ChildItem -Path $Path -File |
Group-Object -Property {($_.extension |
Select-String -Pattern "[^. ]+").matches.value
}
Foreach ($ExtGroup in $files) {
$Destination = "$Path\$($ExtGroup.Name)"
if (!(Test-Path -Path $Destination -PathType Container)) {
$null = New-Item -Path $Destination -Type Directory
}
Move-Item -LiteralPath $ExtGroup.Group -Destination $Destination -Force
}
推荐阅读
- python - 使用matplotlib python将单独的图绘制成一个图形
- mysql - MySql 识别每个组中的行。
- blockchain - 如何在不每次部署的情况下测试合约?
- ruby - 更新不起作用...我猜是参数问题
- python - 检测是否随时按下键
- flutter - %1 安装错误的 Flutter 不是有效的 win32 应用程序
- asp.net-mvc - 使用 Json.Net 忽略类型集合中的序列化属性
- amazon-eks - 无法在 EKS 集群上创建 PodPreset
- javascript - elementsFromPoint 不包含 mouseover 元素
- ssl - AWS 应用程序负载均衡器上的 Websocket + SSL