Home > Net >  Powershell - extract specific items from zip then send a message (loop with message box)
Powershell - extract specific items from zip then send a message (loop with message box)

Time:08-11

I'm trying to achieve the following with this powershell script.

  1. Copy any .zip file from folder dropfilehere to folder IN.
  2. For each .zip file in folder "IN" open the zip file, find only the .csv file.
  3. When .csv file is found, extract it to $dst under name DB.csv (overwrite old file).
  4. Empty contents of folders "dropfilehere" and "IN"
  5. Finally, when all the above is done, create a popup box with a message to the user using wscriptshell - This is the issue. When the message is sent, the user gets 10 popup boxes or an endless loop of them.

In the background i see cmd.exe and conhost.exe processes appearing as each popup box gets created.

I use a batch file to call the powershell script.

Powershell.exe -ExecutionPolicy Bypass -File C:\testingn\Other\script.ps1
exit

The script is:

  $dst = "C:\Testing\DB"
Copy-item -Path "C:\Users\user\dropfilehere\*.zip" -destination "C:\Testing\Other\In" -Force
Foreach ($zipfile in (Get-ChildItem "C:\Testing\Other\In\*.zip" -Recurse)) {
Add-Type -Assembly System.IO.Compression.FileSystem
$zipFile = [IO.Compression.ZipFile]::OpenRead($zipfile)
$zipFile.Entries | where {$_.Name -like '*.csv'} | foreach {$FileName = $_.Name
[System.IO.Compression.ZipFileExtensions]::ExtractToFile($_, "$dst\DB.csv", $true)}
$zipFile.Dispose()
Remove-Item "C:\Testing\Other\In\*" -Recurse -Force
Remove-Item "C:\Users\user\dropfilehere\*" -Recurse -Force
$org="Name of Org"
$timeout = 60 # in seconds
$ws = New-Object -ComObject "Wscript.Shell"
$intButton = $ws.Popup("A new update message here`n
Another message here.",$timeout,$org, 0)
}
exit

CodePudding user response:

There is code inside your foreach loop that should be placed after it, as shown below (properly indenting your code would have made that more obvious):

Add-Type -Assembly System.IO.Compression.FileSystem

$dst = "C:\Testing\DB"
Copy-item -Path "C:\Users\user\dropfilehere\*.zip" -destination "C:\Testing\Other\In" -Force

# Process all files.
foreach ($zipfile in (Get-ChildItem "C:\Testing\Other\In\*.zip" -Recurse)) {
  $zipFile = [IO.Compression.ZipFile]::OpenRead($zipfile)
  $zipFile.Entries | 
    Where-Object { $_.Name -like '*.csv' } |
    ForEach-Object { 
      [System.IO.Compression.ZipFileExtensions]::ExtractToFile($_, "$dst\DB.csv", $true) 
    }
  $zipFile.Dispose()
}

# Remove the folders containing the original *.zip files.
Remove-Item "C:\Testing\Other\In\*" -Recurse -Force
Remove-Item "C:\Users\user\dropfilehere\*" -Recurse -Force

# Show a message box.
$org = "Name of Org"
$timeout = 60 # in seconds
$ws = New-Object -ComObject "Wscript.Shell"
$intButton = $ws.Popup("A new update message here`nAnother message here.", $timeout, $org, 0)
  • Related