Server Fault is a question and answer site for system and network administrators. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I'm writing my first powershell script:

foreach ($UserDir in Get-ChildItem -Path $NetworkLocation) 
    # if the item is a directory, then process it.
    if ($UserDir.Attributes -eq "Directory")
        $Dir = $UserDir.Name
        Remove-Item $Dir +"*" -recurse

Will $Dir end with a trailing "\" so I can just add a * to delete all files in that directory?

share|improve this question
up vote 1 down vote accepted

No it won't supply a trailing slash.

PS C:\> $dirlist=get-childitem c:\
PS C:\> $dirlist[4].name
PS C:\> 

Nor will it supply full path:

PS C:\> $dirlist=get-childitem C:\windows
PS C:\> $dirlist[3].name 
PS C:\> $dirlist[3].fullname

That is provided through "fullname", which also doesn't provide a trailing slash. However, Remove-Item doesn't need slashes!

In summary, to remove all files in a directory and all files in it's sub-directories, use:

Remove-Item $Dir -recurse


$Dir = $UserDir.Fullname
share|improve this answer
To remove all files do you not do: Remove-Item $Dir +"*" -recurse? I thought you needed the \ to use the *? – SteB Nov 1 '12 at 16:50
The recurse parameter tells it to do the removal at this location "$Dir" and all child-locations. Its dos equivalent is rmdir /s. If all you want to do is remove all files in a location, but leave any sub-directories intact, you'd use wildcards without the -recurse parameter. – sysadmin1138 Nov 1 '12 at 16:53
I'm looking to delete everything in $Dir, files and sub-folders (and everything in those) – SteB Nov 1 '12 at 16:55
@SteB In that case, Remove-Item $Dir -recurse should be sufficient, so long as $Dir=$UserDir.Fullname – sysadmin1138 Nov 1 '12 at 16:56

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.