使用Powershell从文件夹中的.txt文件创建单个文件夹



初学者在这里!所以先发制人的道歉。我使用的大部分代码只是稍微修改了一下,我刚刚开始学习真正的基础知识,这样我就可以停止修改和自己制作它。

我有一个装满.txt文件的文件夹,我需要制作一个脚本(仍然只是蘸脚趾,所以我没有开始(,为每个文本文件创建一个文件夹。从那时起,我还需要将一两个PDF复制到每个文件夹中。然后他们每个人都拉上了拉链。

因此,我希望通过此操作实现的是,如果我的文本文件列表文件夹充满:

123.txt 234.txt 345.txt(依此类推(

我最终得到一个文件夹,里面装满了包含文本文件的文件夹,每个文件夹都与文本文件同名,所以:

列表文件夹>(文件夹(123(文件夹(234(文件夹(345,其中(文件夹(123包含123.txt,(文件夹(234包含234.txt,依此类推。

然后我有一两个PDF,我想复制到每个文件夹中,所以(文件夹(123将包含123.txt,PDF1和PDF2。并让每个文件夹都发生这种情况,以便它们都包含原始 txt 文件以及一两个 PDF。

然后只需将它们单独压缩,每个文件夹包含 3 个文件(如果有 2 个 PDF 文件(,并以 123.zip、234.zip、345.zip 结尾,依此类推。

我希望这是有道理的。我知道涉及许多步骤必须有一种方法来简化。其中一些文件夹将包含数百个 txt 文件,因此您可以想象手动操作会多么乏味。感谢您的任何帮助和指导!

我刚刚写了一个小脚本,它可以对 txt 文件执行您需要的操作。对于 pdf 文件,您需要指定哪个 pdf 进入哪个文件夹!

完整脚本

$path = "C:temptxt" #Path where all the TXT files are
$pdfpath = "C:temppdf" #Path where all the PDF Files are
$files = Get-Childitem $path | Where-Object { ! $_.PSIsContainer} #Get all files in the folder
#For each file in this folder
foreach ($file in $files){
## If it is a txt file
if ([io.path]::GetExtension($file.Name) -eq ".txt"){ # If it is a .txt file
$foldername = [io.path]::GetFileNameWithoutExtension($file) #Remove the fileextension in the foldername
if (!(Test-Path "$path$foldername")){ #If the folder doesn't exist
New-Item "$path$foldername" -ItemType "directory" #Create a new folder for the file
}
Move-Item $file.FullName "$path$foldername" #Move file into the created folder
}
}
#Create ZIP-Archive
$folders = Get-Childitem $path | Where-Object {$_.PSIsContainer} #Get all folders
foreach ($folder in $folders){
Copy-Item -Path "$pdfpath*" -Destination "$path$folder" #Copy PDF into the folder
Get-Childitem -Path "$path$folder" | Compress-Archive -DestinationPath "$path$folder.zip" #Zip the folder
Remove-item "$path$folder" -Force -Recurse #Remove the folder
}

让我知道它是否有效。 - 尼卡卢

相关内容

最新更新