简体   繁体   English

PowerShell管道参数

[英]PowerShell Piping parameters

I'm a bit confused as to why the piping of path's to my function works perfectly and returns 2 times $true when the path exists and we can write to it. 我对为什么路径到我的函数的管道工作正常并在路径存在并且我们可以写入时返回$true 2倍感到困惑。 But when I don't pipe it and append the paths after the function, it's only returning one time $true as if the second path isn't checked. 但是,当我不通过管道将其添加到函数之后并附加路径时,它仅返回一次$true就像未检查第二条路径一样。

This works fine and returns 2 times $true : 这工作正常,并返回2倍$true

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

This only returns one result of $true : 这只会返回$true一个结果:

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

I think there's something wrong with my parameters, but I can't seem to figure it out. 我认为我的参数有问题,但是我似乎无法弄清楚。 Thank you for your help. 谢谢您的帮助。

Function: 功能:

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

try this: 尝试这个:

[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
            }

            }
    }

I've removed the key return that stop the foreach! 我已经删除了停止foreach的密钥return

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM