简体   繁体   中英

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)...

[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. But why does "Write-Host $InputVariable" output an empty string?

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")?

This works: "someservername" | ./script This does not work: ./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"
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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