gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 15:16:20 29 4
gpt4 key购买 nike

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

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。

最佳答案

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

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 .

关于powershell - Get-Item 因管道关闭错误而失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1766287/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com