Accept both AD Computer Objects and Strings as input to a custom cmdlet

This topic contains 2 replies, has 2 voices, and was last updated by Profile photo of Chris Gibson Chris Gibson 11 months ago.

  • Author
  • #32461
    Profile photo of Chris Gibson
    Chris Gibson

    Hi Guys,

    I'm trying to convert any non-AD computer object input feed into my custom cmdlet into an Ad computer object. i.e. if you pass me an AD object (from get-adcomputer etc) along the pipeline, I just process it, however if you pass a string I will get it as a AD object, then process it.

    So far I have tried this...

    if ($ComputerName.GetType() -isnot [Microsoft.ActiveDirectory.Management.ADAccount])
    $computername = Get-adcomputer $computername


    However if I do pipe "get-adcomputer servername" to my cmdlet I get the below error

    You cannot call a method on a null-valued expression.
    At line:68 char:13
    + if ($ComputerName.GetType() -isnot [Microsoft.ActiveDirectory.Management ...
    + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo : InvalidOperation: (:) [], RuntimeException
    + FullyQualifiedErrorId : InvokeMethodOnNull

    Can anyone see what i'm doing wrong?

  • #32462
    Profile photo of Don Jones
    Don Jones

    You'd make separate parameters, each in its own parameter set. Like how Stop-Service does it – you've got one set that accepts -Name , another that accepts -InputObject . You get one or the other, but never both, and you can check $PSBoundParameters to see which one you got.

    So you'd have -ComputerName and -InputObject .

  • #32505
    Profile photo of Chris Gibson
    Chris Gibson

    Thanks Don, that's perfect.

You must be logged in to reply to this topic.