【问题标题】:How to continue ps to create folder based upon first 3 characters of file name如何继续 ps 根据文件名的前 3 个字符创建文件夹
【发布时间】:2019-01-29 12:16:54
【问题描述】:

我想要一个 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 
}
}

【问题讨论】:

  • 你可以看看字符串对象的.SubString()方法。 ;-) 这里有一些很有帮助的链接:link1link2
  • 感谢您的所有帮助。

标签: powershell


【解决方案1】:

使用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 
    }

【讨论】:

  • $_.LastWriteTime 已经是 [datetime],您可以使用 -format operator $destinationPath = "{0}\{1:yyMMdd}\{2}" -f $DestinationRoot,$_.LastWriteTime,$_.BaseName 一步构建
  • 我想让 Shirley 更基本一些。 ;-)
猜你喜欢
  • 2018-12-09
  • 2021-07-13
  • 1970-01-01
  • 2016-12-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多