Скрипт powershell для распаковки в определенную именованную папку - PullRequest
0 голосов
/ 20 февраля 2019

У меня есть несколько zip-файлов, которые сгенерировали такие имена, как 21321421-12315-sad3fse-23434fg-ggfsd, что не помогает идентифицировать содержимое zip-файла.

Мне нужен скрипт, который распаковывает его и затем ищет pdf-файлс частично сгенерированным и статическим именем, например asdawd-ersrfse-231-Formular2311.

После этого он должен создать папку с именем файла pdf и разархивировать все содержимое zip-файла в эту папку.

До сих пор мне оставались только фрагменты, которые работают друг за другом, но я все еще застрял.

$shell = new-object -com shell.application
$CurrentLocation = get-location
$CurrentPath = $CurrentLocation.path
$Location = $shell.namespace($CurrentPath)

# Find all the Zip files and Count them
$ZipFiles = get-childitem -Path "C:\Install\NB\Teststart" *.zip
$ZipFiles.count | out-default

# Set the Index for unique folders
$Index = 1

# For every zip file in the folder
foreach ($ZipFile in $ZipFiles) {

    # Get the full path to the zip file
    $ZipFile.fullname | out-default

    # Set the location and create a new folder to unzip the files into - Edit the line below to change the location to save files to
    $NewLocation = "C:\Install\NB\Testfinal\$Index"
    New-Item $NewLocation -type Directory

    # Move the zip file to the new folder so that you know which was the original file (can be changed to Copy-Item if needed)
    Copy-Item $ZipFile.fullname $NewLocation

    # List up all of the zip files in the new folder 
    $NewZipFile = get-childitem $NewLocation *.zip

    # Get the COMObjects required for the unzip process
    $NewLocation = $shell.namespace($NewLocation)
    $ZipFolder = $shell.namespace($NewZipFile.fullname)

    # Copy the files to the new Folder
    $NewLocation.copyhere($ZipFolder.items())

    # Increase the Index to ensure that unique folders are made
    $Index = $Index + 1
}

Get-ChildItem -Path "C:\Install\NB\Testfinal" -Include "*.pdf" -Recurse | ForEach-Object {
    $oldFolder = $_.DirectoryName

    # New Folder Name is .pdf Filename, excluding extension
    $newFolder = $_.Name.Substring(0, $_.Name.Length - 4)

    # Verify Not Already Same Name
    Write-Host "Rename: $oldFolder To: $newFolder"
    Rename-Item -NewName $newFolder -Path $oldFolder
}

Ответы [ 2 ]

0 голосов
/ 21 февраля 2019

В тех же строках, что и ваш собственный скрипт, сначала распакуйте zip-файлы, а затем переименуйте извлеченную папку в файл pdf:

$SourceDir = 'C:\Install\NB\Teststart'
$ExtractDir = 'C:\Install\NB\Testfinal'

# Extract each zip to a folder with the same name as the zip file (BaseName)
Get-ChildItem (Join-Path $SourceDir *.zip) | foreach {
    Expand-Archive $_.FullName -DestinationPath (Join-Path $ExtractDir $_.BaseName)
}

# Rename the PDF's parent folder to the same as the PDF
Get-ChildItem (Join-Path $ExtractDir *.pdf) -Recurse | foreach {
    Rename-Item -Path $_.Directory.FullName -NewName $_.BaseName
}
0 голосов
/ 20 февраля 2019

Это должно сделать, и это намного проще, чем у вас есть.Он опирается на .NET 4.5, который у вас уже должен быть на вашем сервере:

[Reflection.Assembly]::LoadWithPartialName('System.IO.Compression.FileSystem')

# Get all the zip files in the root of the script, change $PSScriptRoot accordingly
Get-ChildItem -Path $PSScriptRoot -Filter *.zip -Recurse | ForEach-Object {
    # Open the archive for reading
    $zip = [IO.Compression.ZipFile]::OpenRead($_.FullName)

    # Find the name of the PD file from the archive entries
    $archiveName = $zip.Entries | `
        Where-Object { [System.IO.Path]::GetExtension($_.FullName) -eq '.pdf' } | `
        Select-Object @{N = "BaseName"; E = {[System.IO.Path]::GetFileNameWithoutExtension($_.FullName)}} |
        Select-Object -Expand BaseName

    # Close the zip file
    $zip.Dispose()

    # Use the native Expand-Archive to unzip the archive
    # Ammand $PSScriptRoot to the destination base path if needed
    Expand-Archive -Path $_.FullName -DestinationPath (Join-Path $PSScriptRoot $archiveName)
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...