6

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

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。

4

2 回答 2

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空值和标量空值问题的更多信息,请查看此博客文章

于 2009-11-19T22:59:24.963 回答
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。

于 2009-11-19T20:49:08.253 回答