gpt4 book ai didi

regex - 根据Powershell中的文件名将文件移动到新位置

转载 作者:行者123 更新时间:2023-12-02 23:28:13 24 4
gpt4 key购买 nike

我有一个文件夹(没有子文件夹),其中充满了成千上万种格式不同的文件(pdf,xls,jpeg等)。
这些文件没有通用的命名结构,唯一与它们相关的模式是文件名中的某个地方有字母PN,紧随其后的是6位数字。 PNxxxxxx代码可能出现在文件名的任何位置,无论是在开头,结尾,空格还是其他字符之间。

多个文件可以共享相同的PN代码,例如,pdf,xls和jpeg的标题中都可能带有PN854678。

我为powershell编写了一个脚本,试图将所有文件与可能共享相同代码的任何其他文件一起移动到新位置,在该位置将它们放置到文件夹中(可能存在或可能不存在)。该文件夹的名称后应有PN,后跟正确的6位数字。

当我尝试运行脚本时,什么也没有发生,我没有收到任何错误或任何提示。我认为代码将执行,并且源文件夹和目标文件夹未更改。只是为了确认,我使用了set-executionpolicy remotesigned并尝试使用cmd.exe运行脚本。

这是代码,请记住,这是我第一次尝试使用Powershell,而且我一般都不熟悉脚本编写,因此,如果我犯了任何愚蠢的错误,我深表歉意。

# Set source directory to working copy
$sourceFolder = "C:\Location A"

#Set target directory where the organized folders will be created
$targetFolder = "C:\Location B"

$fileList = Get-Childitem -Path $sourceFolder
foreach($file in $fileList)
{
if($file.Name -eq "*PN[500000-999999]*") #Numbers are only in range from 500000 to 999999
{

#Extract relevant part of $file.Name using regex pattern -match
#and store as [string]$folderName

$pattern = 'PN\d{6}'

if($file.Name -match $pattern)
{
[string]$folderName = $matches[0]
}


#Now move file to appropriate folder

#Check if a folder already exists with the name currently contained in $folderName
if(Test-Path C:\Location B\$folderName)
{
#Folder already exists, move $file to the folder given by $folderName
Move-Item C:\Location A\$file C:\Location B\$folderName
}
else
{
#Relevant folder does not yet exist. Create folder and move $file to created folder
New-Item C:\Location B\$folderName -type directory
Move-Item C:\Location A\$file C:\Location B\$folderName
}

}
}

最佳答案

文件是否全部存在于一个文件夹或一系列子文件夹中?您没有提及它,但是请记住,您需要在-recurse上添加Get-Childitem才能从子文件夹中获取结果。
问题的根源是子句$file.Name -eq "*PN[500000-999999]*"-eq并非要处理名片。我建议这个简单的选择

$file.Name -match 'PN\d{6}'

但是,您指定的数字必须在一定范围内。让我们对所有内容进行一些更新。
# Set source directory to working copy
$sourceFolder = "C:\Location A"

#Set target directory where the organized folders will be created
$targetFolder = "C:\Location B"

foreach($file in $fileList)
{
# Find a file with a valid PN Number
If($file.Name -match 'PN[5-9]\d{5}'){
# Capture the match for simplicity sake
$folderName = $matches[0]

#Check if a folder already exists with the name currently contained in $folderName
if(!(Test-Path "C:\Location B\$folderName")){New-Item "C:\Location B\$folderName" -type directory}

#Folder already exists, move $file to the folder given by $folderName
Move-Item "C:\Location A\$file" "C:\Location B\$folderName"
}

}
  • 不要忘了引用您的字符串。您可以将变量放在双引号引起来的字符串中,它们会适当扩展。
  • $file.Name -match 'PN([5-9]\d{5})'要做的是查找包含PN的文件,后跟5到9之间的任何数字,再加上5个数字。那应该照顾500000-999999标准。
  • 另外,您还是要移动文件。用Move-Item将行两次都没有意义。相反,只需检查路径即可。如果不是(!),则创建文件夹。
  • 关于regex - 根据Powershell中的文件名将文件移动到新位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27140072/

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