Condividi tramite


Select-Xml

Trova il testo in una stringa o in un documento XML.

Sintassi

Select-Xml
      [-Xml] <XmlNode[]>
      [-XPath] <String>
      [-Namespace <Hashtable>]
      [<CommonParameters>]
Select-Xml
      [-Path] <String[]>
      [-XPath] <String>
      [-Namespace <Hashtable>]
      [<CommonParameters>]
Select-Xml
      -LiteralPath <String[]>
      [-XPath] <String>
      [-Namespace <Hashtable>]
      [<CommonParameters>]
Select-Xml
      -Content <String[]>
      [-XPath] <String>
      [-Namespace <Hashtable>]
      [<CommonParameters>]

Descrizione

Il cmdlet Select-Xml consente di usare query XPath per cercare testo in stringhe e documenti XML. Immettere una query XPath e usare il parametro Content, Path o Xml per specificare il codice XML da cercare.

Esempio

Esempio 1: Selezionare i nodi AliasProperty

PS C:\> $Path = "$Pshome\Types.ps1xml"
PS C:\> $XPath = "/Types/Type/Members/AliasProperty"
PS C:\> Select-Xml -Path $Path -XPath $Xpath | Select-Object -ExpandProperty Node

Name                 ReferencedMemberName
----                 --------------------
Count                Length
Name                 Key
Name                 ServiceName
RequiredServices     ServicesDependedOn
ProcessName          Name
Handles              Handlecount
VM                   VirtualSize
WS                   WorkingSetSize
Name                 ProcessName
Handles              Handlecount
VM                   VirtualMemorySize
WS                   WorkingSet
PM                   PagedMemorySize
NPM                  NonpagedSystemMemorySize
Name                 __Class
Namespace            ModuleName

Questo esempio ottiene le proprietà alias in Types.ps1xml. (Per informazioni su questo file, vedere about_Types.ps1xml).

Il primo comando salva il percorso del file Types.ps1xml nella variabile $Path.

Il secondo comando salva il percorso XML del nodo AliasProperty nella variabile $XPath.

Il terzo comando usa il cmdlet Select-Xml per ottenere i nodi AliasProperty identificati nell'istruzione XPath dal file Types.ps1xml. Il comando usa un operatore pipeline per inviare i nodi AliasProperty al cmdlet Select-Object. Il parametro ExpandProperty espande l'oggetto Node e restituisce le proprietà Name e ReferencedMemberName.

Il risultato mostra le proprietà Name e ReferencedMemberName di ciascuna proprietà alias nel file Types.ps1xml. Ad esempio, esiste una proprietà Count che è un alias della proprietà Length .

Esempio 2: Immettere un documento XML

PS C:\> [xml]$Types = Get-Content $Pshome\Types.ps1xml
PS C:\> Select-Xml -Xml $Types -XPath "//MethodName"

In questo esempio viene illustrato come utilizzare il parametro XML per fornire un documento XML al cmdlet Select-Xml .

Il primo comando usa il cmdlet Get-Content per ottenere il contenuto del file Types.ps1xml e salvarlo nella variabile $Types. [xml] esegue il cast della variabile come oggetto XML.

Il secondo comando usa il cmdlet Select-Xml per ottenere i nodi MethodName nel file Types.ps1xml. Il comando usa il parametro Xml per specificare il contenuto XML nella variabile $Types e il parametro XPath per specificare il percorso del nodo MethodName.

Esempio 3: Search file della Guida di PowerShell

PS C:\> $Namespace = @{command = "https://schemas.microsoft.com/maml/dev/command/2004/10"; maml = "https://schemas.microsoft.com/maml/2004/10"; dev = "https://schemas.microsoft.com/maml/dev/2004/10"}

The second command saves the path to the help files in the $Path variable.If there are no help files in this path on your computer, use the Update-Help cmdlet to download the help files. For more information about Updatable Help, see about_Updatable_Help (https://go.microsoft.com/fwlink/?LinkId=235801).
PS C:\> $Path = "$Pshome\en-us\*dll-Help.xml"

The third command uses the **Select-Xml** cmdlet to search the XML for cmdlet names by finding Command:Name element anywhere in the files. It saves the results in the $Xml variable.**Select-Xml** returns a **SelectXmlInfo** object that has a Node property, which is a **System.Xml.XmlElement** object. The Node property has an InnerXML property, which contains the actual XML that is retrieved.
PS C:\> $Xml = Select-Xml -Path $Path -Namespace $Namespace -XPath "//command:name"

The fourth command sends the XML in the $Xml variable to the Format-Table cmdlet. The **Format-Table** command uses a calculated property to get the Node.InnerXML property of each object in the $Xml variable, trim the white space before and after the text, and display it in the table, along with the path to the source file.
PS C:\> $Xml | Format-Table @{Label="Name"; Expression= {($_.node.innerxml).trim()}}, Path -AutoSize

Name                    Path
----                    ----
Export-Counter          C:\Windows\system32\WindowsPowerShell\v1.0\en-us\Microsoft.PowerShell.Commands.Diagnostics.dll-Help.xml
Get-Counter             C:\Windows\system32\WindowsPowerShell\v1.0\en-us\Microsoft.PowerShell.Commands.Diagnostics.dll-Help.xml
Get-WinEvent            C:\Windows\system32\WindowsPowerShell\v1.0\en-us\Microsoft.PowerShell.Commands.Diagnostics.dll-Help.xml
Import-Counter          C:\Windows\system32\WindowsPowerShell\v1.0\en-us\Microsoft.PowerShell.Commands.Diagnostics.dll-Help.xml
Add-Computer            C:\Windows\system32\WindowsPowerShell\v1.0\en-us\Microsoft.PowerShell.Commands.Management.dll-Help.xml
Add-Content             C:\Windows\system32\WindowsPowerShell\v1.0\en-us\Microsoft.PowerShell.Commands.Management.dll-Help.xml
Checkpoint-Computer     C:\Windows\system32\WindowsPowerShell\v1.0\en-us\Microsoft.PowerShell.Commands.Management.dll-Help.xml
...

In questo esempio viene illustrato come usare il cmdlet Select-Xml per eseguire ricerche nei file della Guida dei cmdlet basati su XML di PowerShell. In questo esempio viene cercato il nome del cmdlet che funge da titolo per ogni file della Guida e il percorso del file della Guida.

Il primo comando crea una tabella hash che rappresenta lo spazio dei nomi XML usato per i file della Guida e la salva nella variabile $Namespace.

Esempio 4: modi diversi per l'input XML

PS C:\> $Xml = @"
<?xml version="1.0" encoding="utf-8"?>
<Book>
  <projects>
    <project name="Book1" date="2009-01-20">
      <editions>
        <edition language="English">En.Book1.com</edition>
        <edition language="German">Ge.Book1.Com</edition>
        <edition language="French">Fr.Book1.com</edition>
        <edition language="Polish">Pl.Book1.com</edition>
      </editions>
    </project>
  </projects>
</Book>
"@

The second command uses the *Content* parameter of **Select-Xml** to specify the XML in the $Xml variable.
PS C:\> Select-Xml -Content $Xml -XPath "//edition" | foreach {$_.node.InnerXML}

En.Book1.com
Ge.Book1.Com
Fr.Book1.com
Pl.Book1.com

The third command is equivalent to the second. It uses a pipeline operator (|) to send the XML in the $Xml variable to the **Select-Xml** cmdlet.
PS C:\> $Xml | Select-Xml -XPath "//edition" | foreach {$_.node.InnerXML}

En.Book1.com
Ge.Book1.Com
Fr.Book1.com
Pl.Book1.com

In questo esempio vengono illustrati due modi diversi per inviare XML al cmdlet Select-Xml .

Il primo comando salva una stringa here contenente XML nella variabile $Xml. Per altre informazioni sulle stringhe di tipo here, vedere about_Quoting_Rules.

Esempio 5: Usare lo spazio dei nomi xmlns predefinito

PS C:\> $SnippetNamespace = @{snip = "https://schemas.microsoft.com/PowerShell/Snippets"}

The second command uses the **Select-Xml** cmdlet to get the content of the Title element of each snippet. It uses the *Path* parameter to specify the Snippets directory and the *Namespace* parameter to specify the namespace in the $SnippetNamespace variable. The value of the *XPath* parameter is the "snip" namespace key, a colon (:), and the name of the Title element.The command uses a pipeline operator (|) to send each **Node** property that **Select-Xml** returns to the ForEach-Object cmdlet, which gets the title in the value of the **InnerXml** property of the node.
PS C:\> Select-Xml -Path $Home\Documents\WindowsPowerShell\Snippets -Namespace $SnippetNamespace -XPath "//snip:Title" | foreach {$_.Node.Innerxml}

In questo esempio viene illustrato come utilizzare il cmdlet Select-Xml con documenti XML che usano lo spazio dei nomi xmlns predefinito. L'esempio ottiene i titoli dei file dei frammenti di codice creati dall'utente di Windows PowerShell ISE. Per informazioni sui frammenti, vedere New-IseSnippet.

Il primo comando crea una tabella hash per lo spazio dei nomi predefinito usato dai file XML del frammento di codice e lo assegna alla variabile $SnippetNamespace. Il valore della tabella hash è l'URI dello schema XMLNS nell'XML del frammento di codice. Il nome della chiave della tabella hash, snip, è arbitrario. È possibile usare qualsiasi nome non riservato, ma non è possibile usare xmlns.

Parametri

-Content

Specifica una stringa che contiene il file XML da cercare. È anche possibile inviare tramite pipe le stringhe a Select-Xml.

Type:String[]
Position:Named
Default value:None
Required:True
Accept pipeline input:True
Accept wildcard characters:False

-LiteralPath

Specifica i percorsi e i nomi file dei file XML da cercare. A differenza di Path, il valore del parametro LiteralPath viene usato esattamente com'è digitato. Nessun carattere viene interpretato come carattere jolly. Se il percorso include caratteri di escape, racchiuderlo tra virgolette singole. Le virgolette singole indicano a PowerShell di non interpretare alcun carattere come sequenze di escape.

Type:String[]
Aliases:PSPath
Position:Named
Default value:None
Required:True
Accept pipeline input:True
Accept wildcard characters:False

-Namespace

Specifica una tabella hash degli spazi dei nomi usati nel file XML. Usare il formato @{<namespaceName> = <namespaceValue>}.

Quando il codice XML usa lo spazio dei nomi predefinito, che inizia con xmlns, usare una chiave arbitraria per il nome dello spazio dei nomi. Non è possibile usare xmlns. Nell'istruzione XPath anteporre a ogni nome di nodo il nome dello spazio dei nomi e i due punti, ad esempio //namespaceName:Node.

Type:Hashtable
Position:Named
Default value:None
Required:False
Accept pipeline input:False
Accept wildcard characters:False

-Path

Specifica il percorso e i nomi file dei file XML da cercare. I caratteri jolly sono consentiti.

Type:String[]
Position:1
Default value:None
Required:True
Accept pipeline input:True
Accept wildcard characters:True

-Xml

Specifica uno o più nodi XML.

Un documento XML verrà elaborato come una raccolta di nodi XML. Se si invia tramite pipe un documento XML a Select-Xml, ogni nodo del documento verrà cercato separatamente man mano che passa attraverso la pipeline.

Type:XmlNode[]
Aliases:Node
Position:1
Default value:None
Required:True
Accept pipeline input:True
Accept wildcard characters:False

-XPath

Specifica una query di ricerca XPath. Il linguaggio della query distingue tra maiuscole e minuscole. Questo parametro è obbligatorio.

Type:String
Position:0
Default value:None
Required:True
Accept pipeline input:False
Accept wildcard characters:False

Input

System.String or System.Xml.XmlNode

È possibile inviare tramite pipe un percorso o un nodo XML a questo cmdlet.

Output

SelectXmlInfo

Note