Take the 2-minute tour ×
Server Fault is a question and answer site for system and network administrators. It's 100% free, no registration required.

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

1 Answer 1

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
PerfLogs
PS C:\> 

Nor will it supply full path:

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

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

where

$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

 
discard

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.