2014-07-21 111 views
1

我有點困惑,爲什麼路徑的管道到我的函數完美工作,並返回2次$true當路徑存在,我們可以寫入它。但是,當我不管它並在函數後添加路徑時,它只返回一次$true,就好像沒有檢查第二個路徑一樣。PowerShell管道參數

這工作得很好,並返回2倍$true

"L:\Scheduled Task\Auto_Clean", "L:\Scheduled Task" | Can-WriteToFolder 

這隻回報$true一個結果:

Can-WriteToFolder "L:\Scheduled Task\Auto_Clean", "L:\Scheduled Task" 

我覺得有什麼毛病我的參數,但我似乎無法弄明白。感謝您的幫助。

功能:

Function Can-WriteToFolder { 
     [CmdletBinding(SupportsShouldProcess=$True)] 
    Param(
     [Parameter(ValueFromPipeline=$true,mandatory=$true)] 
     [ValidateNotNullOrEmpty()] 
     [ValidateScript({Test-Path $_ -PathType Container})] 
     [String[]] 
     $Path 
    ) 

    Process { 
      try { 
       Write-Verbose "Write a new file to the folder '$Path'" 
       $TestPath = Join-Path $Path Get-Random 
       New-Item -Path $TestPath -ItemType File -ErrorAction Stop > $null 
       Write-Verbose "Return TRUE for '^$Path'" 
       return $true 
      } 
      catch { 
        Write-Verbose "Catch return FALSE for '$Path'" 
        return $false 
      } 
      finally { 
        Remove-Item $TestPath -ErrorAction SilentlyContinue 
      } 
    } 
} 
+0

閱讀這裏:http://stackoverflow.com/a/887406/520612 –

+0

我在你提出的例子中直接複製了'process'的整個代碼塊,它仍然返回相同的結果。即使在像foreach($ _ in $ Path)這樣的'foreach'循環中。 – DarkLite1

+0

請閱讀我的答案;) –

回答

0

試試這個:

[CmdletBinding(SupportsShouldProcess=$True)] 
    Param(
     [Parameter(ValueFromPipeline=$true,mandatory=$true)] 
     [ValidateNotNullOrEmpty()] 
     #[ValidateScript({Test-Path $_ -PathType Container})] 
     [String[]] 
     $Path 
    ) 

    Process { 
      foreach ($_ in $Path) 
      { 

      try { 
       Write-Verbose "Write a new file to the folder '$_'" 
       $TestPath = Join-Path $_ Get-Random 
       New-Item -Path $TestPath -ItemType File -ErrorAction Stop > $null 
       Write-Verbose "Return TRUE for '^$_'" 
       $true 
      } 
      catch { 
        Write-Verbose "Catch return FALSE for '$_'" 
        $false 
      } 
      finally { 
        Remove-Item $TestPath -ErrorAction SilentlyContinue 
      } 

      } 
    } 

我已經刪除了關鍵return即停止在foreach!

+0

我應該看到的!但它仍然很奇怪,它管​​道時,管道..謝謝你的幫助CB,真的很感激它。 – DarkLite1

+0

@ darklite1很樂意幫忙! –