Jump to content

Forfiles command not working with autoit


Recommended Posts

So Im trying to use FORFILES dos command with autoit. Here is the command

Forfiles /P C:\users /M *.txt /C "cmd /c ReplaceText @path yes no /I"

Basically this will look at every .txt file in the C:\users directory and replace the word YES with the word NO using replacetext.vbs

I can type this into a command window and it works great. However it does not work with autoit.

Here is a simple command.

Run(@ComSpec & " /c " & "FORFILES /P C:\Users")

That command should show you a list of every file in the C:\users directory, But I cannot get it to work. If I type into a command window, it works.

Any help would be apreciated

Link to comment
Share on other sites

  • Moderators

wisem2540,

Your code works perfectly for me when I change the /c to /k so that the command prompt remains open. So perhaps it is just closing too quickly for you to notice when you run it. ;)

But why are you using such a mix of Autoit, cmd and VBScript? Why not do the whole thing directly in AutoIt? :huh:

M23

Public_Domain.png.2d871819fcb9957cf44f4514551a2935.png Any of my own code posted anywhere on the forum is available for use by others without any restriction of any kind

Open spoiler to see my UDFs:

Spoiler

ArrayMultiColSort ---- Sort arrays on multiple columns
ChooseFileFolder ---- Single and multiple selections from specified path treeview listing
Date_Time_Convert -- Easily convert date/time formats, including the language used
ExtMsgBox --------- A highly customisable replacement for MsgBox
GUIExtender -------- Extend and retract multiple sections within a GUI
GUIFrame ---------- Subdivide GUIs into many adjustable frames
GUIListViewEx ------- Insert, delete, move, drag, sort, edit and colour ListView items
GUITreeViewEx ------ Check/clear parent and child checkboxes in a TreeView
Marquee ----------- Scrolling tickertape GUIs
NoFocusLines ------- Remove the dotted focus lines from buttons, sliders, radios and checkboxes
Notify ------------- Small notifications on the edge of the display
Scrollbars ----------Automatically sized scrollbars with a single command
StringSize ---------- Automatically size controls to fit text
Toast -------------- Small GUIs which pop out of the notification area

 

Link to comment
Share on other sites

Look at _ForFiles in my signature.

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

My bad. I will update the code soon and post to the Examples section.

Badly formatted and will update soon.

#include <Array.au3>
#include <Constants.au3>

Example()

Func Example()
    Local $hTimer = TimerInit()
    ; Search in @UserProfileDir for au3/ini files recursively for a date less than 2 days. The command is to "echo the path".
    Local $aArray = _ForFiles(@UserProfileDir, '*.au3;*.ini', '-2', 'echo @path', True) ; del /q @path
    MsgBox($MB_SYSTEMMODAL, '', TimerDiff($hTimer) / 1000 & @CRLF)
    _ArrayDisplay($aArray)
EndFunc   ;==>Example

Func _ForFiles($sFilePath, $sMask = '*.*', $sDate = '', $sCommand = 'echo @path', $fRecursive = True) ; http://technet.microsoft.com/en-us/library/cc753551(WS.10).aspx
    If Not ($sDate == '') Then
        $sDate = '/d ' & $sDate
    EndIf
    Local $sRecursive = ''
    If $fRecursive Or $fRecursive = Default Then
        $sRecursive = '/S'
    EndIf

    $sFilePath = StringRegExpReplace($sFilePath, '[\\/]+\z', '') & '\'
    Local $aMask = StringSplit($sMask, ';'), $iPID = 0, $sOutput = ''
    For $i = 1 To $aMask[0]
        $iPID = Run(@ComSpec & ' /c ' & 'forfiles /P ' & $sFilePath & ' ' & $sRecursive & ' /M ' & $aMask[$i] & ' ' & $sDate & ' /C ' & ' "cmd /c ' & $sCommand & '"', $sFilePath, @SW_HIDE, $STDERR_CHILD + $STDOUT_CHILD)
        While 1
            $sOutput &= StdoutRead($iPID)
            If @error Then
                ExitLoop
            EndIf
        WEnd
    Next
    $sOutput = StringReplace($sOutput, '"', '')
    $sOutput = StringStripCR($sOutput)
    $sOutput = StringStripWS($sOutput, $STR_STRIPLEADING + $STR_STRIPTRAILING)
    Local $aReturn = StringSplit($sOutput, @LF)
    If @error Then
        Local $aError[1] = [0]
        Return SetError(1, 0, $aError)
    EndIf
    Return $aReturn
EndFunc   ;==>_ForFiles
Edited by guinness

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

  • Moderators

wisem2540,

Use my RecFileListToArray to get a list of all the files on the path. Then loop through the returned array using a For...Next loop and use FileRead to get the content of each file in turn. Then use StringReplace to replace "YES" with "NO" - if the string "YES" is not unique and could be part of another word it gets more complex, but we can deal with that if we have to. Rewrite the amended file with FileWrite. Simples! :)

Now go and have a look at those functions in teh Help file (the link to my UDF is in my sig) and see if you can work out how to code what I have just described. Come back if you get stuck and we will help you to get it working. ;)

M23

Public_Domain.png.2d871819fcb9957cf44f4514551a2935.png Any of my own code posted anywhere on the forum is available for use by others without any restriction of any kind

Open spoiler to see my UDFs:

Spoiler

ArrayMultiColSort ---- Sort arrays on multiple columns
ChooseFileFolder ---- Single and multiple selections from specified path treeview listing
Date_Time_Convert -- Easily convert date/time formats, including the language used
ExtMsgBox --------- A highly customisable replacement for MsgBox
GUIExtender -------- Extend and retract multiple sections within a GUI
GUIFrame ---------- Subdivide GUIs into many adjustable frames
GUIListViewEx ------- Insert, delete, move, drag, sort, edit and colour ListView items
GUITreeViewEx ------ Check/clear parent and child checkboxes in a TreeView
Marquee ----------- Scrolling tickertape GUIs
NoFocusLines ------- Remove the dotted focus lines from buttons, sliders, radios and checkboxes
Notify ------------- Small notifications on the edge of the display
Scrollbars ----------Automatically sized scrollbars with a single command
StringSize ---------- Automatically size controls to fit text
Toast -------------- Small GUIs which pop out of the notification area

 

Link to comment
Share on other sites

I got stuck on the For, Next thing.... so I didnt make it very far. I dont know why I find arrays so hard to understand. Actually, yes I do. The reason why I find it so difficult is because all of the experienced coders use variables for EVERYTHING. So every Script is packed full of var after var, and it makes it hard to follow. I know in the end, Vars make the script easier to follow, but not when you are a beginner.

In the end, I was able to get mine working. I am still interested in learning how to accomplish with autoit,

Here is my script

$Old = InputBox( "Please Specify Old String ", "Please Specify String to Replace: " )

$New = InputBox( "Please Specify New String", "Please Specify New String: " )

$Path = InputBox( "Please Specify Path", "Path to files: ")

Run(@ComSpec & " /k "&"Forfiles /P " &$Path& " /M *.txt /C"& ' "cmd /c ReplaceText @path ' & $Old & ' ' & $New & ' /I"')

Link to comment
Share on other sites

  • Moderators

wisem2540,

Does this help to clarify things a bit? ;)

; Declare an array with 5 elements
; In AutoIt arrays start at [0] so we have elements [0], [1], [2], [3], [4]
Global $aArray[5] = ["Item 0", "Item 1", "Item 2", "Item 3", "Item 4"]

; We start a For...Next loop
; We have to tell AutoIt what values to use in the loop
; Here we tell it to start at 0 and go up to 4
For $i = 0 To 4
    ; Just to show what happens
    MsgBox(0, "Element "  & $i, $aArray[$i])
; When we get to the Next statement AutoIt adds 1 to the index value
; and looks to see if the value is now higher than we set at the beginning
; If it is not, we run through the loop again
Next
; But if it is we exit the loop
; Now let us see if $i is too large:
MsgBox(0, "Out of the loop", $i)

Please ask if you have questions - that is why I come here. :)

M23

Public_Domain.png.2d871819fcb9957cf44f4514551a2935.png Any of my own code posted anywhere on the forum is available for use by others without any restriction of any kind

Open spoiler to see my UDFs:

Spoiler

ArrayMultiColSort ---- Sort arrays on multiple columns
ChooseFileFolder ---- Single and multiple selections from specified path treeview listing
Date_Time_Convert -- Easily convert date/time formats, including the language used
ExtMsgBox --------- A highly customisable replacement for MsgBox
GUIExtender -------- Extend and retract multiple sections within a GUI
GUIFrame ---------- Subdivide GUIs into many adjustable frames
GUIListViewEx ------- Insert, delete, move, drag, sort, edit and colour ListView items
GUITreeViewEx ------ Check/clear parent and child checkboxes in a TreeView
Marquee ----------- Scrolling tickertape GUIs
NoFocusLines ------- Remove the dotted focus lines from buttons, sliders, radios and checkboxes
Notify ------------- Small notifications on the edge of the display
Scrollbars ----------Automatically sized scrollbars with a single command
StringSize ---------- Automatically size controls to fit text
Toast -------------- Small GUIs which pop out of the notification area

 

Link to comment
Share on other sites

wisem2540,

I apologize for such simple questions

The questions only become simple once you know the answer. So obvious, but so often forgotten.

To you point:

The size of an array can be determined by the "ubounds" statement. Many functions also return the # of elements in offset 0 of the array, see helpfile for what the function does.

Stringreplace can be done as follows (a simple example)

#include <array.au3>
local $array[5] = ['1','2','3','4','5']
for $i = 0 to ubound($array) - 1
 if $array[$i] = '3' then $array[$i] = stringreplace($array[$i],'3','x')
next
_arraydisplay($array)

kylomas

Forum Rules         Procedure for posting code

"I like pigs.  Dogs look up to us.  Cats look down on us.  Pigs treat us as equals."

- Sir Winston Churchill

Link to comment
Share on other sites

  • Moderators

wisem2540,

Some arrays (like the one returned by my UDF) have a count in the [0] element so you can use:

For $i = 1 To $aArray[0]

Otherwise you can get the size of the array like this:

For $i = 0 To UBound($aArray) - 1

Can you see why we need the "- 1"? :huh:

How are you trying to use StringReplace on the array? Please post your code. :)

M23

Public_Domain.png.2d871819fcb9957cf44f4514551a2935.png Any of my own code posted anywhere on the forum is available for use by others without any restriction of any kind

Open spoiler to see my UDFs:

Spoiler

ArrayMultiColSort ---- Sort arrays on multiple columns
ChooseFileFolder ---- Single and multiple selections from specified path treeview listing
Date_Time_Convert -- Easily convert date/time formats, including the language used
ExtMsgBox --------- A highly customisable replacement for MsgBox
GUIExtender -------- Extend and retract multiple sections within a GUI
GUIFrame ---------- Subdivide GUIs into many adjustable frames
GUIListViewEx ------- Insert, delete, move, drag, sort, edit and colour ListView items
GUITreeViewEx ------ Check/clear parent and child checkboxes in a TreeView
Marquee ----------- Scrolling tickertape GUIs
NoFocusLines ------- Remove the dotted focus lines from buttons, sliders, radios and checkboxes
Notify ------------- Small notifications on the edge of the display
Scrollbars ----------Automatically sized scrollbars with a single command
StringSize ---------- Automatically size controls to fit text
Toast -------------- Small GUIs which pop out of the notification area

 

Link to comment
Share on other sites

Sorry to be a little of topic now, but I updated my code in post #6. Though my advice, listen to Melba23.

Edited by guinness

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

wisem2540,

Look at my example, especially the for loop and the stringreplace. Look these up in the help file.

Please use code tags when you post code.

And yes, the -1 is because all array elements start at offset "0".

kylomas

edit: I don't know how to make the editor show code tags as characters.

Edited by kylomas

Forum Rules         Procedure for posting code

"I like pigs.  Dogs look up to us.  Cats look down on us.  Pigs treat us as equals."

- Sir Winston Churchill

Link to comment
Share on other sites

  • Moderators

kylomas,

I don't know how to make the editor show code tags as characters

Put some other BB codes inside the tag - like this without the spaces: [ a u t o [ b ] [ / b ] i t ]. ;)

wisem2540,

-1 would apply because integer 0 counts as a number, correct?

Correct. In the code I posted above, UBound woudl return 5 as that is the number of elements - but the elements are actually 0 - 4. Personally I would have caller the function something other than UBound but that is what we have got. :(

For $i = 0-100 Stringreplace("yes","","No")

You need to put in some effort yourself if you want us to help you. Have you even looked at the Help file pages for For and StringReplace? I think not as that snippet looks nothing like the syntax shown in the examples there - nor in kylomas' code just above. Go and look at both and see if you can come up with something a little more correct. ;)

And no, we are not being harsh - we are just trying to get you to learn how to use the Help file so that you can do it yourself next time. See you soon, I hope. :)

M23

Public_Domain.png.2d871819fcb9957cf44f4514551a2935.png Any of my own code posted anywhere on the forum is available for use by others without any restriction of any kind

Open spoiler to see my UDFs:

Spoiler

ArrayMultiColSort ---- Sort arrays on multiple columns
ChooseFileFolder ---- Single and multiple selections from specified path treeview listing
Date_Time_Convert -- Easily convert date/time formats, including the language used
ExtMsgBox --------- A highly customisable replacement for MsgBox
GUIExtender -------- Extend and retract multiple sections within a GUI
GUIFrame ---------- Subdivide GUIs into many adjustable frames
GUIListViewEx ------- Insert, delete, move, drag, sort, edit and colour ListView items
GUITreeViewEx ------ Check/clear parent and child checkboxes in a TreeView
Marquee ----------- Scrolling tickertape GUIs
NoFocusLines ------- Remove the dotted focus lines from buttons, sliders, radios and checkboxes
Notify ------------- Small notifications on the edge of the display
Scrollbars ----------Automatically sized scrollbars with a single command
StringSize ---------- Automatically size controls to fit text
Toast -------------- Small GUIs which pop out of the notification area

 

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

  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...