2

How do I create a blank file collection then add a file to it?

This is the pseudo-representaion.

$filelist = get-childitem "c:\somefolder\*"

$keepfiles  = new-object psobject #????
$purgefiles = new-object psobject #????

foreach ($file in $filelist)
{
  if (somecondition)
    $keepfiles | Add-Member $file #?????
  else
    $purgefiles | Add-Member $file #?????
}

#at this point I can use my 2 new collections

Thanks in advance.

Shankar R10N
  • 4,926
  • 1
  • 21
  • 24
Mouffette
  • 732
  • 1
  • 7
  • 19

2 Answers2

4
$filelist = get-childitem "c:\somefolder\*"

$keepfiles  = new-object System.Collections.ArrayList
$purgefiles = new-object System.Collections.ArrayList

foreach ($file in $filelist)
{
  if (somecondition)
    $keepfiles.Add($file)
  else
    $purgefiles.Add($file)
}

#at this point I can use my 2 new collections
EBGreen
  • 36,735
  • 12
  • 65
  • 85
3

@EBGreen's answer addresses your question directly, but you can accomplish what you want in more succinct and arguably in a more Powershell way using below:

You can do it like this:

$filelist = get-childitem "c:\somefolder\*" 
$keepfiles = $filelist | ?{somecondition}
$purgefiles =  $filelist | ?{-not (somecondition)}
#$purgefiles =  compare $filelist $keepfiles | %{$_.InputObject}

( also, if you club the statements and pipeline them, rather than collecting in variables, you will get better performance as the objects are "Streamed" through the pipeline whenever they are available. Also, probably you will calculate only keep or purge but not both most of the times so the clubbing makes sense)

manojlds
  • 290,304
  • 63
  • 469
  • 417
  • This is certainly less verbose. Wouldn't $purgefiles = $filelist | ?{!somecondition} Be even less verbose? – EBGreen Aug 09 '11 at 21:42
  • @EBGreen - Thanks, that is the most logical way, but wanted to show how to get $purgefiles from $filelist, $keepfiles. Updated. Do you think it is proper to actually instantiate a list etc for achieving this? I don't think the script is less verbose only, but also better if done this way. – manojlds Aug 09 '11 at 21:52
  • Yup, yours is probably better (that's why I +1'd it). Unless the the lists are massive though I don't think that there would be a huge performance difference though. To be honest if this were my problem to solve I would probably not use any list and just perform whatever actions were required inside the logic blocks if at all possible. – EBGreen Aug 09 '11 at 21:56
  • With the 2 lists I'm doing all the processing up front so that I can prompt the user if needed and also log and do some post processing notifications/logging. This is why I opted not to do it inside the logic blocks themselves. – Mouffette Aug 10 '11 at 03:27