2

Я работаю над сценарием, который:

  1. Принимает загруженную папку и удаляет все ее папки
  2. Сбрасывает все свои файлы в другую папку
  3. Конвертирует все файлы в один PDF-файл, используя ImageMagick
  4. Перемещает этот .pdf в другую папку и удаляет все остальные файлы.

Я запустил скрипт, прежде чем пытаться заставить его проверить, было ли завершено копирование папки перед запуском. Но теперь я что-то напутал и запускаю скрипт (просто отлично), но на рабочем столе, где хранится файл. Не с указанными каталогами.

Все, что я пытаюсь сделать, это убедиться, что сценарий ждет, пока папка не будет скопирована, перед запуском.

Мой текущий код:

$freshStart = 0
$input = 'C:\IT\Convert Drop'
While ($freshStart -eq 0)
{
    $status = Get-Item $input | Foreach { $_.LastWriteTime }
    If ($status -eq $statusOld)
    {
        $input = 'C:\IT\Convert Drop'
        $output = 'C:\IT\Processing'
        $pdf = 'C:\IT\Processing\*.pdf'
        $done = 'C:\IT\Converted PDF'
        $deleteME = 'C:\IT\Convert Drop\*'
        $deleteMEToo = 'C:\IT\Processing\*'

        $folder = get-childitem -Path $input -Directory -Name

        $fileName = $folder + ".pdf"

        Get-ChildItem -Path $input -Recurse -File | Move-Item -Destination $output
        & CD $output
        & magick "*.{png,jpeg,jpg,tif}" $fileName
        Get-ChildItem -Path $pdf -File | Move-Item -Destination $done
        Remove-Item $deleteMEToo -Recurse -Force
        Remove-Item $deleteME -Recurse -Force
    }
    Else
    {
        sleep 10
        $statusOld = $status
    }

    $freshStart = 1
}


### SET FOLDER TO WATCH + FILES TO WATCH + SUBFOLDERS YES/NO
    $watcher = New-Object System.IO.FileSystemWatcher
    $watcher.Path = "$input"
    $watcher.Filter = "*.*"
    $watcher.IncludeSubdirectories = $true
    $watcher.EnableRaisingEvents = $true


$status = Register-ObjectEvent $watcher "Created"
### DEFINE ACTIONS AFTER AN EVENT IS DETECTED
    $action =
{
    $status = Get-Item $input | Foreach { $_.LastWriteTime }
    If ($status -eq $statusOld)
    {
        $input = 'C:\IT\Convert Drop'
        $output = 'C:\IT\Processing'
        $pdf = 'C:\IT\Processing\*.pdf'
        $done = 'C:\IT\Converted PDF'
        $deleteME = 'C:\IT\Convert Drop\*'
        $deleteMEToo = 'C:\IT\Processing\*'

        $folder = get-childitem -Path $input -Directory -Name

        $fileName = $folder + ".pdf"

        Get-ChildItem -Path $input -Recurse -File | Move-Item -Destination $output
        #& CD $output
        #Set-Location -Path '$output'
        & magick "*.{png,jpeg,jpg,tif}" $fileName
        Get-ChildItem -Path $pdf -File | Move-Item -Destination $done
        Remove-Item $deleteMEToo -Recurse -Force
        Remove-Item $deleteME -Recurse -Force
    }
    Else{       
        sleep 10
        $statusOld = $status
    }
}

### DECIDE WHICH EVENTS SHOULD BE WATCHED 
    Register-ObjectEvent $watcher "Created" -Action $action
    while ($true) {sleep 5}

РЕДАКТИРОВАННЫЙ КОД (не работает):

$freshStart = 0
$inLoc = 'C:\IT\Convert Drop'
$outLoc = 'C:\IT\Processing'
$pdf = 'C:\IT\Processing\*.pdf'
$done = 'C:\IT\Converted PDF'
$deleteME = 'C:\IT\Convert Drop\*'
$deleteMEToo = 'C:\IT\Processing\*'

While ($freshStart -eq 0)
{
    $status = Get-Item $inLoc | Foreach { $_.LastWriteTime }
    $statusOld = 0
    If ($status -eq $statusOld)
    {

        $folder = get-childitem -Path $inLoc -Directory -Name

        $fileName = $folder + ".pdf"

        Get-ChildItem -Path $inLoc -Recurse -File | Move-Item -Destination $outLoc
        & CD $outLoc
        & magick "*.{png,jpeg,jpg,tif}" $fileName
        Get-ChildItem -Path $pdf -File | Move-Item -Destination $done
        Remove-Item $deleteMEToo -Recurse -Force
        Remove-Item $deleteME -Recurse -Force
    }
    Else
    {
        $statusOld = $status
        $status = Get-Item $inLoc | Foreach { $_.LastWriteTime }
        sleep 10
    }

    $freshStart = 1
}


### SET FOLDER TO WATCH + FILES TO WATCH + SUBFOLDERS YES/NO
    $watcher = New-Object System.IO.FileSystemWatcher
    $watcher.Path = "$inLoc"
    $watcher.Filter = "*.*"
    $watcher.IncludeSubdirectories = $true
    $watcher.EnableRaisingEvents = $true


### DEFINE ACTIONS AFTER AN EVENT IS DETECTED
    $action =
{
    $status = Get-Item $inLoc | Foreach { $_.LastWriteTime }
    $statusOld = 0
    If ($status -eq $statusOld)
    {

        $folder = get-childitem -Path $inLoc -Directory -Name

        $fileName = $folder + ".pdf"

        Get-ChildItem -Path $inLoc -Recurse -File | Move-Item -Destination $outLoc
        #& CD $outLoc
        #Set-Location -Path '$outLoc'
        & magick "*.{png,jpeg,jpg,tif}" $fileName
        Get-ChildItem -Path $pdf -File | Move-Item -Destination $done
        Remove-Item $deleteMEToo -Recurse -Force
        Remove-Item $deleteME -Recurse -Force
    }
    Else{
        $statusOld = $status
        $status = Get-Item $inLoc | Foreach { $_.LastWriteTime }
        sleep 10
    }
}

### DECIDE WHICH EVENTS SHOULD BE WATCHED 
    Register-ObjectEvent $watcher "Created" -Action $action
    while ($true) {sleep 5}

ОБНОВЛЕННЫЙ ПИСЬМО

#File Locations
$rootPath = 'C:\IT\'
$inLoc = 'Convert Drop'
$prossLoc = 'Processing'
$outLoc = 'Converted PDF'

#File types to include in PDF creation.
$fileTypes = '*.{png,jpeg,jpg,tiff,tif}'

#Function Variables
$inPath  = Join-Path -Path "$rootPath" -ChildPath "$inLoc"
$outPath = Join-Path -Path "$rootPath" -ChildPath "$outLoc"
$runPath = Join-Path -Path "$rootPath" -ChildPath "$prossLoc"
$remove1 = Join-Path -Path "$rootPath" -ChildPath "$($inLoc + "\*")"
$remove2 = Join-Path -Path "$rootPath" -ChildPath "$($outLoc + "\*")"

#Folder Watching Variables
$watcher = New-Object System.IO.FileSystemWatcher
$watcher.Path = "$inPath"
$watcher.Filter = "*.*"
$watcher.IncludeSubdirectories = $false
$watcher.EnableRaisingEvents = $true

#Lone Counter
$freshStart = $null
$statusOld  = $null
$pathLoc    = (Get-Item -Path ".\").FullName

#Pulls the last write time of a folder to compare later.
$grabStatus = {$status = Get-Item $pathLoc | Foreach { $_.LastWriteTime } }

#Get PDF name from Folder
$grabFileName = {
    $folder = get-childitem -Path $inPath -Directory -Name
    $fileName = $folder + ".pdf"
}

#Move all nested files to single folder.
$moveFiles = {
    Get-ChildItem -Path $inPath -Recurse -File | Move-Item -Destination $runPath
}

#Convert Nested files into single PDF
$makePDF = {
    & CD $runPath
    & magick "$fileTypes" $fileName
}

#Move final PDF
$moveCmplt = {
    Get-ChildItem -Path $pdf -File | Move-Item -Destination $outPath
}

#Delete Old files
$deleteOld = {
    Remove-Item $remove1 -Recurse -Force
    Remove-Item $remove2 -Recurse -Force
}

#Set compare status to current status then fetches new status.
$stats = {
    $statusOld = $status
    $grabStatus
    sleep 10
}

#Exicute main conversion together.
$action = {
    $grabStatus
    If ($status -eq $statusOld){
        $grabFileName
        $moveFiles
        & CD $runPath
        $grabStatus
        If ($status -eq $statusOld) {
            $makePDF
        }
        Else{
            $stats
        }
        $deleteOld
    }
    Else
    {
        $stats
    }
}

#First Time Start, Then Loop run.
While ($freshStart -eq $null) {
    If ((Get-ChildItem $inPath | Measure-Object).Count -eq 0) {
    }
    Else {
        $action
    }
    $freshStart = "FreshStartDone!"
}

#Scan folder every 5 seconds for new content then run convert on change.
Register-ObjectEvent $watcher "Created" -Action $action
while ($true) {sleep 5}

1 ответ1

1

Решен скрипт

#File Locations
$rootPath = 'C:\IT'
$inLoc = 'Convert Drop'
$prossLoc = 'Processing'
$outLoc = 'Converted PDF'

#File types to include in PDF creation.
$fileTypes = '*.{png,jpeg,jpg,tiff,tif}'

#Function Variables
$inPath = Join-Path -Path "$rootPath" -ChildPath "$inLoc"
$outPath = Join-Path -Path "$rootPath" -ChildPath "$outLoc"
$runPath = Join-Path -Path "$rootPath" -ChildPath "$prossLoc"
$remove1 = Join-Path -Path "$rootPath" -ChildPath "$($inLoc + "\*")"
$remove2 = Join-Path -Path "$rootPath" -ChildPath "$($prossLoc + "\*")"
$global:thefile = Join-Path -Path "$rootPath" -ChildPath "$("START.txt")"

#Lone Vars
$freshStart = $null
$Global:statusOld = $null
$pathLoc = (Get-Item -Path ".\").FullName
$global:allClear = 'No'
$pathTaken = $null
$global:areYouThere = $null

#Pulls the last write time of a folder to compare later.
function grabStatus
{
    $global:status = Get-Item $runPath | Foreach { $_.LastWriteTime }
}

#Get PDF name from Folder
function grabFileName
{
    $folder = get-childitem -Path $inPath -Directory -Name
    $global:fileName = $folder + ".pdf"
}

#Check if Empty
function checkEmpty
{
    $directoryInfo = Get-ChildItem $inPath | Measure-Object
    $directoryInfo.count #Returns the count of all of the files in the directory
    If ($directoryInfo.count -eq 0)
    {
        $global:allClear = 'Yes'
    }
    else
    {
        sleep 5
    }
}

#Move all nested files to single folder.
function moveFiles
{
    Get-ChildItem -Path $inPath -Recurse -File | Move-Item -Destination $runPath
}

#Convert Nested files into single PDF
function makePDF
{
    & CD $runPath
    & magick $fileTypes $global:fileName
}

#Move final PDF
function moveCmplt
{
    Get-ChildItem -Path "$runPath\*.pdf" -File | Move-Item -Destination $outPath
}

#Delete Old files
function deleteOld
{
    Remove-Item $remove1 -Recurse -Force
    Remove-Item $remove2 -Recurse -Force
}

#Delete Empty folders
function folderClean
{
    do
    {
        $dirs = gci $inPath -directory -recurse | Where { (gci $_.fullName -Force).count -eq 0 } | select -expandproperty FullName
        $dirs | Foreach-Object { Remove-Item $_ }
    }
    while ($dirs.count -gt 0)
}
#Set compare status to current status then fetches new status.
function stats
{
    $Global:statusOld = $Global:status
    grabStatus
    sleep 10
}

function testPDFcreate
{
    do { sleep 5 }
    until (test-path -path ($outpath + '\$global:fileName') -eq true)
    $global:areYouThere = $true
}


#Exicute main conversion together.
function global:runIt
{
    grabFileName
    moveFiles
    folderClean
    Do { checkEmpty }
    Until ($global:allClear -eq 'Yes')
    makePDF
    grabStatus
    $global:allClear = 'No'
    Do { stats }
    Until ($Global:status -eq $Global:statusOld)
    moveCmplt
    $Global:statusOld = 'No'
    If ($global:areYouThere = $true)
    {
        deleteOld
        $global:areYouThere = $false
    }

}

while ($true)
{
    If ((Get-ChildItem $inPath | Measure-Object).Count -eq 0)
    {
        If (Test-Path -Path $global:thefile)
        {
            Remove-Item -Path $global:thefile
        }
        else{}
    }
    Else
    {
        If (Test-Path -Path $global:thefile)
        {
            [int]$fileSize = "{0:N2}" -f ((Get-ChildItem $inPath -Recurse | Measure-Object -Property Length -Sum -ErrorAction Stop).Sum / 1MB)
            If ($fileSize -gt 30)
            {
                Set-Content -Path $($outPath + "\Please Ask IT to Convert.txt") -Value "Please Ask IT to Convert"
                deleteOld
                Remove-Item -Path $global:thefile
            }
            else
            {
                global:runIt
                Remove-Item -Path $global:thefile
            }

        }
        else { sleep 10 }
    }
}

Всё ещё ищете ответ? Посмотрите другие вопросы с метками .