尝试使用powershell根据文件的扩展名和文件夹名称将文件放入文件夹中

问题描述 投票:0回答:3

我有一个包含三个文件的目录:.xlsx,.docx和.txt,在同一目录中也有名为xlsx,docx和txt的文件夹。基本上是尝试将每个文件放入其相应的文件夹中,以练习PowerShell的技能。我是PowerShell的新手,并尝试了以下方法。我可以说出它的错误,但我不太确定为什么。

$folders = Get-ChildItem -Directory
$files = Get-ChildItem -File
foreach ($file in $files) {
        foreach ($folder in $folders) {
                 if ("*$file.extension*" -like "*$folder.Name*") {
                         move-item $file -Destination "C:\Users\userA\Desktop\$folder.name"
                 }
         }
}
powershell
3个回答
1
投票

请尝试下面的代码。使用Where-Object功能,您可以找到相应的文件。我删除了该点,因为否则它包含在扩展名中。

$folders = Get-ChildItem -Directory

$files = Get-ChildItem -File

foreach ($file in $files) {
    $folder = $folders | Where-Object { $_.Name -Like $file.Extension.Replace(".","") }
    Move-Item -Path $file -Destination $folder
}

在您的示例中,请注意字符串的实际解释方式。如果您有"*$item.Name*",则字符串实际上为“ * 变量。Name *”。在这种情况下,您需要使用"*$($var.Name)*"来获取正确的字符串。


0
投票

以下是对您的方法进行的一些调整,使其可以使用。将-Destination参数分解为一个单独的变量$ newpath,可以在其中设置调试语句,以便可以轻松检查其创建内容。

$folders = Get-ChildItem -Directory
$files = Get-ChildItem -File
foreach ($file in $files) {
        foreach ($folder in $folders) {
                 if ($file.extension.trim(".") -like $folder.Name) {
                         $newpath = ("{0}\{1}" -f $folder.FullName, $file.Name)
                         move-item $file -Destination $newpath
                 }
         }
}

0
投票

如果扩展名还不存在,您甚至可以为其创建目标文件夹:

$SourceFolder = C:\sample
$TargetFolder = D:\sample

Get-ChildItem -Path $SourceFolder -File |
    ForEach-Object{
        $DesinationFolder = Join-Path -Path $TargetFolder -ChildPath $_.Extension.TrimStart('.')
        if(-not (Test-Path -Path $DesinationFolder)){
            New-Item -Path $DesinationFolder -ItemType Directory | Out-Null
        }
        Copy-Item -Path $_.FullName -Destination $DesinationFolder -Force 
    }
© www.soinside.com 2019 - 2024. All rights reserved.