首页 > 解决方案 > 如何在没有硬编码变量的情况下移动项目

问题描述

我想移动带有.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"
   }
}

标签: shellpowershell

解决方案


尽管此解决方案不像其他解决方案那样简洁,但它确实可以处理目标文件夹不存在的情况。它还会移动可能包含特殊字符的文件,例如[]. 它还明确忽略没有扩展名的文件,因为没有对这些文件给出要求。通过使用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
}

推荐阅读