Can someone please tell me what I'm missing here?
function Test-Cmdlet {
[CmdletBinding()]
Param (
[string] $Prepend,
[parameter(ValueFromPipeline=$true)] [string] $OtherString
)
BEGIN
{
if ($Prepend -eq $null) {
$Prepend = ".."
}
}
PROCESS
{
write-host ($Prepend + $OtherString)
}
}
# success:
PS> @( "ab", "cd" ) | Test-Cmdlet "-"
-ab
-cd
# failure:
PS> @( "ab", "cd" ) | Test-Cmdlet
ab
cd
# should be:
..ab
..cd
Why is $Prepend not getting set?
I've tried declaring variables outside the BEGIN/PROCESS blocks, but the interpreter doesn't accept that.
I've tried using: Set-Variable -Name "Prepend" -Value ".." -Scope 1
(and Scope 0, and Scope 2), instead of: $Prepend = "..", but still nothing works.
I'm familiar with $global:Variable, but any idea how to get function-scoped variables in a cmdlet with Advanced Methods?
Edit:
The solution, as per below, is:
function Test-Cmdlet {
[CmdletBinding()]
Param (
[string] $Prepend,
[parameter(ValueFromPipeline=$true)] [string] $OtherString
)
BEGIN
{
$_prepend = $Prepend
if (!$Prepend) {
$_prepend = ".."
}
}
PROCESS
{
write-host ($_prepend + $OtherString)
}
}
[string] $Prepend="..",