简体   繁体   English

使用 PowerShell,如何将文件添加到新创建的文件集合中?

[英]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.

相关问题 如何使用 XmlWriter() 在 Powershell 中正确创建此 xml 文件? - How can I properly create this xml file in Powershell using XmlWriter()? 检测新创建的文件,只检测编辑的文件 - Detect newly created file, just edited file 如何更新fileSystemWatch以在C#中查找新创建的文件? - How to update fileSystemWatch in order to find newly created file in C#? 如何查看新创建的文件并等待它们被解锁? - How can I watch for newly created files and wait for them to be unlocked? 我如何找出谁使用.NET在Windows中创建了文件? - How can I find out who created a file in Windows using .NET? 如何使用PowerShell检查文件是否超过特定时间? - How can I check if a file is older than a certain time with PowerShell? 如何将配置文件引入 Powershell 脚本? - How can I introduce a config file to Powershell scripts? 如何确定我创建的文件是否在当前用户的登录会话期间创建的? - How can I find out if a file I created was created during the current user's logon session? 如何将其他解决方案的项目添加到新创建的解决方案中? - How to add the projects of other solution to a newly created solution? 如何在要复制的文件中添加日期戳? - How can I add a date stamp to a file i am copying?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM