반응형
파워셸에서 XML을 통해 반복하는 방법은 무엇입니까?
텍스트 파일에 다음 XML 문서가 있습니다.
<?xml version="1.0"?>
<Objects>
<Object Type="System.Management.Automation.PSCustomObject">
<Property Name="DisplayName" Type="System.String">SQL Server (MSSQLSERVER)</Property>
<Property Name="ServiceState" Type="Microsoft.SqlServer.Management.Smo.Wmi.ServiceState">Running</Property>
</Object>
<Object Type="System.Management.Automation.PSCustomObject">
<Property Name="DisplayName" Type="System.String">SQL Server Agent (MSSQLSERVER)</Property>
<Property Name="ServiceState" Type="Microsoft.SqlServer.Management.Smo.Wmi.ServiceState">Stopped</Property>
</Object>
</Objects>
나는 각각의 물체를 반복해서 찾고 싶습니다.DisplayName
그리고.ServiceState
내가 그걸 어떻게 하겠어요?저는 모든 종류의 조합을 시도했고 그것을 해결하기 위해 고군분투하고 있습니다.
XML을 변수로 변환하기 위해 이 작업을 수행하고 있습니다.
[xml]$priorServiceStates = Get-Content $serviceStatePath;
어디에$serviceStatePath
는 위에 표시된 xml 파일 이름입니다.그리고 나서 저는 다음과 같은 것을 할 수 있다고 생각했습니다.
foreach ($obj in $priorServiceStates.Objects.Object)
{
if($obj.ServiceState -eq "Running")
{
$obj.DisplayName;
}
}
그리고 이 예에서 저는 다음과 같이 출력되는 문자열을 원합니다.SQL Server (MSSQLSERVER)
PowerShell에는 XML 및 XPath 기능이 내장되어 있습니다.Select-Xml cmdlet을 XPath 쿼리와 함께 사용하여 XML 개체에서 노드를 선택한 다음에 를 선택할 수 있습니다.노드 값에 액세스할 노드.'#text'입니다.
[xml]$xml = Get-Content $serviceStatePath
$nodes = Select-Xml "//Object[Property/@Name='ServiceState' and Property='Running']/Property[@Name='DisplayName']" $xml
$nodes | ForEach-Object {$_.Node.'#text'}
또는 더 짧음
[xml]$xml = Get-Content $serviceStatePath
Select-Xml "//Object[Property/@Name='ServiceState' and Property='Running']/Property[@Name='DisplayName']" $xml |
% {$_.Node.'#text'}
[xml] 캐스트 없이도 수행할 수 있습니다. (xpath는 그 자체로 월드입니다.)https://www.w3schools.com/xml/xml_xpath.asp)
$xml = (select-xml -xpath / -path stack.xml).node
$xml.objects.object.property
또는 이것만으로도 xpath는 대소문자를 구분합니다.둘 다 출력이 동일합니다.
$xml = (select-xml -xpath /Objects/Object/Property -path stack.xml).node
$xml
Name Type #text
---- ---- -----
DisplayName System.String SQL Server (MSSQLSERVER)
ServiceState Microsoft.SqlServer.Management.Smo.Wmi.ServiceState Running
DisplayName System.String SQL Server Agent (MSSQLSERVER)
ServiceState Microsoft.SqlServer.Management.Smo.Wmi.ServiceState Stopped
언급URL : https://stackoverflow.com/questions/18509358/how-to-iterate-through-xml-in-powershell
반응형
'prosource' 카테고리의 다른 글
npm을 통해 설치된 노드 모듈을 편집하려면 어떻게 해야 합니까? (0) | 2023.07.27 |
---|---|
sql 중첩된 대/소문자 문장 (0) | 2023.07.27 |
PLSQL 랜덤 정수 생성 (0) | 2023.07.27 |
mysql 정렬 문자열 번호 (0) | 2023.07.27 |
$_SERVER["REMOTE_ADDR"]는 방문자 IP가 아닌 서버 IP를 제공합니다. (0) | 2023.07.27 |