Jump to content

7zip command line - batch archive testing script


Recommended Posts

Ok, here's what I'm trying to do. I've searched for the 7zip.udf and it's a complete no-go for what I wish to do, so I'm trying to make it work via the command line. Problem is, I'm so rusty that I can't exactly wrap my head around this one.

$pid = RunWait(@ComSpec & " /c " & 'C:\Users\My Name\Documents\7za.exe t badzipfile.zip', "")
Sleep(5000)
MsgBox(0,"",StdoutRead($pid) & @CRLF & StderrRead($pid))

I'm trying to read whether or not a .zip file passes or is corrupt with the 7zip command line utility so I can batch process about 2,000 files and cull out the non-operational archives.

When I do this manually, it reads as such on the CMD window.

C:\Users\My Name\Documents>7za t badzipfile.zip

7-Zip (A) 9.20 Copyright © 1999-2010 Igor Pavlov 2010-11-18

Processing archive: badzipfile.zip

Error: Can not open file as archive

Good files spit out something other than the "Error: Can not open file as archive" and is not important for me at this time.

So ... what am I doing wrong, besides everything, since I get a blank MsgBox()?

Lofting the cyberwinds on teknoleather wings, I am...The Blue Drache

Link to comment
Share on other sites

Please try using:

$pid = RunWait(@ComSpec & " /c " & 'C:UsersMy NameDocuments7za.exe t badzipfile.zip', "", @SW_HIDE, $STDOUT_CHILD)
.

Hope this was useful.

----------------------------------------

:bye: Hey there, was I helpful?

----------------------------------------

My Current OS: Win8 PRO (64-bit); Current AutoIt Version: v3.3.8.1

Link to comment
Share on other sites

Didn't think of using $stdout_child; however, the space is causing hiccups now.

'C:UsersMy is not recognized as an internal or external command,

operable program or batch file.

+>07:38:52 AutoIT3.exe ended.rc:0

>Exit code: 0 Time: 8.142

Told you I was rusty.

I've tried

$pid = RunWait(@ComSpec & " /c " & 'C:UsersMy NameDocuments7za.exe t badzipfile.zip', "", @SW_HIDE, $STDOUT_CHILD)
and
$pid = RunWait(@ComSpec & " /c " & '"C:UsersMy NameDocuments7za.exe t badzipfile.zip"', "", @SW_HIDE, $STDOUT_CHILD)

(Note the extra pair of quotes)

Edited by Blue_Drache

Lofting the cyberwinds on teknoleather wings, I am...The Blue Drache

Link to comment
Share on other sites

Try this, because you have to read the StdOut in a loop to get all of the text from it.

$pid = Run(@ComSpec & " /c " & 'C:UsersMy NameDocuments7za.exe t badzipfile.zip', "", "", 8)
While 1
    $line = StdoutRead($pid)
    If @error Then ExitLoop
    If $line <> "" Then
        ConsoleWrite('@@ Debug(' & @ScriptLineNumber & ') : $line = ' & $line & @CRLF & '>Error code: ' & @error & @CRLF) ;### Debug Console
    EndIf
WEnd

This will write the information to the SciTe console if you run it from within SciTe, but skips blank lines to make it easier to read it.

EDIT: Forgot to change the RunWait to Run, because using RunWait won't let you read the information, because by the time it gets to the While loop, the process is closed.

Edited by BrewManNH

If I posted any code, assume that code was written using the latest release version unless stated otherwise. Also, if it doesn't work on XP I can't help with that because I don't have access to XP, and I'm not going to.
Give a programmer the correct code and he can do his work for a day. Teach a programmer to debug and he can do his work for a lifetime - by Chirag Gude
How to ask questions the smart way!

I hereby grant any person the right to use any code I post, that I am the original author of, on the autoitscript.com forums, unless I've specifically stated otherwise in the code or the thread post. If you do use my code all I ask, as a courtesy, is to make note of where you got it from.

Back up and restore Windows user files _Array.au3 - Modified array functions that include support for 2D arrays.  -  ColorChooser - An add-on for SciTE that pops up a color dialog so you can select and paste a color code into a script.  -  Customizable Splashscreen GUI w/Progress Bar - Create a custom "splash screen" GUI with a progress bar and custom label.  -  _FileGetProperty - Retrieve the properties of a file  -  SciTE Toolbar - A toolbar demo for use with the SciTE editor  -  GUIRegisterMsg demo - Demo script to show how to use the Windows messages to interact with controls and your GUI.  -   Latin Square password generator

Link to comment
Share on other sites

I presumed 7-Zip would return an Exit code if there was an error, hence the use of RunWait.

UDF List:

 
_AdapterConnections()_AlwaysRun()_AppMon()_AppMonEx()_ArrayFilter/_ArrayReduce_BinaryBin()_CheckMsgBox()_CmdLineRaw()_ContextMenu()_ConvertLHWebColor()/_ConvertSHWebColor()_DesktopDimensions()_DisplayPassword()_DotNet_Load()/_DotNet_Unload()_Fibonacci()_FileCompare()_FileCompareContents()_FileNameByHandle()_FilePrefix/SRE()_FindInFile()_GetBackgroundColor()/_SetBackgroundColor()_GetConrolID()_GetCtrlClass()_GetDirectoryFormat()_GetDriveMediaType()_GetFilename()/_GetFilenameExt()_GetHardwareID()_GetIP()_GetIP_Country()_GetOSLanguage()_GetSavedSource()_GetStringSize()_GetSystemPaths()_GetURLImage()_GIFImage()_GoogleWeather()_GUICtrlCreateGroup()_GUICtrlListBox_CreateArray()_GUICtrlListView_CreateArray()_GUICtrlListView_SaveCSV()_GUICtrlListView_SaveHTML()_GUICtrlListView_SaveTxt()_GUICtrlListView_SaveXML()_GUICtrlMenu_Recent()_GUICtrlMenu_SetItemImage()_GUICtrlTreeView_CreateArray()_GUIDisable()_GUIImageList_SetIconFromHandle()_GUIRegisterMsg()_GUISetIcon()_Icon_Clear()/_Icon_Set()_IdleTime()_InetGet()_InetGetGUI()_InetGetProgress()_IPDetails()_IsFileOlder()_IsGUID()_IsHex()_IsPalindrome()_IsRegKey()_IsStringRegExp()_IsSystemDrive()_IsUPX()_IsValidType()_IsWebColor()_Language()_Log()_MicrosoftInternetConnectivity()_MSDNDataType()_PathFull/GetRelative/Split()_PathSplitEx()_PrintFromArray()_ProgressSetMarquee()_ReDim()_RockPaperScissors()/_RockPaperScissorsLizardSpock()_ScrollingCredits_SelfDelete()_SelfRename()_SelfUpdate()_SendTo()_ShellAll()_ShellFile()_ShellFolder()_SingletonHWID()_SingletonPID()_Startup()_StringCompact()_StringIsValid()_StringRegExpMetaCharacters()_StringReplaceWholeWord()_StringStripChars()_Temperature()_TrialPeriod()_UKToUSDate()/_USToUKDate()_WinAPI_Create_CTL_CODE()_WinAPI_CreateGUID()_WMIDateStringToDate()/_DateToWMIDateString()Au3 script parsingAutoIt SearchAutoIt3 PortableAutoIt3WrapperToPragmaAutoItWinGetTitle()/AutoItWinSetTitle()CodingDirToHTML5FileInstallrFileReadLastChars()GeoIP databaseGUI - Only Close ButtonGUI ExamplesGUICtrlDeleteImage()GUICtrlGetBkColor()GUICtrlGetStyle()GUIEventsGUIGetBkColor()Int_Parse() & Int_TryParse()IsISBN()LockFile()Mapping CtrlIDsOOP in AutoItParseHeadersToSciTE()PasswordValidPasteBinPosts Per DayPreExpandProtect GlobalsQueue()Resource UpdateResourcesExSciTE JumpSettings INISHELLHOOKShunting-YardSignature CreatorStack()Stopwatch()StringAddLF()/StringStripLF()StringEOLToCRLF()VSCROLLWM_COPYDATAMore Examples...

Updated: 22/04/2018

Link to comment
Share on other sites

I presumed 7-Zip would return an Exit code if there was an error, hence the use of RunWait.

I tried it using RunWait with a non-existant zip file and it returned:

@@ Debug(2) : $pid = 0

>Error code: 0

7za.exe doesn't seem to return an exitcode that tells you it had a problem.

If I posted any code, assume that code was written using the latest release version unless stated otherwise. Also, if it doesn't work on XP I can't help with that because I don't have access to XP, and I'm not going to.
Give a programmer the correct code and he can do his work for a day. Teach a programmer to debug and he can do his work for a lifetime - by Chirag Gude
How to ask questions the smart way!

I hereby grant any person the right to use any code I post, that I am the original author of, on the autoitscript.com forums, unless I've specifically stated otherwise in the code or the thread post. If you do use my code all I ask, as a courtesy, is to make note of where you got it from.

Back up and restore Windows user files _Array.au3 - Modified array functions that include support for 2D arrays.  -  ColorChooser - An add-on for SciTE that pops up a color dialog so you can select and paste a color code into a script.  -  Customizable Splashscreen GUI w/Progress Bar - Create a custom "splash screen" GUI with a progress bar and custom label.  -  _FileGetProperty - Retrieve the properties of a file  -  SciTE Toolbar - A toolbar demo for use with the SciTE editor  -  GUIRegisterMsg demo - Demo script to show how to use the Windows messages to interact with controls and your GUI.  -   Latin Square password generator

Link to comment
Share on other sites

Thanks for testing. I should have mentioned that I've had no luck in the past, so I've usually done the same approach as you did BrewManNH, with the addition of checking whether of not the file exists.

UDF List:

 
_AdapterConnections()_AlwaysRun()_AppMon()_AppMonEx()_ArrayFilter/_ArrayReduce_BinaryBin()_CheckMsgBox()_CmdLineRaw()_ContextMenu()_ConvertLHWebColor()/_ConvertSHWebColor()_DesktopDimensions()_DisplayPassword()_DotNet_Load()/_DotNet_Unload()_Fibonacci()_FileCompare()_FileCompareContents()_FileNameByHandle()_FilePrefix/SRE()_FindInFile()_GetBackgroundColor()/_SetBackgroundColor()_GetConrolID()_GetCtrlClass()_GetDirectoryFormat()_GetDriveMediaType()_GetFilename()/_GetFilenameExt()_GetHardwareID()_GetIP()_GetIP_Country()_GetOSLanguage()_GetSavedSource()_GetStringSize()_GetSystemPaths()_GetURLImage()_GIFImage()_GoogleWeather()_GUICtrlCreateGroup()_GUICtrlListBox_CreateArray()_GUICtrlListView_CreateArray()_GUICtrlListView_SaveCSV()_GUICtrlListView_SaveHTML()_GUICtrlListView_SaveTxt()_GUICtrlListView_SaveXML()_GUICtrlMenu_Recent()_GUICtrlMenu_SetItemImage()_GUICtrlTreeView_CreateArray()_GUIDisable()_GUIImageList_SetIconFromHandle()_GUIRegisterMsg()_GUISetIcon()_Icon_Clear()/_Icon_Set()_IdleTime()_InetGet()_InetGetGUI()_InetGetProgress()_IPDetails()_IsFileOlder()_IsGUID()_IsHex()_IsPalindrome()_IsRegKey()_IsStringRegExp()_IsSystemDrive()_IsUPX()_IsValidType()_IsWebColor()_Language()_Log()_MicrosoftInternetConnectivity()_MSDNDataType()_PathFull/GetRelative/Split()_PathSplitEx()_PrintFromArray()_ProgressSetMarquee()_ReDim()_RockPaperScissors()/_RockPaperScissorsLizardSpock()_ScrollingCredits_SelfDelete()_SelfRename()_SelfUpdate()_SendTo()_ShellAll()_ShellFile()_ShellFolder()_SingletonHWID()_SingletonPID()_Startup()_StringCompact()_StringIsValid()_StringRegExpMetaCharacters()_StringReplaceWholeWord()_StringStripChars()_Temperature()_TrialPeriod()_UKToUSDate()/_USToUKDate()_WinAPI_Create_CTL_CODE()_WinAPI_CreateGUID()_WMIDateStringToDate()/_DateToWMIDateString()Au3 script parsingAutoIt SearchAutoIt3 PortableAutoIt3WrapperToPragmaAutoItWinGetTitle()/AutoItWinSetTitle()CodingDirToHTML5FileInstallrFileReadLastChars()GeoIP databaseGUI - Only Close ButtonGUI ExamplesGUICtrlDeleteImage()GUICtrlGetBkColor()GUICtrlGetStyle()GUIEventsGUIGetBkColor()Int_Parse() & Int_TryParse()IsISBN()LockFile()Mapping CtrlIDsOOP in AutoItParseHeadersToSciTE()PasswordValidPasteBinPosts Per DayPreExpandProtect GlobalsQueue()Resource UpdateResourcesExSciTE JumpSettings INISHELLHOOKShunting-YardSignature CreatorStack()Stopwatch()StringAddLF()/StringStripLF()StringEOLToCRLF()VSCROLLWM_COPYDATAMore Examples...

Updated: 22/04/2018

Link to comment
Share on other sites

Here's a part of the code I used for a tool I built which allows users to password protect documents....

Func EncryptZIP()
;# First lock out the controls....
GUICtrlSetState($FolderInput, $Gui_Disable)
GUICtrlSetState($NameInput, $Gui_Disable)
GUICtrlSetState($PasswordInputField1, $Gui_Disable)
GUICtrlSetState($PasswordInputField2, $Gui_Disable)
;# The debug option displays the background processes to the user so that troubleshooting can be done in the
;# event something is not going according to plan.  Those controls are displayed below.  The $DebugSwitch is
;# controlled by a "CASE" above in the BasicSet() function.
If $DebugSwitch = False Then
  $CMD = (" /c")
  $Visibility = @SW_HIDE
ElseIf $DebugSwitch = True Then
  $CMD = (" /k")
  $Visibility = @SW_SHOW
EndIf
;# Below processes the actual password protection and features
$PID1 = RunWait(@ComSpec & $CMD & " " & $TempDir & "7z.exe" & " a " & '"' & $FileName & ".zip" & '"' & ' "' & $FolderInputValue & '"' & " -p" & $Password1, $TempDir, $Visibility)
ProcessWaitClose($PID1)
If $EmailSwitch = True Then
  $objOutlook = ObjCreate("Outlook.Application")
  $OutlookMailItem = $objOutlook.CreateItem($olMailItem)
  $OutlookMailItem.HTMLBody = ("Attached to this message is a password protected archive.")
  $OutlookMailItem.Attachments.Add($TempDir & "" & $FileName & ".zip")
  $OutlookMailItem.Display
Else
  $PID3 = RunWait(@ComSpec & $CMD & " move " & "/y " & '"' & $FileName & ".zip" & '" "' & @DesktopDir & '"', $TempDir, $Visibility)
  ProcessWaitClose($PID3)
EndIf
; Clean up to the GUI is done here once the encryption is complete
GUICtrlSetData($NameInput, "") ; Clears out the $NameInput field
GUICtrlSetData($PasswordInputField1, "") ; Clears out the PasswordInputField1 field
GUICtrlSetData($PasswordInputField2, "") ; Clears out the PasswordInputField2 field
GUICtrlSetData($FolderInput, "")
GUICtrlSetBkColor($StatusIndicator, 0xffffff)
GUICtrlSetColor($StatusIndicator, 0xffffff)
; Now all the controls are released for input so the user can run the program again with new data
GUICtrlSetState($FolderInput, $Gui_Enable)
GUICtrlSetState($NameInput, $Gui_Enable)
GUICtrlSetState($PasswordInputField1, $Gui_Enable)
GUICtrlSetState($PasswordInputField2, $Gui_Enable)

BasicSet()

The actual line of code you'll be interested in is:

$PID1 = RunWait(@ComSpec & $CMD & " " & $TempDir & "7z.exe" & " a " & '"' & $FileName & ".zip" & '"' & ' "' & $FolderInputValue & '"' & " -p" & $Password1, $TempDir, $Visibility)

Hopefully you might find it useful if you can decipher it :oops:

Edited by Colyn1337
Link to comment
Share on other sites

I'm not sure if this will help you but I use external 7zip command-line (I could never get the UDF to work properly) but here is a simple code snippet example below of how I am using it:

7-Zip returns the following exit codes:

0 = No Error

1 = Warning (Non fatal error(s)). For example, one or more files were locked by some other application, so they were not compressed.

2 = Fatal Error

7 = Command line error

8 = Not enough memory for operation

255 = User Aborted

; === this is a basic sample ===

$DLdir = @ScriptDir&"DL"
$ZipName = "SourceZipFile.zip"
;
; the command-line passed to 7zip assembled below (this is an Extract with params)
$xString = " x " & $DLdir & $ZipName & " -O" & $DLdir & " -aoa"
;
$retResult = ShellExecuteWait("7za.exe", $xString, "", "") ;, @SW_MINIMIZE)
;
If @error > 0 Then
    ConsoleWrite("7ZIP Extract Error occurred: " & $retResult)
    ; above prints the error code to console, this could be acted upon with IF conditions and sent to statusbar or similar action
Else
    $UnPackMsg = "COMPLETED" & @CR
    ConsoleWrite("Unpack: " & $UnPackMsg)
EndIf
Edited by WhiteStar

~ WhiteStar Magic

Always tuned to http://www.superbluesradio.com/  Tune in at http://87.117.217.41:8036/

Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
 Share

×
×
  • Create New...