powershell - 如何继续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
}
}
解决方案
使用该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
}
推荐阅读
- java - 使用 openAPI 通过 REST 发送 protobuf 数据
- javascript - Next.js 中的 JSON 输入意外结束
- android - 在android中创建即时活动过渡动画
- python - Pyspark:用同名的另一列替换行值
- python - 我们可以将 json 响应映射到类似于 Jackson 中的 Object mapper 的 python 对象吗?
- r - 用因子值替换 1 和 0
- php - Symfony Order 表字段使用原则
- vba - 从 VBA 脚本中提取变量名
- python - Tensorflow如何从输入和输出的元组创建数据集
- shell - 如何在 macOS 的终端中中断“睡眠”?