Pregunta

Si tengo una función de ejemplo ...

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
         ....
       }
     }
  }

El mensaje de excepción es ... The WriteObject and WriteError methods cannot be called after the pipeline has been closed. Please contact Microsoft Support Services.

Básicamente, no puedo usar Get-Item de nuevo dentro de la función o bucle para obtener una lista de los archivos en una carpeta diferente.

Cualquier explicación y cuál es la forma correcta de solucionarlo?

Por cierto estoy usando PS 1.0.

¿Fue útil?

Solución

Esto es sólo una variación menor de lo que ya se ha sugerido, pero utiliza algunas técnicas que hacen que el código un poco más simple ...

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
        ....
    }
}

Para obtener más información sobre el tema con foreach y escalares valores nulos echa un vistazo a este entrada de blog .

Otros consejos

He modificado ligeramente el código anterior para crear el archivo de copia de seguridad, pero soy capaz de utilizar el Get-Item dentro del bucle con éxito, sin excepciones que son lanzadas. Mi código es:

 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
             ...
        }
     }
 }

También estoy usando PowerShell 1.0.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top