tags:

views:

62

answers:

2

Is it possible to define an array of filenames (all files in different folders) and then in a loop delete them all, or do something else?

Actually I need to create a few symbolic links using mklink to one file, putting those links in a different folders, replacing the old links if there was any.

+3  A: 

Deleting an array of filenames is simple:

Remove-Item foo.txt,c:\temp\bar.txt,baz\baz.txt

Or via a variable:

$files = 'foo.txt','c:\temp\bar.txt','baz\baz.txt'
Remove-Item $files

And then based on all files in different folders:

$folders = 'C:\temp','C:\users\joe\foo'
Get-ChildItem $folders -r | Where {!$_.PSIsContainer} | Remove-Item -WhatIf

Remove the -WhatIf to do the actual removal.

If you want to delete a file with a specific name you could use the -Filter parameter on Get-ChildItem. This would be the best performing approach:

$folders = 'C:\temp','C:\users\joe\foo'
Get-ChildItem $folders -r -filter foo.bak | Remove-Item -WhatIf

If the name requires more sophisticated matching then you can use a regex in a Where scriptblock e.g.:

$folders = 'C:\temp','C:\users\joe\foo'
Get-ChildItem $folders -r | Where {$_.Name -match 'f\d+.bak$'} | 
                            Remove-Item -WhatIf
Keith Hill
what's PSIsContainer ?
Ike
Can you tell me please how to remove files with given filename in all folders defined in a variable?
Ike
$PSIsContainer is a property added by PowerShell that indicates if the "ChildItem" is a container (directory) or not (file). Note that this concept is independent of the actual provider (filesystem, certificate, wsman, etc).
Keith Hill
+1  A: 

something like this should work: can't test right now, sorry

$filenames = @('filename1.txt', 'filename2.txt', 'filename3.txt')

foreach($file in $filenames)
{
   #GCI recursive to find all instances of this filename
   $filesToDelete = Get-ChildItem -R | where {$_.Name -eq $file}

   foreach($f in $filesToDelete)
   {
      #delete the file that matches, etc. here
      # just using Write-Host to echo out the name for now
      Write-Host $f.Name
   }

}

As with most powershell, you can really compress this, but wanted to extend for explanation.

You could extend this to match your needs. For example if you needed all files that contain the word "delete", you could do gci | where {$_.Name -like "$file"}

Taylor
Your .net part produces unwanted output (the `Add`) method that should be discarded. Just try to run `$filelist = New-Object System.Collections.ArrayList; $filelist.add("filename1.txt")`.
stej
Didn't have time to test it yesterday. Removed for now.
Taylor