Delete Automation

This topic contains 2 replies, has 2 voices, and was last updated by Profile photo of Benjamin Winkelmann Benjamin Winkelmann 1 year, 2 months ago.

  • Author
  • #28859
    Profile photo of Benjamin Winkelmann
    Benjamin Winkelmann

    Hi Folks,

    I am currently working on a script that should delete all of the files on the Desktop of a Users.
    In my Company we have about 24 PC's with 1 generic user and now we want to wake em, delete all temp and desktop files and shut them down again.
    The wake on lan function already works but it seems I can't delete files. Here is my Code Example without the computer Names of course:


    foreach ($Computername in $Computernames) {
    "$Computername=" +$Computername.Length

    for ($count2=0;$count2 -ne 2;$count2++){


    remove-item -path \users\$User[$count2]\desktop\*


    Every Computername has only one generic user. How can I make this work best?

    Thank you for your answers.


  • #28862
    Profile photo of Don Jones
    Don Jones

    Wow. OK, first, we need to look at your loop logic.

    ForEach ($computer in $computernames) {
      ForEach ($user in $users) {
         # use $computer and $user
         Remove-Item "\\$computer\C\Users\$user\desktop\*" -Recurse -EA SilentlyContinue

    Arrays are comma-separated lists, not semicolon. And, a ForEach loop is a much better way to enumerate a collection than a For loop.

    Are you saying that each computer has either User 1 or User 2, but not both? Then you'd simply try deleting both. Add "-ErrorAction SilentlyContinue" to Remove-Item if you want to suppress the errors that result when you try to delete a path that doesn't exist. That's what I did above.

    I'll note that your example doesn't actually connect to the remote computers by name – I'm assuming you knew that. In my example, I'm assuming you're connecting to a shared folder named C, but that might not be the case in your environment, obviously.

  • #28865
    Profile photo of Benjamin Winkelmann
    Benjamin Winkelmann

    You guessed right. On every Computer there is only one of the Users in $Users, so on PC 1 is User 1 and so on.

    Over all your one looks really good. I will try that.

    Thanks Don Jones 😉

    Unfortunately it didn't work. But a co-worker found a way using an if loop.
    Thanks for the help again

You must be logged in to reply to this topic.