質問

関数の例があれば...

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 関数またはループ内で再度実行して、別のフォルダー内のファイルのリストを取得します。

何らかの説明とそれを修正する正しい方法は何ですか?

ちなみにPS1.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 スカラー null 値については、これをチェックしてください ブログ投稿.

他のヒント

私は、バックアップファイルを作成するために、わずかに上記のコードを変更し、私は例外がスローされないされた状態で、成功したループ内のGet-項目を使用することができています。私のコードは次のとおりです。

 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