Reputation: 13
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 (i.e. - ./script.ps -InputVariable "something")?
This works: "someservername" | ./script This does not work: ./script -SqlServer "someservername"
Thank you.
Upvotes: 1
Views: 123
Reputation: 174435
$_
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"
}
}
Upvotes: 3