Powershell: Difference between revisions

From Leo's Notes
This page was last edited on 17 April 2017, at 21:25.
→Syntax: boolean
Line 15: Line 15:
   -param2 value
   -param2 value
}}
}}
==== Boolean Values ====
Use {{code|$TRUE}} or {{code|$FALSE}}.


==== Data Containers ====
==== Data Containers ====

Revision as of 21:25, 17 April 2017

Quick Overview

Syntax

Comments

<#
multi-line comments
#>

Multi-Line Commands

Similar to the \ in bash, use the backtick to continue the command on the next line.

Do-Something `
  -param1 value `
  -param2 value

Boolean Values

Use $TRUE or $FALSE.

Data Containers

These are things in powershell that can contain data values or other objects.

Objects
$a = New-Object –TypeNamePSObject
$a

Arrays

$a = @()
$a += "Item"

Hash Tables (aka. a Dictionary)

# Basic Operation
$a = @{}
$a.Add("Key", "Value")
$a["Key"] = "New Value"
$a.Remove("Key")

# To iterate over the hash table
$a.GetEnumerator()

Parameters

param (
 ??
)

Common Tasks

Writing Output

Use Write-Host to write logging information to the console. It runs [console]::WriteLine() in the background.

Use Write-Output to write to the pipeline.

In either case, wrap the output text in brackets so that concatenation works as expected. Eg: Write-Output ("Hello" + $World).

Filtering

Pipe to Where-Object and provide the matching condition.

Where-Object {$_.RecordData.IPv4Address -like "172.20.1.*" }

Iterating

Use the ForEach statement:

foreach($item in $items) {
  # do things on $item
}

Or if you're dealing with a list of objects, pipe to the ForEach-Object. Pass in any of:

  • -process - Runs for each incoming object
  • -begin - Runs before any object is processed
  • -end - Runs after objects are processed

Eg:

ForEach-Object -process { $_.doSomething() }

Other Stuff

Get machine UIUD

get-wmiobject Win32_ComputerSystemProduct  | Select-Object -ExpandProperty UUID


Troubleshooting

Error: "File cannot be loaded because the execution of scripts is disabled on this system"

To allow untrusted script execution, open a powershell instance (same arch as what you're trying to run the script as. ie: 64bit/32bit) as Administrator and run:

PS> set-executionpolicy unrestricted

You should now be able to see:

PS> get-executionpolicy
Unrestricted