Disclaimer: I am a consultant at Amazon Web Services, and this is my personal blog. The opinions expressed here are solely mine and do not reflect the views of Amazon Web Services (AWS). Any statements made should not be considered official endorsements or statements by AWS.
Recently I started working on PowerShell as I was working on C# for a long time. Initially, it took me a while to get familiar with the PowerShell syntaxes. That’s why I thought to put all my google searches over here in this single post. I hope this will help you during your transition period from C# to PowerShell.
# declare & initialize an array
[string[]] $names = @("Ankush", "Virat", "Sachin", "MS Dhoni")
# call for loop
For ($i=0; $i -lt $names.count ; $i++) {
[string]$playerName = $names[$i]
Write-Output $playerName
}
# declare & initialize an array
[string[]] $names = @("Ankush", "Virat", "Sachin", "MS Dhoni")
# call foreach
Foreach ($playerName in $names)
{
Write-Output $playerName
}
[bool] $result = $true
if($result){
Write-Output "Success"
}
# declare & initialize an array
[string[]] $names = @("Ankush", "Virat", "Sachin", "MS Dhoni")
# declare & initialize an array
[string[]] $names = @("Ankush", "Virat", "Sachin", "MS Dhoni")
if($names.Contains("Ankush")){
Write-Output "Yes Ankush Exists"
}
# declare & initialize an array
[string[]] $names = @("Ankush", "Virat", "Sachin", "MS Dhoni")
# add item in array
$names += "Ishant"
$i = 4
$j = 8
# use -eq for equal operator
Write-Output ($i -eq $j)
# use -le for less than or equal operator
Write-Output ($i -le $j)
[string]$pathToSave = "C:\Users\ankushjain01\Desktop\"
$apiResult = Invoke-RestMethod -Uri "http://example.com/getusers" -Method Get -ContentType "application/json"
# code to save json
$apiResult | ConvertTo-Json -depth 100 | Set-Content "$pathToSave\users.json"
# physical path to save json result
[string]$pathToSave = "C:\Users\ankushjain01\Desktop\"
# Base64-encodes the Personal Access Token (PAT) appropriately
[string]$base64AuthInfo = [Convert]::ToBase64String([Text.Encoding]::ASCII.GetBytes(("{0}:{1}" -f $user,$password)))
# this method invokes rest api & downloads it's result into json object
$apiResult = Invoke-RestMethod -Uri "http://example.com/getusers" -Method Get -ContentType "application/json" -Headers @{Authorization=("Basic {0}" -f $base64AuthInfo)}
# code to save json
$apiResult | ConvertTo-Json -depth 100 | Set-Content "$pathToSave\users.json"