Powershell

Windows PowerShell is a command-line shell and scripting language designed for system administration.

PowerShell ISE

The Windows PowerShell Integrated Scripting Environment (ISE) is a host application for Windows PowerShell. In Windows PowerShell ISE, you can run commands and write, test, and debug scripts in a single Windows-based graphic user interface with multiline editing, tab completion, syntax coloring, selective execution, context-sensitive help, and support for right-to-left languages.

Create a script

  • Create a example.ps1 script:

  • Allow script execution (once)

  • Run the script

Cmdlet

Powershell commands are called cmdlets:

  • Cmdlets are .NET Framework class objects; and not just stand-alone executables.

  • Cmdlets can be easily constructed from as few as a dozen lines of code.

  • Parsing, error presentation, and output formatting are not handled by cmdlets. It is done by the Windows PowerShell runtime.

  • Cmdlets process works on objects not on text stream and objects can be passed as output for pipelining.

  • Cmdlets are record-based as they process a single object at a time.

Syntax

Common verbs to use include:

  • Get

  • Start

  • Stop

  • Read

  • Write

  • New

  • Out

Comments

Variables

  • Create variable:

  • Use variable:

  • Get information (e.g. properties and methods) about a variable:

Example:

Special variables

Operator

Description

$$

Represents the last token in the last line received by the session.

$?

Represents the execution status of the last operation. It contains TRUE if the last operation succeeded and FALSE if it failed.

$^

Represents the first token in the last line received by the session.

$_

Same as $PSItem. Contains the current object in the pipeline object. You can use this variable in commands that perform an action on every object or on selected objects in a pipeline.

$ARGS

Represents an array of the undeclared parameters and/or parameter values that are passed to a function, script, or script block.

$CONSOLEFILENAME

Represents the path of the console file (.psc1) that was most recently used in the session.

$ERROR

Represents an array of error objects that represent the most recent errors.

$EVENT

Represents a PSEventArgs object that represents the event that is being processed.

$EVENTARGS

Represents an object that represents the first event argument that derives from EventArgs of the event that is being processed.

$EVENTSUBSCRIBER

Represents a PSEventSubscriber object that represents the event subscriber of the event that is being processed.

$EXECUTIONCONTEXT

Represents an EngineIntrinsics object that represents the execution context of the PowerShell host.

$FALSE

Represents FALSE. You can use this variable to represent FALSE in commands and scripts instead of using the string "false".

$FOREACH

Represents the enumerator (not the resulting values) of a ForEach loop. You can use the properties and methods of enumerators on the value of the $ForEach variable.

$HOME

Represents the full path of the user's home directory.

$HOST

Represents an object that represents the current host application for PowerShell.

$INPUT

Represents an enumerator that enumerates all input that is passed to a function.

$LASTEXITCODE

Represents the exit code of the last Windows-based program that was run.

$MATCHES

The $Matches variable works with the -match and -notmatch operators.

$MYINVOCATION

$MyInvocation is populated only for scripts, function, and script blocks. PSScriptRoot and PSCommandPath properties of the $MyInvocation automatic variable contain information about the invoker or calling script, not the current script.

$NESTEDPROMPTLEVEL

Represents the current prompt level.

$NULL

$null is an automatic variable that contains a NULL or empty value. You can use this variable to represent an absent or undefined value in commands and scripts.

$PID

Represents the process identifier (PID) of the process that is hosting the current PowerShell session.

$PROFILE

Represents the full path of the PowerShell profile for the current user and the current host application.

$PSCMDLET

Represents an object that represents the cmdlet or advanced function that is being run.

$PSCOMMANDPATH

Represents the full path and file name of the script that is being run.

$PSCULTURE

Represents the name of the culture currently in use in the operating system.

$PSDEBUGCONTEXT

While debugging, this variable contains information about the debugging environment. Otherwise, it contains a NULL value.

$PSHOME

Represents the full path of the installation directory for PowerShell.

$PSITEM

Same as $_. Contains the current object in the pipeline object.

$PSSCRIPTROOT

Represents the directory from which a script is being run.

$PSSENDERINFO

Represents information about the user who started the PSSession, including the user identity and the time zone of the originating computer.

$PSUICULTURE

Represents the name of the user interface (UI) culture that is currently in use in the operating system.

$PSVERSIONTABLE

Represents a read-only hash table that displays details about the version of PowerShell that is running in the current session.

$SENDER

Represents the object that generated this event.

$SHELLID

Represents the identifier of the current shell.

$STACKTRACE

Represents a stack trace for the most recent error.

$THIS

In a script block that defines a script property or script method, the $This variable refers to the object that is being extended.

$TRUE

Represents TRUE. You can use this variable to represent TRUE in commands and scripts.

Array

  • Declare an array:

    or

    or

  • Length of the array:

Examples:

Hashtables

  • Declare a hashtable

    or

  • Access a value

Examples:

  • Return keys array:

  • Return

Examples:

Operators

Arithmetic Operators

Operator

Description

Example

+

Addition

A + B

-

Subtraction

A - B

*

Multiplication

A * B

/

Division

B / A

%

Modulus

B % A

Comparison Operators

Operator

Description

Example

eq

equals

A -eq B

ne

not equals

A -ne B

gt

greater than

B -gt A

ge

greater than or equals to

B -ge A

lt

less than

B -lt A

le

less than or equals to

B -le A

Assignment Operators

Operator

Description

Example

=

Simple assignment operator. Assigns values from right side operands to left side operand.

C = A + B

+=

Add AND assignment operator. It adds right operand to the left operand and assign the result to left operand.

C += A

-=

Subtract AND assignment operator. It subtracts right operand from the left operand and assign the result to left operand.

C -= A

Logical Operators

Operator

Description

Example

AND

logical and

(A -AND B)

OR

logical or

(A -OR B)

NOT

logical not

-NOT(A -AND B)

Condition statements

If Else

Switch case

Loops

For

Example:

For each

Example:

While

Example:

Do While

Example:

Write/read on console

Write on console

  • Print <string> on console:

  • Print <string> on console without \n at the end:

Example:

Read input on console

  • Read the value <variable_name> from user:

  • Read the value <variable_name> from user:

    As a value is being entered, asterisks (*) appear on the console in place of the input. When the Enter key is pressed, the value is stored as a SecureString object in the $<variable_name> variable.

Examples:

Common cmdlets

Help

Cmdlet

Description

Get-Help

Help about a command and its parameter

Get-Command

List all the commands

Updates

Cmdlet

Description

Get-HotFix

Get the list of available updates

Get-HotFix -id <id_num>

Check for missing or required KB with id <id_num>

Files and Folder Operations

Cmdlet

Description

New-Item -Path <dir_path> -ItemType Directory

Create a folder

New-Item -Path <file_path> -ItemType File

Create a file

Copy-Item <old_dir> <new_dir>

Copy a folder

Copy-Item <old_dir> -Destination <new_dir>

Copy a folder recursively

Copy-Item <old_file> <new_file>

Copy a file

Copy-Item -Filter <regex> -Path <old_path> -Recurse -Destination <new_path>

Copy all files matching a regex

Remove-Item <dir_file_path>

Delete a file/folder

Remove-Item <dir_path> -Recurse

Delete a folder recursively

Move-Item <old_path> <new_path>

Move a file

Rename-Item <old_path> <new_path>

Rename a file/folder

Test-Path <file_dir_path>

Check file/folder existence

Date and Time Operations

Cmdlet

Description

Get-Date

Print date and time

Get-Date -DisplayHint Date

Print only Date

Get-Date -DisplayHint Time

Print only Time

Set-Date -Date (Get-Date).AddDays(X)

Add X days, where X integer (remove X days if X negative), to current date

Files I/O

Cmdlet

Description

Get-Content <file_path>

Get file content of a file

(Get-Content <file_path>).length

Get number of character in a file

Set-Content <file_path> <new_content>

Set file content

Get-FileHash -Algorithm <hash_type> <file_path>

Get hash of a file (e.g. Get-FileHash -Algorithm SHA256 test.txt)

Download files

Cmdlets Output format

Cmdlet

Description

Format-List

Obtain more information about objects

findstr <string>

Grep results

Format-Table <column_name>

Keep only some columns of a table

Out-File <file_path>

Save the output to file <file_path>

Last updated