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

Advertisements
A few PowerShell 2.0 Know-Hows

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s