PowerShell advanced function output PipelineVariable doesn't work -
i created advanced function mac address vm running on vmware esxi.
function get-macfromvm { [cmdletbinding(supportsshouldprocess=$true)] param( # name of vm of want obtain mac address. [parameter(mandatory=$true, valuefrompipeline=$true, valuefrompipelinebypropertyname=$true)] [string[]] $name ) begin {} process { foreach ($item in $name) { if ($pscmdlet.shouldprocess($item, "getting mac address")) { get-vm $item -pipelinevariable vm | get-networkadapter | select-object @{n="name"; e={$vm.name}}, @{n="clientid"; e={$_.macaddress -replace ":","-"}} } } } end {} }
so far works perfect. can use in of following ways , results back.
it accepts either single or array of string via named parameter or pipeline input.
get-macfromvm -name "playground" get-macfromvm -name "playground", "dc01" "playground", "dc01" | get-macfromvm
the output [pscustomobject]
2 properties, name , clientid.
now problem starts when want chain result multiple other cmdlets using -pipelinevariable
parameter.
normally should able use this:
get-macfromvm -name "playground" -pipelinevariable pv | % {$pv}
but doesn't show me results back. if substitute $pv
$_
show correct result, cannot use automatic variable 2 or 3 cmdlets farther in pipeline chain.
although can solve using -outvariable
and/or split multiple lines. want know why doesn't work, want know i'm missing here.
i have no experience -pipelinevariable
parameter. so, took opportunity learn -pipelinevariable
parameter:
because not have easy access vms either, simulated function follows:
function get-macfromvm { [cmdletbinding(supportsshouldprocess=$true)] param( [parameter(mandatory=$true, valuefrompipeline=$true, valuefrompipelinebypropertyname=$true)] [string[]] $name ) function macaddress {(1..4 | foreach {'{0:x2}' -f (get-random -min 0 -max 255)}) -join ":"} function get-vm {[cmdletbinding()] param ($name) [pscustomobject]@{name = $name; macaddress = (macaddress)}} foreach ($item in $name) { if ($pscmdlet.shouldprocess($item, "getting mac address")) { get-vm $item -pipelinevariable vm | select-object @{n="name"; e={$vm.name}}, @{n="clientid"; e={$_.macaddress -replace ":","-"}} } } }
but not able reproduce issue:
ps c:\> get-macfromvm -name "playground", "dc01" -pipelinevariable pv | % {$pv} name clientid ---- -------- playground 3c-23-55-c4 dc01 4f-38-42-a7
so wonder if simulated function works you.
if yes, maybe can find differences real vm object.
knowing powershell, question whether there nothing outputted or nothing displayed. happens if output single property:
get-macfromvm -name "playground" -pipelinevariable pv | % {$pv.name}
or:
get-macfromvm -name "playground" -pipelinevariable pv | % {$pv.gettype()}
does return "you cannot call method on null-valued expression.
" error?
Comments
Post a Comment