2011-04-15 43 views
3

我想构造一个可以用来调用另一个powershell命令的计算机名列表。Powershell格式输出System.Xml.XmlElement类型

手工工艺:

$Type1Machines="Machine1","Machine2","Machine3","Machine4" 
Invoke-command {Powershell.exe C:\myscript.ps1 Type1} -computername $Type1Machines 

我已经有关于 “类型1” 的机器在一个XML文件中的名称信息(MachineInfo.xml)

<Servers> 
<Type1> 
<Machine><Name>Machine1</Name> <MachineOS>WinXP</MachineOS></Machine> 
<Machine><Name>Machine2</Name> <MachineOS>WinServer2003</MachineOS></Machine> 
<Machine><Name>Machine3</Name> <MachineOS>WinServer2003</MachineOS></Machine> 
<Machine><Name>Machine4</Name><MachineOS>WinServer2003</MachineOS></Machine> 
</Type1> 
</Servers> 

我想写一个脚本,它可以拉起机器名称是“Type1”的列表并构建下面的url。

$ Type1Machines = “MACHINE1”, “机器2”, “Machine3”, “Machine4”

到目前为止,我得到的地步,我可以从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 

输出:

Machine 
------- 
{Machine1, Machine2, Machine3, Machine4} 

现在我该怎样使用上面的输出,构建以下网址是什么?

$ Type1Machines = “MACHINE1”, “机器2”, “Machine3”, “Machine4”

任何帮助表示赞赏。谢谢你的时间!

回答

2

我假设你想在每个机器名称值放入数组(与调用-条命令使用):

[string[]]$arr = @() # declare empty array of strings 
$ConfigFile.SelectNodes("/Servers/$typeInformation/Machine") | % {$arr += $_.name} 
+0

我喜欢这个解决方案。比将结果分配给变量并使用for循环提取所需的信息要简单得多。谢谢您的帮助。我应该开始使用这种风格的脚本。 – Sanjeev 2011-04-15 21:18:54

2

这里是你的代码:您刚才忘了“”在XPath查询

#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 
} 
+0

太好了。那工作!感谢给我一只手:) – Sanjeev 2011-04-15 21:16:50

3

接受溶液(复制):

[string[]]$arr = @() # declare empty array of strings 
$ConfigFile.SelectNodes("/Servers/$typeInformation/Machine") | % {$arr += $_.name} 

有这相当于(更多PowerShellish方式,使用.NET只有当你有):

$typeInformation = 'Type1' 
$arr = ($ConfigFile.Servers."$typeInformation".Machine | % { $_.Name }) -join ',' 

$typeInformation = 'Type1' 
$arr = ($ConfigFile | Select-Xml "/Servers/$typeInformation/Machine/Name" | % { $_.Node.'#text' }) -join ',' 
+0

很棒!谢谢! – Sanjeev 2011-04-18 18:32:42