首页 > 解决方案 > 如何继续ps根据文件名的前3个字符创建文件夹

问题描述

我想要一个 powershell 脚本,它会根据文件的日期将文件移动到文件夹中,然后根据文件名的前 3 个字符移动到子文件夹中。我已经能够将文件移动到一个过时的文件夹,但不知道如何继续使用 powershell 创建子文件夹并将文件移动到正确的日期子文件夹。这就是我所拥有的并且正在为该日期工作:

Get-ChildItem \\servername\path\path\path\path\New_folder\*.* -Recurse |     foreach { 
$x = $_.LastWriteTime.ToShortDateString()
$new_folder_name = Get-Date $x -Format yyMMdd
$des_path = "\\servername\path\path\path\path\$new_folder_name"

if (test-path $des_path){ 
move-item $_.fullname $des_path 
} else {
new-item -ItemType directory -Path $des_path
move-item $_.fullname $des_path 
}
}

标签: powershell

解决方案


使用该SubString()方法,您可以提取给定字符串的特定部分:

$SourcePath = '\\servername\path\path\path\path\New_folder'
$DestinationRoot = '\\servername\path\path\path\path'
Get-ChildItem $SourcePath -Recurse -File |
    ForEach-Object { 
        $timeStamp = Get-Date $( $_.LastWriteTime) -Format 'yyMMdd'
        $FirstThreeLettersFromFileName = $_.BaseName.SubString(0,3)
        $destinationPath = "$DestinationRoot\$timeStamp\$FirstThreeLettersFromFileName"

        if (-not (Test-Path -Path $destinationPath)) { 
            New-Item -ItemType Directory -Path $destinationPath
        }
        Move-Item -Path $_.fullname -Destination $destinationPath 
    }

推荐阅读