Wednesday, July 20, 2016

PowerShell - Search XML by passing an input parameter

In this script I would like to show how we can perform XML search by passing an input parameter.
Sample xml file to work with the example

  1. <Employees>  
  2. <Employee>  
  3.   <Name>TestName</Name>  
  4.   <Age>32</Age>  
  5.   <Location>Hyderabad</Location>  
  6. </Employee>  
  7. <Employee>  
  8.   <Name>TestName1</Name>  
  9.   <Age>29</Age>  
  10.   <Location>Hyderabad</Location>  
  11. </Employee>  
  12. <Employee>  
  13.   <Name>TestName3</Name>  
  14.   <Age>45</Age>  
  15.   <Location>Rajahmundry</Location>  
  16. </Employee>  
  17. </Employees> 

Power shell script 

  1. cls  
  2. function XmlOperations  
  3. {  
  4.    param (  
  5.         [Parameter(Mandatory)]  
  6.         [string] $EmployeeName  
  7.     )  
  8.   
  9.     $xml = [xml](Get-Content C:\sample.xml)  
  10.     $xml.Employees.Employee | where { $_.Name -like "*$EmployeeName*" }  
  11. }  
  12.   
  13. XmlOperations


No comments:

Post a Comment

Popular Posts