PowerShell changes return object's type

前端 未结 2 1127
无人及你
无人及你 2020-12-06 09:44

I am using PowerShell v3 and the Windows PowerShell ISE. I have the following function that works fine:

function Get-XmlNode([xml]$XmlDocument, [string]$Nod         


        
相关标签:
2条回答
  • 2020-12-06 10:29

    More specifically, what is happening here is that your coding habit of strongly typing $fullyQualifiedModePath is trying to turn the result of the Get (which is a list of objects) into a string.

    [string]$foo

    will constrain the variable $foo to only be a string, no matter what came back. In this case, your type constraint is what is subtly screwing up the return and making it Object[]

    Also, looking at your code, I would personally recommend you use Select-Xml (built into V2 and later), rather than do a lot of hand-coded XML unrolling. You can do namespace queries in Select-Xml with -Namespace @{x="..."}.

    0 讨论(0)
  • What's happening is PowerShell is converting your namespace manager object to a string array.

    I think it has to do with PowerShell's nature of "unrolling" collections when sending objects down the pipeline. I think PowerShell will do this for any type implementing IEnumerable (has a GetEnumerator method).

    As a work around you can use the comma trick to prevent this behavior and send the object as a whole collection.

    function Get-XmlNamespaceManager([xml]$XmlDocument, [string]$NamespaceURI = "")
    {
        ...
        $xmlNsManager.AddNamespace("ns", $NamespaceURI)
        return ,$xmlNsManager
    }
    
    0 讨论(0)
提交回复
热议问题