[英]Powershell Pipeline Processing - $_ Works but $ParamName Does Not
I'm having trouble understanding this behavior...我无法理解这种行为...
Given a Powershell script like this (updated with actual code)...鉴于这样的 Powershell 脚本(使用实际代码更新)...
[cmdletbinding(DefaultParameterSetName="Default")]
param (
[cmdletbinding()]
[Parameter( Mandatory=$true,
ValueFromPipeline = $true,
ParameterSetName="Default")]
[Parameter(Mandatory=$true, ParameterSetName="Azure")]
[Parameter(Mandatory=$true, ParameterSetName="AWS")]
[Alias("Server")]
[String[]] $SqlServer,
# other parameters
)
BEGIN {}
PROCESS {
<# *************************************
PROCESS EACH SERVER IN THE PIPELINE
**************************************** #>
Write-Debug "Processing SQL server $_..."
# GET SMO OBJECTS
$Error.Clear()
try {
# GET CONNECTION TO TARGET SERVER
$_svr = _get-sqlconnection -Server $_ -Login $DatabaseLogin -Pwd $Password
# PROCESS DATABASES ON SERVER
} catch {
$Error
}
} END {}
It is my understanding that $_ is the current object in the pipeline and I think I understand why "Write-Host $_" works.我的理解是 $_ 是管道中的当前对象,我想我明白为什么“Write-Host $_”有效。 But why does "Write-Host $InputVariable" output an empty string?
但是为什么“Write-Host $InputVariable”会输出一个空字符串呢?
How must I define the parameter so I can pass values both through the pipeline and as a named parameter (ie - ./script.ps -InputVariable "something")?我必须如何定义参数,以便我可以通过管道和作为命名参数(即 - ./script.ps -InputVariable "something")传递值?
This works: "someservername" |这有效: "someservername" | ./script This does not work: ./script -SqlServer "someservername"
./script 这不起作用:./script -SqlServer "someservername"
Thank you.谢谢你。
$_
is only populated when working on pipeline input. $_
仅在处理管道输入时填充。
If you want to accept both:如果你想同时接受:
"string","morestrings" | ./script.ps1
# and
./script.ps1 -MyParameter "string","morestrings"
... then use the following pattern: ...然后使用以下模式:
[CmdletBinding()]
param(
[Parameter(Mandatory=$true,ValueFromPipeline=$true)]
[string[]]$MyParameter
)
process {
foreach($paramValue in $MyParameter){
Write-Host "MyParameter: $paramValue"
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.