Foreach remove-item help

This topic contains 2 replies, has 2 voices, and was last updated by  Daniel Brooks 2 years, 7 months ago.

  • Author
    Posts
  • #22046

    Daniel Brooks
    Participant

    I'm trying to delete everything on the desktop from a txt file containing computer names(40 pcs – separate domain). Maybe my syntax is off. I tried using invoke-command inside the foreach loop and wasn't successful either.

    $computers = Get-Content C:\mypc.txt
    foreach ($comp in $computers)
    {
    Remove-item -Path "\\$comp\c$\Users\desktop\*"
    }

  • #22047

    Dave Wyatt
    Moderator

    Your code is basically okay, assuming that you have appropriate rights on all of the computers you're connecting to (access to the c$ share, permission to remove files from users' desktops, etc. Basically, Administrator), with one exception. There is no C:\Users\Desktop folder. Instead, you want to remove the contents of the Desktop folder from each user profile found in C:\Users (assuming that user profile directories are their default values and haven't been redirected.) Try this:

    Remove-Item -Path "\\$comp\c$\Users\*\desktop\*" -WhatIf
    

    I added the -WhatIf switch because this is a destructive command, and you might want to make sure you like what it's doing first. You might also want to add a -Recurse switch to the command, if there are folders on these desktops that you want to clear out.

  • #22048

    Daniel Brooks
    Participant

    Thank you! It looks like I was only one * off. I wish I would have known about that -WhatIf command earlier, that is extremely helpful.

You must be logged in to reply to this topic.