gpt4 book ai didi

powershell - 如何基于文件名的前3个字符继续ps创建文件夹

转载 作者:行者123 更新时间:2023-12-02 23:52:57 26 4
gpt4 key购买 nike

我想要一个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()方法,您可以提取给定字符串的特定部分:

$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
}

关于powershell - 如何基于文件名的前3个字符继续ps创建文件夹,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54420885/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com