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

时间:2009-11-19 20:28:46

标签: powershell powershell-v1.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
         ....
       }
     }
  }

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

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

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

顺便说一句,我正在使用PS 1.0。

2 个答案:

答案 0 :(得分: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
        ....
    }
}

有关foreach和标量空值问题的详情,请查看此blog post

答案 1 :(得分:1)

我稍微修改了上面的代码来创建备份文件,但是我能够成功地在循环中使用Get-Item,不会抛出任何异常。我的代码是:

 function foo() 
 {
     # get a list of files matched pattern and timestamp
     $files = Get-Item -Path "C:\Temp\*.*" | Where-Object {$_.lastwritetime -gt "11/01/2009"}
     foreach ($file in $files)
     {
        $fileBackup = [string]::Format("{0}{1}{2}", "C:\Temp\Test\", $file.Name , ".bak") 
        Copy-Item $file.FullName -destination $fileBackup
        # Test that backup file exists 
        if (!(Test-Path $fileBackup))
        {
             Write-Host "$fileBackup does not exist!"
        }
        else
        {
             $fs1 = Get-Item -Path $fileBackup
             ...
        }
     }
 }

我也在使用PowerShell 1.0。