开发者

Using PowerShell, how can I add a file to a newly created file collection?

开发者 https://www.devze.com 2023-03-26 21:50 出处:网络
How do I create a blank file collection then add a file to it? This is the pseudo-representaion. $filelis开发者_如何学JAVAt = get-childitem \"c:\\somefolder\\*\"

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

This is the pseudo-representaion.

$filelis开发者_如何学JAVAt = 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.


$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'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)

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号