PowerShell Syntax HighLighting with PowerShell Script

For script in the previous post, I needed a tool that would convert PowerShell script to HTML format. Surprisingly numerous online tools somehow completely ignored PowerShell, so I found PowerShell scripts that would do the job: PowerShell Syntax Highlighting by Lee Holmes, an extended version by Helge Klein, and different implementation, which will only work on PowerShell 2.0 by Jeff Hillman.

PowerShell Syntax HighLighting with PowerShell Script

Post Issue to Jira Using PowerShell 2.0

Some time ago I was looking for a skeleton of a PowerShell 2.0 script that would allow me to post an issue to Jira. Didn’t find one, so had to come up with my own.

# Change those strings to whatever is specific to environment
[string] $SERVER = “localhost:8080”
[string] $USER = “powershelluser”
[string] $PWD = “password”
# Get Project ID from Administration -> Projects, e.g. 
[string] $PROJECTID = “10123”
# Specify fields that need to be posted
# NOTE: You must provide all required fields
# Example below submits 4 fields: 
#    assignee – automatically assigned to default user of the project
#    issuetype – selected type 3 = task
#    summary and description, which are read from elsewhere
[string] $FIELDS = “issuetype=3&priority=3&assignee=-1&summary={0}&description={1}”

# Those constants normally do not change
[string] $LOGIN_URL = http://{0}/login.jsp?os_username={1}&os_password={2}&os_destination=/secure/”
[string] $CREATE_URL = http://{0}/secure/CreateIssueDetails.jspa?pid={1}&{2}&Create=Create&atl_token={3}”
[string] $TOKEN_PREFIX = ‘<meta id=”atlassian-token” name=”atlassian-token” content=”‘
[string] $TOKEN_SUFFIX = ‘”>’

function loginToJira($server, $user, $pwd) {

[string] $postUrl = $url -f  $user, $pwd

[System.Net.WebRequest] $webRequest = [System.Net.WebRequest]::Create($postUrl)
$webRequest.CookieContainer = New-object System.Net.CookieContainer
[System.Net.WebResponse] $webResponse = $webRequest.getResponse()
# TO DO: Response can be verified here
# One of the ways to check if request was successful is to read $webResponse.StatusDescription, e.g.
Write-Host “status = “ $webResponse.StatusDescription;

$resStream = $webResponse.GetResponseStream()
[System.IO.StreamReader] $streamReader = New-Object System.IO.StreamReader -argumentList $resStream
$res = $streamReader.ReadToEnd()
$start = $res.IndexOf($TOKEN_PREFIX, 0+ $TOKEN_PREFIX.Length
$end = $res.IndexOf($TOKEN_SUFFIX, $start)
$token = $res.substring($start, $end  $start)

return $webRequest.CookieContainer, $token
}

function createJiraIssue($server, $session, $token, $project_id, $summary, $description) {

[string] $formattedFields = $FIELDS -f [System.Web.HttpUtility]::UrlEncode($summary), [System.Web.HttpUtility]::UrlEncode($description)
[string] $postUrl = $CREATE_URL -f $server, $project_id, $formattedFields, $token

[System.Net.WebRequest]$webRequest = [System.Net.WebRequest]::Create($postUrl);
$webRequest.CookieContainer = $session
[System.Net.WebResponse]$webResponse = $webRequest.getResponse()
# TO DO: Response can be verified here (similar to login)

$resStream = $webResponse.GetResponseStream()
[System.IO.StreamReader]$streamReader = New-Object System.IO.StreamReader -argumentList $resStream
$res = $streamReader.ReadToEnd()
# TO DO: Here it can be verified if the issue was posted successully, by looking into $res
# If issue is not posted, Jira will return HTML similar to the page seeing by the user who tried to post issue with missing / problematic fields
}

if($args.count -ne 3) {
showHelp
break
}
Add-Type -AssemblyName System.Web
$session, $token = loginToJira $SERVER $USER $PWD
$testsummary = “This is a test – issue summary”
$testdscription = “This is a test.`n`nIssue description usually contains several lines of text”
createJiraIssue $session $token $PROJECTID $testsummary $testdscription

Post Issue to Jira Using PowerShell 2.0

A few PowerShell 2.0 Know-Hows

Script Snippets

1. Create a Unique Folder Name

(From: “Hey PowerShell guy, how can I create a new folder using a name based on the current date”)

function Create-UniqueFolder([string]$path) {
  md ($path + "\result_$((get-date).toString('yyyyMMddHHmmss'))")
}

2. Check if Script Runs on x86 or x64 Platform

(From: “What is the best way to program against PowerShells x64 vs x86 Variability”)

function Is-Wx64 {
  return test-path (join-path $env:WinDir "SysWow64")
}

3. Locate an Assembly (in Known Path, such As GAC)

function Get-AssemblyPathByName([string]$name) {
   return [System.Reflection.Assembly]::LoadWithPartialName($name).Location
}

4. Read XML File

$file = "XML file path"
[System.Xml.XmlDocument] $xd = new-object System.Xml.XmlDocument
 $xd.load($file)
# ... for example ...
$xd.SelectSingleNode("/mynode").getAttribute("myattribute")

5. Replace All Occurrences of a String in File

function Replace-InFile([string]$file, [string]$find, [string]$replace) {
  (Get-Content $file) | Foreach-Object {$_ -replace $find, $replace} | Set-Content $file
}

6. Handle a Process

Start a Process, Get Process Output and Standard Error Output, Wait for Process to Complete

# ... example doesn't load user profile, but redirects and retrieves stdout and stderr
$StartInfo = New-Object System.Diagnostics.ProcessStartInfo
 $StartInfo.FileName = "process path and name"
 $StartInfo.Arguments="process arguments, if any"
 $StartInfo.LoadUserProfile = $false
 $StartInfo.RedirectStandardOutput = $true
 $StartInfo.RedirectStandardError = $true
 $StartInfo.UseShellExecute = $false
 $StartInfo.WorkingDirectory = "working directory path"

 $process = [System.Diagnostics.Process]::Start($StartInfo)
# At this point can access process properties, e.g.:
Write-Host ("Started process with PID=" + $process.Id)

# Saving output to a file
 $stderr = $process.StandardError
if ($stdout -ne $null) {
  $output = $stdout.ReadToEnd()
  $outfile = "location and name of file to save output to"
  if ($output -ne "") { $output | Out-File $outfile }
 }
# Saving standard error output to a file
$stdout = $process.StandardOutput
 if ($stderr -ne $null) {
  $errors = $stderr.ReadToEnd()
  $errfile = "file to save errors to"
  if ($errors -ne "") { $errors | Out-File $errfile }
 }

 [void] $process.WaitForExit

7. Get Script Own Path

(From: Get Script Directory)

$scriptPath = Split-Path $MyInvocation.MyCommand.Path

Syntax and Cmdlets

1. Show Something on Screen

Write-Host "whatever you want to show on screen"

2. Run WMI Query

gwmi win32_service # or other class

Also handy in conjunction with filter:

gwmi win32_service | where-object {$_.Name -eq "service name" }

… And query on top of that:

gwmi win32_service | where-object {$_.Name -eq "service name" } | select Status,State,StartName,StartMode

3. Text File

Reading:

Get-Content "my file"

Writing:

Set-Content "my file" "my content"

Appending:

Add-Content "my file" "my content"

4. Check if File Exists

test-path "file path and name"

5. String Functions

See: The String’s the Thing

6. Comparison Operators

See: About Comparison Operators

7. Special Characters (like tab, newline)

`0 -- Null
`a -- Alert
`b -- Backspace
`n -- New line
`r -- Carriage return
`t -- Horizontal tab
`' -- Single quote
`" -- Double quote

A few PowerShell 2.0 Know-Hows