Get-Item falha com erro de pipeline fechado
-
21-09-2019 - |
Pergunta
Se eu tiver uma função de exemplo ...
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
....
}
}
}
A mensagem de exceção é ... The WriteObject and WriteError methods cannot be called after the pipeline has been closed. Please contact Microsoft Support Services.
Basicamente, não posso usar Get-Item
Novamente dentro da função ou loop, para obter uma lista de arquivos em uma pasta diferente.
Alguma explicação e qual é a maneira correta de corrigi -la?
A propósito, estou usando o PS 1.0.
Solução
Isso é apenas uma pequena variação do que já foi sugerido, mas usa algumas técnicas que tornam o código um pouco mais simples ...
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 mais informações sobre o assunto com foreach
e valores nulos escalares, verifique isso Postagem do blog.
Outras dicas
Modifiquei um pouco o código acima para criar o arquivo de backup, mas sou capaz de usar o get-item dentro do loop com sucesso, sem exceções sendo lançadas. Meu código é:
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
...
}
}
}
Também estou usando o PowerShell 1.0.