Powershell format output of type System.Xml.XmlElement
I'm trying to construct a list of computernames which can then be used to invoke another powershell command.
Manual process:
$Type1Machines="Machine1","Machine2","Machine3","Machine4"
Invoke-command {Powershell.exe C:\myscript.ps1 Type1} -computername $Type1Machines
I already have information about the name of the "Type1" machines in an XML file (MachineInfo.xml)
<Servers>
<Type1>
<Machine><Name>Machine1</Name> <MachineOS>WinXP</MachineOS></Machine>
<Machine><Name>Machine2</Name&开发者_运维问答gt; <MachineOS>WinServer2003</MachineOS></Machine>
<Machine><Name>Machine3</Name> <MachineOS>WinServer2003</MachineOS></Machine>
<Machine><Name>Machine4</Name><MachineOS>WinServer2003</MachineOS></Machine>
</Type1>
</Servers>
I'm trying to write a script which can pull up the list of machine name which are "Type1" and construct the below url.
$Type1Machines="Machine1","Machine2","Machine3","Machine4"
So far, I got to the point where I can get the list of Machine names from the xml
#TypeInformation will be pass as an argument to the final script
$typeinformation = 'Type1'
$global:ConfigFileLocation ="C:\machineinfo.xml"
$global:ConfigFile= [xml](get-content $ConfigFileLocation)
$MachineNames = $ConfigFile.SelectNodes("Servers/$typeinformation")
$MachineNames
Output:
Machine
-------
{Machine1, Machine2, Machine3, Machine4}
Now how do I use the above output and construct the below url?
$Type1Machines="Machine1","Machine2","Machine3","Machine4"
Any help is appreciated. Thanks for your time!
Accepted solution (copied):
[string[]]$arr = @() # declare empty array of strings
$ConfigFile.SelectNodes("/Servers/$typeInformation/Machine") | % {$arr += $_.name}
has this equivalent (more PowerShellish way, use .NET only when you have to):
$typeInformation = 'Type1'
$arr = ($ConfigFile.Servers."$typeInformation".Machine | % { $_.Name }) -join ','
or
$typeInformation = 'Type1'
$arr = ($ConfigFile | Select-Xml "/Servers/$typeInformation/Machine/Name" | % { $_.Node.'#text' }) -join ','
I assume you want each machine name value put into array (to use with invoke-commmand):
[string[]]$arr = @() # declare empty array of strings
$ConfigFile.SelectNodes("/Servers/$typeInformation/Machine") | % {$arr += $_.name}
Here is your code : You just forgot "Machine" in the Xpath query
#TypeInformation will be pass as an argument to the final script
$typeinformation = 'Type1'
$global:ConfigFileLocation ="C:\machineinfo.xml"
$global:ConfigFile= [xml](get-content $ConfigFileLocation)
$Machines = $ConfigFile.SelectNodes("Servers/$typeinformation/Machine")
foreach($Machine in $Machines)
{
Write-Host $Machine.name
}
精彩评论