PowerShell 脚本(foreach 循环问题)

PowerShell Script (foreach-loop problems)

我有一个简短的问题,但是我现在站在墙上太久了,所以我不得不问你...... 情况是: 我有一个特殊的文件类型,在不同的文件夹和子文件夹中。 我已经设法找到文件,将它们写入一个 TXT 文件,我还设法拆分路径,以便我可以用文件夹名称和日期命名一个 ZIP 文件。 但我唯一不明白的是如何只将 folder1 的特殊文件压缩到 Zip-archiv "folder1-date.zip" 和 folder2 的文件到 Zip-archiv "folder2-date.zip ”。 代码部分如下所示:

[string[]]$dirs = (Split-Path (Split-Path -Path $output -Parent) -Leaf | Foreach-Object { $i++; $_ })
[string[]]$arrayFromFile = Get-content -Path 'C:\TEMP\output.txt'
foreach ($file in $arrayFromFile) {
foreach ($dir in $dirs){
#
Compress-Archive -Path $file -CompressionLevel Optimal -Update -DestinationPath $destination$dir-$date.zip }
}

问题是,每个带扩展名的文件都在每个 ZIP-Archiv 中(逻辑是因为它是 foreach 中的 foreach)但我找不到正确的方法.... 感谢您的帮助!

这将获得所需的结果,而不必将输出保存到文本文件。

$origin = "C:\TEMP\"
$filetyp = ".stl, .vol, .pct, .tif"
$destination = "C:\Daten\zipstore\"
$date = $(Get-Date -Format d)


$fileNames = Get-ChildItem "$origin" -Recurse | Where {$_.extension -eq ".stl"} | ForEach-Object { $_.FullName }

foreach ($file in $fileNames) {

    $dir = (Split-Path (Split-Path -Path $file -Parent) -Leaf)
    
    Compress-Archive -Path $file -CompressionLevel Optimal -Update -DestinationPath $destination$dir-$date.zip
}

谢谢您的回答!这里有完整的代码:

# Variablen Definition: 
# 
$origin = "C:\TEMP\"
$filetyp = ".stl, .vol, .pct, .tif"
$destination = "C:\Daten\zipstore\"
$date = $(Get-Date -Format d)
#
#
# Auslesen aller Files die bestimmte Dateiendung haben: 
#
Get-ChildItem "$origin" -Recurse | Where {$_.extension -eq ".stl"} | ForEach-Object { $_.FullName } > C:\TEMP\output.txt
#
#
# Remove filename, keep path to file / split and only keep last directory:
#
$output = Get-content C:\TEMP\output.txt
$i = 0
#
[string[]]$dirs = (Split-Path (Split-Path -Path $output -Parent) -Leaf | Foreach-Object { $i++; $_ })
#
#
# Create ZIP-Archiv:
#

[string[]]$arrayFromFile = Get-content -Path 'C:\TEMP\output.txt'
foreach ($file in $arrayFromFile) {
foreach ($dir in $dirs){
#
Compress-Archive -Path $file -CompressionLevel Optimal -Update -DestinationPath $destination$dir-$date.zip }
}
#
# 
# Delete files not needed anymore:
Remove-Item -Path $origin -Include *.txt -Recurse -Force
#

也许这有帮助!