سؤال

إذا كان لدي وظيفة مثال ...

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 والقيم الفارغة العددية تحقق من هذا مشاركة مدونة.

نصائح أخرى

لقد قمت بتعديل الكود أعلاه قليلاً لإنشاء ملف النسخ الاحتياطي ، لكنني قادر على استخدام Get-Intem داخل الحلقة بنجاح ، مع عدم وجود استثناءات. الكود الخاص بي هو:

 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.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top