基于文件名移动文件的Powershell脚本

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

我正在研究将文件从USB设备移动到桌面的脚本。文件应根据文件名以单独的顺序排列:

文件:

xx_xx_122.xx
xx_xx_143.xx
xx_xx_129.xx

文件夹:

xx_122
xx_143
xx_129

当前停留在这里:

$sourceFolder = "C:\Schule"


$targetFolder = "C:\Privat"

foreach($file in $fileList)
{

    If($file.Name -match "122"){

        $folderName = $matches[0]


        if(!(Test-Path "C:\Schule\$folderName")){New-Item "C:\Privat\$folderName" -type directory} 

        Move-Item "C:\Schule\$file" "C:\Privat\$folderName"                  
    }

}
windows powershell scripting filenames move
1个回答
0
投票

您可以使用正则表达式来做。

我认为您想要这样的东西:

$sourceFolder = "C:\Temp\powershell\files"
$targetFolder = "C:\Temp\powershell\folder"

$files = Get-ChildItem $sourceFolder

foreach($file in $files){
    if($file.name -match "(_)(?!.*\1)(.*)\."){
        $newFolderName = $matches[2]
        $newFolderPath = "$targetFolder\$newFolderName"
        if(!(Test-Path $newFolderPath)){
            New-Item $newFolderPath -type directory
        }
        Move-Item "$sourceFolder\$file" $newFolderPath
    }
}

输入:

C:\Temp\powershell\files
|-def_122.txt
|-abc_132.txt

输出:

C:\Temp\powershell\folder
|-122
  |-def_122.txt
|-132
  |-abc_132.txt
© www.soinside.com 2019 - 2024. All rights reserved.