[英]Using PowerShell, how can I add a file to a newly created file collection?
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.提前致谢。
$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: @EBGreen 的回答直接解决了您的问题,但是您可以使用以下方式以更简洁且可以说更 Powershell 的方式完成您想要的:
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) (此外,如果您将语句组合起来并将它们流水线化,而不是在变量中收集,那么您将获得更好的性能,因为只要对象可用,它们就会通过管道“流式传输”。此外,您可能只会计算保留或清除而不是大多数时候都是这样,所以泡吧是有道理的)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.