如何创建一个空白文件集合,然后向其中添加一个文件?
这是伪表示。
$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
$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的回答直接解决了你的问题,但你可以用下面的方法更简洁、更有争议地实现你想要的:
你可以这样做:
$filelist = get-childitem "c:somefolder*"
$keepfiles = $filelist | ?{somecondition}
$purgefiles = $filelist | ?{-not (somecondition)}
#$purgefiles = compare $filelist $keepfiles | %{$_.InputObject}
(同样,如果您组合语句并将它们管道化,而不是收集变量,那么您将获得更好的性能,因为对象在可用时通过管道"流式传输"。此外,您可能只计算keep或purge,但大多数情况下不会同时计算这两个值,因此使用棒化是有意义的)