Thursday, February 4, 2016

Powershell Programming

I am just putting togetther simple things that I come to know about powershell and i just said wow!


1. How to Merge XML files using powershell:


Let consider we have two below xml files to merge:

C:/MainFile.xml
<?xml version="1.0"?>
<catalog>
   <Recipe id="rc501">
      <author>Suhas, Tiwaskar</author>
      <title>C++ Cofta</title>
      <price>98.95</price>
      <originated_from>Sewagram</originated_from>
   </Recipe>
   <Recipe id="rc502">
      <author>Harish, Datey</author>
      <title>Java Malai</title>
      <price>1765.00</price>
      <originated_from>Khandesh</originated_from>
   </Recipe>
</catalog>

C:/Delta.xml
<?xml version="1.0"?>
<catalog>
   <Recipe id="rc503">
      <author>Vaibhav, Wakodikar</author>
      <title>.Net Rajma</title>
      <price>98.95</price>
      <originated_from>Karve, Nagar</originated_from>
   </Recipe>
   <Recipe id="rc504">
      <author>Amit, Nandurikar</author>
      <title>PHP Rassam</title>
      <price>116.00</price>
      <originated_from>Aurangabad</originated_from>
   </Recipe>

</catalog>

Now create one more File with name mergeXml.ps1 in C:\  with below content:

[xml]$File1 = Get-Content C:\MainFile.xml
[xml]$File2 = Get-Content C:\Delta.xml
ForEach ($XmlNode in $File2.DocumentElement.ChildNodes){$File1.DocumentElement.AppendChild($File1.ImportNode($XmlNode, $true))}
$File1.Save('C:\Merged.xml')


now on powershell window run this script by running "powershell C:\mergeXML.ps1" it will merge two xml files.


you may get error "The input document has exceeded a limit set by MaxCharactersFromEntities". you need to make one trick so that validator will turn off. Upper code will changed to:

$MainFile = New-Object System.Xml.XmlDocument
$MainFile.XmlResolver = $null
$MainFile.Load($args[0])

$DeltaFile = New-Object System.Xml.XmlDocument
$DeltaFile.XmlResolver = $null
$DeltaFile.Load($args[1])


ForEach ($XmlNode in $DeltaFile.DocumentElement.ChildNodes){$MainFile.DocumentElement.AppendChild($MainFile.ImportNode($XmlNode, $true))}
$MainFile.Save($args[0])

========================================================================


2. Get the output of command in variable using Powershell

$output = cmd /c "set JAVA_HOME"

this will push output of command "set JAVA_HOME" to $output variable, after which you can print that variable content using:

return $output

========================================================================


3. Splitting the content using Powershell

$output = cmd /c "set"

this will just push output of command set to variable $output, if we want to split the content by new line character

ForEach($line in $output){     //looping on lines
    $split = $line -split "="  //split by "="
    $varName = $split[0]
    Write-Host $varName        //writing to console
}


========================================================================

4. How to know if variable is empty or not

There are multiple ways but I am keeping here the simplest one:

if($yourName) {           
Write-Host $yourName" is awesome!"      
}


========================================================================

5. Error: “execution of scripts is disabled on this system”

Yes you need to set execution policy to powershell command prompt like below:

powershell.exe -ExecutionPolicy Unrestricted C:\SampleScript.ps1

this will bypass the restrictions and execute the command.

Documentation
========================================================================

6. Downloading the Amazon S3 Bucket content

# Your account access key - must have read access to your S3 Bucket
$accessKey = "your_access_key"
# Your account secret access key
$secretKey = "your_success_key"
# The region associated with your bucket e.g. eu-west-1, us-east-1, us-west-2, eu-west-1, eu-central-1, ap-southeast-1, ap-northeast-1, ap-southeast-2, ap-northeast-2, sa-east-1. Documentation 
$region = "us-east-1"
# The name of your S3 Bucket
$bucket = "your_s3bucket_name"
# The folder in your bucket to copy, including trailing slash. Leave blank to copy the entire bucket
$keyPrefix = "folder_name/"
# The local file path where files should be copied
$localPath = "D:\YourLocalFolder\"

$objects = Get-S3Object -BucketName $bucket -KeyPrefix $keyPrefix -AccessKey $accessKey -SecretKey $secretKey -Region $region

foreach($object in $objects) {
$localFileName = $object.Key -replace $keyPrefix, ''
if ($localFileName -ne '') {
$localFilePath = Join-Path $localPath $localFileName
Copy-S3Object -BucketName $bucket -Key $object.Key -LocalFile $localFilePath -AccessKey $accessKey -SecretKey $secretKey -Region $region
}
}

====================================================================

7. Creating directory using powershell script


New-Item -ItemType directory -Path C:\Scripts\newDir

====================================================================

8. Adding Content at the end of File


Add-Content C:\Windows\System32\drivers\etc\hosts "`n127.0.0.0 hostname"

====================================================================

No comments:

Post a Comment