对于 Windows 中的给定文件夹,请说
$currentDir = Get-Location
我希望递归搜索这两个文件夹 json
和 txt
,它们必须位于 db_execute
文件夹下。
下面是我的 powershell,但它不能按预期工作。
# Define the names of the folders to search for
$folderNames = "db_execute\json", "db_execute\txt"
$zipFileName = "Folders.zip"
$currentDir = Get-Location
# Create an empty zip file
Compress-Archive -LiteralPath $currentDir -DestinationPath $zipFileName -CompressionLevel Optimal -Update
# Loop through each folder name
foreach ($folderName in $folderNames) {
# Find all the subdirectories with the given name in the current directory recursively
$subDirs = Get-ChildItem -Path $currentDir -Directory -Recurse -Filter $folderName
# Loop through each subdirectory
foreach ($subDir in $subDirs) {
# Add the subdirectory to the zip file
Compress-Archive -LiteralPath $subDir.FullName -DestinationPath $zipFileName -CompressionLevel Optimal -Update
}
}
这会创建一个具有多个文件和文件夹的
Folder.zip
,但我需要它只包含这两个文件夹db_execute_scripts\json,db_execute_scripts\txt
及其内容。
$currentDir
| -- source
|--- repo
| db_execute
|--- txt
|--- json
注意
db_execute
可以位于 $currentDir 内的任何位置。以上只是一个例子,这个结构可能会改变。
想要的
Folders.zip
|--- db_execute
|--- txt
|--- json
您能否建议我在 PowerShell 中做错了什么?
@Ashar,你可以使用这个脚本来实现你的要求
# Define the names of the folders to search for
$folderNames = "db_execute_scripts\json", "db_execute_scripts\txt"
$zipFileName = "Folders.zip"
$currentDir = Get-Location
# Loop through each folder name
foreach ($folderName in $folderNames) {
# Find the folder with the given name in the current directory recursively
$folder = Get-ChildItem -Path $currentDir -Directory -Recurse -Filter $folderName
# Check if the folder exists
if ($folder) {
# Add the folder and its contents to the zip file
Compress-Archive -LiteralPath $folder.FullName -DestinationPath $zipFileName -CompressionLevel Optimal -Update
}
}