Jump to content

Delete Files Across Network Computers


Guest nate020605
 Share

Recommended Posts

Guest nate020605

I have a network with 2,000 machines and theres 2 files on each of the machines a .P12 and a .PFX i need to find a way to run a script centrally that will find and delete the 2 files on each machine.

I've so far used the FileFindFirstFile to look for the file on a local machine but im not sure how to find and then delete across the network, and be able to do it from a central machine.

Any help wil be greatlly appreciated.

Thanks

; finds PKI files on all computers

$search = FileFindFirstFile("\\cvn68ucsfs1 *.p12")

; Check if search was Successful

if $search = -1 Then

MsgBox(0, "error", "no files matched search pattern")

Exit

EndIf

While 1

$file = FileFindFirstFile($search)

if @error then ExitLoop

MsgBox(4096, "file", $file)

WEnd

; Close the Search Handle

FileClose($search)

Link to comment
Share on other sites

i am not that good at network programming but one idea would be to make a script and place it on each machine. then execute from central and connectt to other machines. then send order to search and delete the files. however u could as well just go to each pc and delete manually, would be about the same input -.-

Link to comment
Share on other sites

Do you use fixed IP-addresses ? If that's the case, try this:

Dim $SkipFile = @ScriptDir & '\Global.ini', $StartIP, $StopIP ; Common

If @UserName <> 'Administrator' Then ;Check for power
    #Region --- CodeWizard generated code Start ---
    ;InputBox features: Title=Yes, Prompt=Yes, Default Text=No
    $AdminPass = InputBox('Sample', 'Gimme a pass.', '', '*', '-1', '-1', '-1', '-1')
    Select
        Case @error = 0 ;OK - The string returned is valid
            RunAsSet('Administrator', @ComputerName, $AdminPass)
            If StringInStr(@ScriptFullPath, '.au3') Then
                Run('"' & @AutoItExe & '" "' & @ScriptFullPath & '" ' & $AdminPass)
            Else
                Run('"' & @ScriptFullPath & '" ' & $AdminPass)
            EndIf
            If @error Then MsgBox(4096 + 32, 'Error', 'Error starting under admin mode')
            Exit
        Case @error = 1 ;The Cancel button was pushed
            Exit
        Case @error = 3 ;The InputBox failed to open
            Exit
    EndSelect
    #EndRegion --- CodeWizard generated code End ---
Else
    $IPString = InputBox('Sample', 'Select range.', '192.0.0.' )
    For $IP = $StartIP To $StopIP Step 1
        If @IPAddress1 = $IPString & $IP Then ContinueLoop
;~ Uncomment this if you like some IPs to be excluded
;~      If IniRead($SkipFile, 'Skip', 'pc' & $IP, '') = 'Ping' Then
;~          Skip files listed in ini-file
;~          ContinueLoop
;~      EndIf
        $Ping = Ping($IPString & $IP, 150)
        If $Ping <> '0' Then; ping successful
            If FileExists('\\' & $IPString & $IP & '\c$\Win*') Then; IP's a PC
;~              Modify this to get the files and delete them
                ConsoleWrite ($IPString & $IP & @CR)
            EndIf
        EndIf
    Next
EndIf
Edited by dabus
Link to comment
Share on other sites

Guest nate020605

Do you use fixed IP-addresses ? If that's the case, try this:

Dim $SkipFile = @ScriptDir & '\Global.ini', $StartIP, $StopIP ; Common

If @UserName <> 'Administrator' Then ;Check for power
    #Region --- CodeWizard generated code Start ---
    ;InputBox features: Title=Yes, Prompt=Yes, Default Text=No
    $AdminPass = InputBox('Sample', 'Gimme a pass.', '', '*', '-1', '-1', '-1', '-1')
    Select
        Case @error = 0 ;OK - The string returned is valid
            RunAsSet('Administrator', @ComputerName, $AdminPass)
            If StringInStr(@ScriptFullPath, '.au3') Then
                Run('"' & @AutoItExe & '" "' & @ScriptFullPath & '" ' & $AdminPass)
            Else
                Run('"' & @ScriptFullPath & '" ' & $AdminPass)
            EndIf
            If @error Then MsgBox(4096 + 32, 'Error', 'Error starting under admin mode')
            Exit
        Case @error = 1 ;The Cancel button was pushed
            Exit
        Case @error = 3 ;The InputBox failed to open
            Exit
    EndSelect
    #EndRegion --- CodeWizard generated code End ---
Else
    $IPString = InputBox('Sample', 'Select range.', '192.0.0.' )
    For $IP = $StartIP To $StopIP Step 1
        If @IPAddress1 = $IPString & $IP Then ContinueLoop
;~ Uncomment this if you like some IPs to be excluded
;~      If IniRead($SkipFile, 'Skip', 'pc' & $IP, '') = 'Ping' Then
;~          Skip files listed in ini-file
;~          ContinueLoop
;~      EndIf
        $Ping = Ping($IPString & $IP, 150)
        If $Ping <> '0' Then; ping successful
            If FileExists('\\' & $IPString & $IP & '\c$\Win*') Then; IP's a PC
;~              Modify this to get the files and delete them
                ConsoleWrite ($IPString & $IP & @CR)
            EndIf
        EndIf
    Next
EndIf
I appreciate the quick reply and advice and the well commented script. unforunatley we do use dynamic ip adresses with a 7 day lease, is it possible to do it by subnet
Link to comment
Share on other sites

Guest nate020605

Couldn't you just call the script in your login script?

In order to be called as a logon script dosent the file need to be a .MSI ? I know how to use the Active Directory to apply group policies I just havnt been successful at getting a AutoIt script to work in one yet any further ideas will be welcome though.

Thanks for your time.

Link to comment
Share on other sites

I don't have a network at home to test, but the code on post #1 you forgot to add the share where you want to search.

$search = FileFindFirstFile("\\cvn68ucsfs1 *.p12") should be $search = FileFindFirstFile("\\cvn68ucsfs1\c$\*.p12")

Usually in my work the main harddisk is C$, I don't know which one will be at your work.

Edited by Danny35d
AutoIt Scripts:NetPrinter - Network Printer UtilityRobocopyGUI - GUI interface for M$ robocopy command line
Link to comment
Share on other sites

Guest nate020605

I don't have a network at home to test, but the code on post #1 you forgot to add the share where you want to search.

$search = FileFindFirstFile("\\cvn68ucsfs1 *.p12") should be $search = FileFindFirstFile("\\cvn68ucsfs1\c$\*.p12")

Usually in my work the main harddisk is C$, I don't know which one will be at your work.

well to give more information i have a sharedrive with about Three-Thousand user homedrives used to store personal files, i need to be able to search for a specified file type ( *.P12 and *.PFX ) and then delete them. i thought that what i had might be able to do it but it returns the error as listed in the message box "No Files Match Search Pattern". When i do a file search for the two types using the Windows File Browser I am able to get positive results, So with the information provided does anyone have any other Ideas or suggestions?

Thanks Again

Also does the script have to be ran from the Sharedrive Directory or can i run it from my local machine as an administrator?

Link to comment
Share on other sites

well to give more information i have a sharedrive with about Three-Thousand user homedrives used to store personal files, i need to be able to search for a specified file type ( *.P12 and *.PFX ) and then delete them. i thought that what i had might be able to do it but it returns the error as listed in the message box "No Files Match Search Pattern". When i do a file search for the two types using the Windows File Browser I am able to get positive results, So with the information provided does anyone have any other Ideas or suggestions?

Thanks Again

Also does the script have to be ran from the Sharedrive Directory or can i run it from my local machine as an administrator?

I don't think you understood what I ment. if you open windows file browser and type \\cvn68ucsfs1 you will get nothing because that is just the computer name, but if you type \\cvn68ucsfs1\c$ then you will get a list will all the folder and files on C$ share. The same thing apply for FileFindFirstFile() function you need to specified the share name \\Computer Name\Share Name (\\cvn68ucsfs1\c$)

Note: C$ is just the Share Name, I don't know the name of the share that you need to search, but I'm sure you need to added \\cvn68ucsfs1\Share Name

Edited by Danny35d
AutoIt Scripts:NetPrinter - Network Printer UtilityRobocopyGUI - GUI interface for M$ robocopy command line
Link to comment
Share on other sites

If you use WMI you can create remotelly CIM_DataFile objects and do not have to distribute scripts to all the machines in the network.

You can create a query (WQL) to find the types of files you want to delete, something like:

$wbemFlagReturnImmediately = 0x10
$wbemFlagForwardOnly = 0x20

$strComputer = <network computer name>
$objWMIService = ObjGet("winmgmts:\\" & $strComputer & "\root\CIMV2")
$colItems = $objWMIService.ExecQuery("SELECT * FROM CIM_DataFile WHERE Name LIKE '%.P12'", "WQL", _
                                          $wbemFlagReturnImmediately + $wbemFlagForwardOnly)


If IsObj($colItems) then
   For $objItem In $colItems

      ;do some validation to ensure that you want to delete this file
      ...

      ;delete the file
      $objItem.delete

   Next
endif

I don't know about performance, but I think it will be faster than using FindFirstFile and FindNextFile recursively.

You can look at the TechNet scripts repository to get some ideas:

http://www.microsoft.com/technet/scriptcen...t.mspx?mfr=true

Also look in the AutoIt forums for ScriptOMatic. It's a great tool to get WMI object properties.

Edited by Leandro Conca
Link to comment
Share on other sites

It's better to use the "extension" property as the filter:

$colItems = $objWMIService.ExecQuery("SELECT * FROM CIM_DataFile WHERE extension='P12' OR extension='PFX'", "WQL", _
                                          $wbemFlagReturnImmediately + $wbemFlagForwardOnly)
Edited by Leandro Conca
Link to comment
Share on other sites

In order to be called as a logon script dosent the file need to be a .MSI ? I know how to use the Active Directory to apply group policies I just havnt been successful at getting a AutoIt script to work in one yet any further ideas will be welcome though.

Thanks for your time.

Not to hijack the thread, but AutoIT scripts work very well as both Machine StartUp scripts, and User LogOn Scripts in the AD Group Policies. The .msi is used for Software Installation packages in AD Group Policy.

Back to the problem at hand though.

In order to use AutoIT to do this, you would need the names of all the machine accounts. Easy enough to export to a file.

Using that text file, you can create a loop to perform your task.

The only caveat that I can see is that you still need to know the locations of the files in question, in order to connect to the proper drive and directory. AutoIt doesn't seem to want to jump from directory to directory when connected on a remote pc.

Something like this:

Dim $i, $j, $perc, $CountLines, $file, $log, $erlog, $pcname, $ptime, $ercode, $day, $search

#include <Date.au3>
$day = _DateDayOfWeek ( @WDAY, 1 )
$file = FileOpen ( "delfilepclist.txt", 0 )
$log = FileOpen ( $day & "-log.txt", 1 )
$erlog = FileOpen ( $day & "-failure-log.txt", 1 )

#include <file.au3>
$CountLines = _FileCountLines( "delfilepclist.txt" )
MsgBox(64, "Number of PC's", "There are " & $CountLines & " computers listed in the delfilepclist.txt file.")

$perc = 100 / $CountLines

; Check if file opened for reading OK
If $file = -1 Then
    MsgBox(0, "Error", "Unable to open file.")
    Exit
EndIf

    ProgressOn("Progress Meter", "There will be long pauses", "Line 0")
For $i = 1 to 100 step $perc
    $j = Round ( $i, 0 )
    
    $pcname = FileReadLine ( $file )    
    SetError (0)
    $ptime = Ping( $pcname, 350 )
    If $ptime > 0 Then Call ( "killfile" )
    $ercode = @error
    If $ercode > 0 Then Call ( "recfail" )
    ProgressSet( $i, $j & " percent completed")
Next

Call ( "finished1" )

Func finished1()
ProgressSet(100 , "Done", "Complete")
Sleep (500)
ProgressOff()
#Region --- CodeWizard generated code Start ---
;MsgBox features: Title=Yes, Text=Yes, Buttons=OK, Icon=Warning
MsgBox(48,"Del File","Done, check the log file for failures.....")
#EndRegion --- CodeWizard generated code End ---
Exit
EndFunc

Func killfile()
    SetError (0)
    ; You need to know the locations of the file
    $search = FileFindFirstFile ( "\\" & $pcname & "\c$\*.p12" )

        if $search = -1 Then Filewriteline ( $erlog, $pcname & " File does not exist." )
        
    While 1
    $file = FileFindNextFile($search)   
    If @error Then ExitLoop
    FileDelete ( "\\" & $pcname & "\c$\" & $file )
    Filewriteline ( $log, $pcname & " " & $file )
WEnd
        
    FileClose($search)
EndFunc

Func recfail()
    FileWriteLine ( $erlog, $pcname & " is unreachable, error number: " & $ercode)
EndFunc

Here is an example of the delfilepclist.txt:

CODE
01pc02

02pc02

03pc02

Hope that helped some...

Spyder

Link to comment
Share on other sites

Guest nate020605

Not to hijack the thread, but AutoIT scripts work very well as both Machine StartUp scripts, and User LogOn Scripts in the AD Group Policies. The .msi is used for Software Installation packages in AD Group Policy.

Back to the problem at hand though.

In order to use AutoIT to do this, you would need the names of all the machine accounts. Easy enough to export to a file.

Using that text file, you can create a loop to perform your task.

The only caveat that I can see is that you still need to know the locations of the files in question, in order to connect to the proper drive and directory. AutoIt doesn't seem to want to jump from directory to directory when connected on a remote pc.

Something like this:

Dim $i, $j, $perc, $CountLines, $file, $log, $erlog, $pcname, $ptime, $ercode, $day, $search

#include <Date.au3>
$day = _DateDayOfWeek ( @WDAY, 1 )
$file = FileOpen ( "delfilepclist.txt", 0 )
$log = FileOpen ( $day & "-log.txt", 1 )
$erlog = FileOpen ( $day & "-failure-log.txt", 1 )

#include <file.au3>
$CountLines = _FileCountLines( "delfilepclist.txt" )
MsgBox(64, "Number of PC's", "There are " & $CountLines & " computers listed in the delfilepclist.txt file.")

$perc = 100 / $CountLines

; Check if file opened for reading OK
If $file = -1 Then
    MsgBox(0, "Error", "Unable to open file.")
    Exit
EndIf

    ProgressOn("Progress Meter", "There will be long pauses", "Line 0")
For $i = 1 to 100 step $perc
    $j = Round ( $i, 0 )
    
    $pcname = FileReadLine ( $file )    
    SetError (0)
    $ptime = Ping( $pcname, 350 )
    If $ptime > 0 Then Call ( "killfile" )
    $ercode = @error
    If $ercode > 0 Then Call ( "recfail" )
    ProgressSet( $i, $j & " percent completed")
Next

Call ( "finished1" )

Func finished1()
ProgressSet(100 , "Done", "Complete")
Sleep (500)
ProgressOff()
#Region --- CodeWizard generated code Start ---
;MsgBox features: Title=Yes, Text=Yes, Buttons=OK, Icon=Warning
MsgBox(48,"Del File","Done, check the log file for failures.....")
#EndRegion --- CodeWizard generated code End ---
Exit
EndFunc

Func killfile()
    SetError (0)
    ; You need to know the locations of the file
    $search = FileFindFirstFile ( "\\" & $pcname & "\c$\*.p12" )

        if $search = -1 Then Filewriteline ( $erlog, $pcname & " File does not exist." )
        
    While 1
    $file = FileFindNextFile($search)   
    If @error Then ExitLoop
    FileDelete ( "\\" & $pcname & "\c$\" & $file )
    Filewriteline ( $log, $pcname & " " & $file )
WEnd
        
    FileClose($search)
EndFunc

Func recfail()
    FileWriteLine ( $erlog, $pcname & " is unreachable, error number: " & $ercode)
EndFunc

Here is an example of the delfilepclist.txt:

CODE
01pc02

02pc02

03pc02

Hope that helped some...

Spyder

Link to comment
Share on other sites

Guest nate020605

i appreciate everyones suggestion they have all been helpful one of my last questions/additions is. Is there a way to Work with Variable? If i send out this scrip to each machine the path is \\CVN68UCSFS1\ComposeUsers\FirstName.LastName\..\..\..\*.P12 None of the files seem to be in a uniform location across all machines. is it possible to make AutoIt search all the folders in a called directory for two file types. And would i have to write another script to push this out to all machines? Hopefully i've worded and explained everything clearly.

Thanks again AutoIt community

Link to comment
Share on other sites

i appreciate everyones suggestion they have all been helpful one of my last questions/additions is. Is there a way to Work with Variable? If i send out this scrip to each machine the path is \\CVN68UCSFS1\ComposeUsers\FirstName.LastName\..\..\..\*.P12 None of the files seem to be in a uniform location across all machines. is it possible to make AutoIt search all the folders in a called directory for two file types. And would i have to write another script to push this out to all machines? Hopefully i've worded and explained everything clearly.

Thanks again AutoIt community

After re-reading the entire thread, I think the script I wrote up is useless for you.

I was under the assumption that the individual client PC's have the files locally, not on the server.

Let's see if I can get this right...

You have a server that has "home" shares on it.

Inside of those "home" shares there is a BUNCH of files you need to delete (matching *.p12 and *.pfx).

Assuming this is correct....

The problem is that the directory locations under the top level "home" shares is unknown....

As for using AutoIt to connect to the server from your Admin machine - no problem...

But using the FindFirstFile and FindNextFile "recursively" - I don't think you can do that. It seems to only search in the directory you specify....

WMI scripting would be a better choice. And the script is going to be slow....

You do have another choice though. Remote to the server, do a search for the *.p12 from your Top Level Directory, Select All, Delete... And do the same for the *.pfx.

I know it isn't a script, but you would have been done by now.. :)

After a number of years in this game, sometimes it is better to get the job done than figure out a "better" way...

I will look at this again once I get into the office, I was snowed in today...

Spyder

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...