PowerShell管道参数

时间:2014-07-21 09:33:16

标签: powershell parameters

我有点困惑的是,为什么我的函数的路径管道完美地工作,并且当路径存在时返回2次$true并且我们可以写入它。但是当我不管道它并在函数之后附加路径时,它只返回一次$true,好像没有检查第二条路径一样。

这样可以正常运行并返回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
            }
    }
}

1 个答案:

答案 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
            }

            }
    }

我删除了阻止foreach的密钥return