首页 > 解决方案 > power shell 移动特定文件

问题描述

在此处输入图像描述 我有一个 txt 文件中包含用户 ID 的列表,以及一个包含大量文件和文件夹的文件夹,文件名中包含用户 ID。我正在尝试创建一个脚本,该脚本将从 txt 文件中查找每个用户的 ID,在包含所有文件的文件夹中找到包含用户 ID 的文件,并将匹配的文件移动到由完整文件夹或文件名命名的 EXPORTED 文件夹中已找到。文件名包含名字、姓氏和用户 ID

我在下面尝试了这个,但这只会从 txt 文件中移动具有确切用户 ID 的文件夹...它不会移动文件列表中包含用户 ID 的文件/文件夹

$aryfiles = Get-Content "e:\new\text.txt" 
$sourcedir = "e:\new\" 
$destinationDir = "e:\new\new" 
$sourceFiles = Get-ChildItem -Path $sourceDir -Recurse -Include $aryfiles | Select-Object -ExpandProperty FullName 
foreach ($sourceFile in $SourceFiles) { 
    Move-Item $sourcefile -Destination $destinationDir 
} 

标签: powershell

解决方案


您使用的过滤器中没有通配符Get-ChildItem。使用通配符创建一个新列表并将此列表用于Get-ChildItem

$NewAryFiles = $aryfiles  | foreach {"*$_*"}
$sourceFiles = Get-ChildItem -Path $sourceDir -Recurse -Include $NewAryFiles | Select-Object -ExpandProperty FullName

要使用用户 ID 的名称创建文件夹,请使用New-Item. New-Item创建一个输出,您可以捕获该输出以使用新生成的文件夹。

$aryfiles  | foreach {
    $SourceFile  = Get-ChildItem -Path $sourceDir -Recurse -filter "*$_*"
    $NewFolder = New-Item -ItemType "directory" -Path $destinationDir -Name $_
    foreach ($File in $SourceFile) {
        Move-Item -Path $($File.FullName) -Destination $NewFolder
    }
}

推荐阅读