Foreach remove-item help

Welcome Forums General PowerShell Q&A Foreach remove-item help

This topic contains 2 replies, has 2 voices, and was last updated by

3 years, 12 months ago.

  • Author
  • #22046

    Points: 0
    Rank: Member

    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

    Points: 0
    Rank: Member

    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

    Points: 0
    Rank: Member

    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.

The topic ‘Foreach remove-item help’ is closed to new replies.