Author Posts

August 21, 2015 at 6:35 am

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:

$computernames=@("1";"2";"3";"4";"5";"6";"7")
$User=@("1";"2")

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

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

$Users[$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.

Greetings

August 21, 2015 at 6:50 am

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

$computernames=@("1","2","3","4","5","6","7")
$Users=@("1","2")
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.

August 21, 2015 at 7:17 am

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 😉

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