Get-Item因关闭的管道错误而失败

Dav*_*.ca 6 powershell powershell-1.0

如果我有一个示例函数...

function foo() 
{
    # get a list of files matched pattern and timestamp
    $fs = Get-Item -Path "C:\Temp\*.txt" 
               | Where-Object {$_.lastwritetime -gt "11/01/2009"}
    if ( $fs -ne $null ) # $fs may be empty, check it first
    {
      foreach ($o in $fs)
      {
         # new bak file
         $fBack = "C:\Temp\test\" + $o.Name + ".bak"
         # Exception here Get-Item! See following msg
         # Exception thrown only Get-Item cannot find any files this time.
         # If there is any matched file there, it is OK
         $fs1 = Get-Item -Path $fBack
         ....
       }
     }
  }
Run Code Online (Sandbox Code Playgroud)

异常消息是...... The WriteObject and WriteError methods cannot be called after the pipeline has been closed. Please contact Microsoft Support Services.

基本上,我不能Get-Item在函数或循环中再次使用来获取不同文件夹中的文件列表.

任何解释以及解决问题的正确方法是什么?

顺便说一下,我正在使用PS 1.0.

Kei*_*ill 4

这只是已经建议的一个微小的变化,但它使用了一些使代码更简单的技术......

function foo() 
{    
    # Get a list of files matched pattern and timestamp    
    $fs = @(Get-Item C:\Temp\*.txt | Where {$_.lastwritetime -gt "11/01/2009"})
    foreach ($o in $fs) {
        # new bak file
        $fBack = "C:\Temp\test\$($o.Name).bak"
        if (!(Test-Path $fBack))
        {
            Copy-Item $fs.Fullname $fBack
        }

        $fs1 = Get-Item -Path $fBack
        ....
    }
}
Run Code Online (Sandbox Code Playgroud)

有关标量空值问题的更多信息,foreach请查看此博客文章