Powershell 根据修剪后的文件名将文件移动到新目标

Powershell Move file to new destination based on trimmed file name

我有一个文件被丢弃的文件夹,我希望从该文件夹中提取文件并根据部分文件名移动到新文件夹。如果新文件夹丢失,则创建它。

我试图将下面的内容放在一起,但是它会抛出关于路径已经存在的错误并且不会移动文件。

文件名可以是除了文件的最后 16 个字符之外的任何没有模式的东西,我正在删除这些并使用剩余的作为文件夹名称。 我真的是脚本编写的新手,所以如果我犯了一个愚蠢的错误,我们将不胜感激。

编辑 我玩过不同的操作顺序,在新项目命令中添加了“-Force”,尝试使用 "Else" 而不是 "If (!("。 我现在正处于它自豪地显示新目录然后停止的地步。 我可以将移动项目部分添加到每个循环的新部分,以便在创建和测试目录后对其进行处理吗?如果是这样,您如何安排 { } 部分?

编辑 2 我终于让它工作了,更新了下面的脚本,当 运行 进入文件名中的特殊字符时,movie-item 命令出现问题,在我的例子中是方括号。 -literalpath 开关为我解决了这个问题。 谢谢各位的意见。

更新脚本 3.0

#Set source folder
$source = "D:\test\source\"
#Set destination folder (up one level of true destination)
$dest = "D:\test\dest\"
#Define filter Arguments
$filter = "*.txt"
<#
$sourcefile - finds all files that match the filter in the source folder
$trimpath - leaves $file as is, but gets just the file name.
$string - gets file name from $trimpath and converts to a string
$trimmedstring - Takes string from $trimfile and removes the last 16 char off the end of the string
Test for path, if it exists then move on, If not then create directory
Move file to new destination
#>
pushd $source
$sourcefile = Get-ChildItem $source -Filter $filter
foreach ($file in $sourcefile){
$trimpath = $file | split-path -leaf
$string = $trimpath.Substring(0)
$trimmedstring = $string.Substring(0,$string.Length-16)
If(!(Test-Path -path "$dest$trimmedstring")){New-Item "$dest$trimmedstring" -Type directory -Force}        
move-Item -literalpath "$file" "$dest$trimmedstring"
}

您可能需要调整正在使用的路径,但以下应该有效。

 $sourcefiles = ((Get-ChildItem $source -Filter $filter).BaseName).TrimEnd(16)
 foreach ($file in $sourcefiles)
 {
     if(!(Test-Path "$dest$file")){
         New-item -ItemType directory -path "$dest$file"
     }
    Move-Item "$source$file" "$dest\file"
 }

我终于让它工作了,更新了下面的脚本,电影项目命令在 运行 进入文件名中的特殊字符时出现问题,在我的例子中是方括号。 -literalpath 开关为我解决了这个问题。感谢大家的参与。

#Set source folder
$source = "D:\test\source\"
#Set destination folder (up one level of true destination)
$dest = "D:\test\dest\"
#Define filter Arguments
$filter = "*.txt"
<#
$sourcefile - finds all files that match the filter in the source folder
$trimpath - leaves $file as is, but gets just the file name.
$string - gets file name from $trimpath and converts to a string
$trimmedstring - Takes string from $trimfile and removes the last 16 char off the end of the string
Test for path, if it exists then move on, If not then create directory
Move file to new destination
#>
pushd $source
$sourcefile = Get-ChildItem $source -Filter $filter
foreach ($file in $sourcefile){
$trimpath = $file | split-path -leaf
$string = $trimpath.Substring(0)
$trimmedstring = $string.Substring(0,$string.Length-16)
If(!(Test-Path -path "$dest$trimmedstring")){New-Item "$dest$trimmedstring" -Type directory -Force}        
move-Item -literalpath "$file" "$dest$trimmedstring"
}