Networknet archive Blog

PowerShell: Delete a remote file using a list of computers

Originally published Last updated 12 comments

This PowerShell script deletes a remote file from computers listed in a text file. It defines a function for the session and pipes the computer names from the file to that function.

Create C:\Scripts\Active_Computers.txt and add the computer names.

PowerShell13 lines
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
function delete-remotefile {
    PROCESS {
                $file = "\\$_\c$\install.exe"
                if (test-path $file)
                {
                echo "$_ install.exe exists"
                Remove-Item $file -force
                echo "$_ install.exe file deleted"
                }
            }
}

Get-Content  C:\Scripts\Active_Computers.txt | delete-remotefile

That's it.

PowerShell-Remove-Item-Text-File

12 comments

Comments from the original WordPress site, kept read-only.

  1. Tom

    Thanks Ram. How would you go about deleting specific file types. For example: I want to delete all .pst files from a list of computers.

  2. Amit

    Hii
    I would like to know if the aboe script would work for computers which are password protected because I have around 400 machines in the domain and I wanted to delete some log file and txt file from all the computers
    Thanks
    Amit

  3. carlos porras

    Id doesn't work for me.

    I have a folder named: C:\scripts\master2
    it has inside
    clean2.ps1
    computers.txt

    I run the script on the same computer and i get:
    PS C:\scripts\master2> .\clean2.ps1
    Get-Content : Cannot find path 'C:\scripts\master2\computers.txt' because it does not exist.
    At C:\scripts\master2\clean2.ps1:13 char:12
    + Get-Content <<<

    any advice?

  4. ATX

    This worked great.  I medified it to use wildcard for logs and it saves so much time.

     

    Thanks!

  5. ATX

    This worked great.  I modified it to use wildcard for logs and it saves so much time.

    I will call if from my stop script tp dp the cleanup once systems are stopped.

    Thanks!

  6. Laiq

    Thank you sir!

     

    Could i take it one step further and ask how can we delete temp files for all users on any given machine that are active for last 60 days ?

    Please and Thank you!