PowerShell


This draft deletes the entire topic.

expand all collapse all

Examples

  • 7

    By default PowerShell is set up, for security reasons, to only allow signed scripts to execute. Executing the following command will allow you to run unsigned scripts (you must run PowerShell as Administrator to do this).

    Set-ExecutionPolicy RemoteSigned
    

    Another way to run PowerShell scripts is to use Bypass as ExecutionPolicy:

    powershell.exe -ExecutionPolicy Bypass -File "c:\MyScript.ps1"
    

    Temporary work-around for execution policy can be achieved by running the Powershell executable and passing any valid policy as -ExecutionPolicy parameter. The policy is in effect only during process' lifetime, so no administrative access to the registry is needed.

    C:\>powershell -ExecutionPolicy RemoteSigned
    

    There are multiple other policies avaialable, and sites online often encourage you to use Set-ExecutionPolicy Unrestricted. This policy stays in place until changed, and lowers the system security stance. This is not advisable. Use of RemoteSigned is recommended, because it allows locally stored and written code, and requires remotely acquired code be signed with certificate from a trusted root.

    TechNet Documentation:
    Set-ExecutionPolicy
    about_Execution_Policies

  • 4

    In PowerShell there are many ways to achieve the same result, this can be illustrated nicely with the simple, familiar Hello World example:

    Using Write-Host cmdlet

    Write-Host "Hello World"  
    

    Using Write-Output cmdlet

    Write-Output "Hello world"
    

    Using Aliases like echo

    echo "Hello world"
    

    Or, simply, typing "Hello world"

    "Hello world"
    

    All of which will result with the expected console output

    Hello World
    

    It's worth noting however that while these all achieve the goal "write to screen", Write-Host and Write-Output differ in that the former prints only to stdout (i.e. the console screen) whereas the latter can be can be captured in a variable or pipeline.

    echo and write are aliases for Write-Output.

  • 2

    One of the first questions people have when they begin to use PowerShell for scripting is how to manipulate the output from a cmdlet to perform another action.

    The pipeline symbol | is used at the end of a cmdlet to take the data it exports and feed it to the next cmdlet. A simple example is using Select-Object to only show the Name property of a file shown from Get-ChildItem:

    Get-ChildItem | Select-Object Name
    #This may be shortened to:
    gci | Select Name
    

    More advanced usage of the pipeline allows us to pipe the output of a cmdlet into a foreach loop:

    Get-ChildItem | ForEach-Object {
        Copy-Item -Path $_.FullName -destination C:\NewDirectory\ 
    }
    

    Note that the example above uses the $_ symbol - when objects from the pipeline aren't specifically named using | foreach($item in $items) for example, they use this variable.

I am downvoting this example because it is...

Remarks

Windows PowerShell is an automation/configuration management framework from Microsoft built off of the .NET Framework. PowerShell is installed by default on all supported versions of Windows client and server operating systems since Windows 7 / Windows Server 2008 R2. Powershell can be updated at any time by downloading a later version of the Windows Management Framework (WMF). The "Alpha" version of PowerShell 6 is cross-platform (Windows, Linux, and OS X) and needs to be downloaded and installed from this release page.

Additional resources:

Versions

VersionIncluded with WindowsRelease Date
1.0XP / Server 20082006-11-01
2.07 / Server 2008 R22009-11-01
3.08 / Server 20122012-08-01
4.08.1 / Server 2012 R22013-11-01
5.010 / Server 2016 Tech Preview2015-12-16
5.1 Preview10 Anniversary edition / Server 20162016-07-16

Note: v5.1 will be GA when Server 2016 is officially released, but the Preview is part of Win 10 Anniversary edition - MS blog post.

Still have a question about Introduction to PowerShell? Ask Question

Allow scripts stored on your machine to run un-signed

7

By default PowerShell is set up, for security reasons, to only allow signed scripts to execute. Executing the following command will allow you to run unsigned scripts (you must run PowerShell as Administrator to do this).

Set-ExecutionPolicy RemoteSigned

Another way to run PowerShell scripts is to use Bypass as ExecutionPolicy:

powershell.exe -ExecutionPolicy Bypass -File "c:\MyScript.ps1"

Temporary work-around for execution policy can be achieved by running the Powershell executable and passing any valid policy as -ExecutionPolicy parameter. The policy is in effect only during process' lifetime, so no administrative access to the registry is needed.

C:\>powershell -ExecutionPolicy RemoteSigned

There are multiple other policies avaialable, and sites online often encourage you to use Set-ExecutionPolicy Unrestricted. This policy stays in place until changed, and lowers the system security stance. This is not advisable. Use of RemoteSigned is recommended, because it allows locally stored and written code, and requires remotely acquired code be signed with certificate from a trusted root.

TechNet Documentation:
Set-ExecutionPolicy
about_Execution_Policies

Hello World

4

In PowerShell there are many ways to achieve the same result, this can be illustrated nicely with the simple, familiar Hello World example:

Using Write-Host cmdlet

Write-Host "Hello World"  

Using Write-Output cmdlet

Write-Output "Hello world"

Using Aliases like echo

echo "Hello world"

Or, simply, typing "Hello world"

"Hello world"

All of which will result with the expected console output

Hello World

It's worth noting however that while these all achieve the goal "write to screen", Write-Host and Write-Output differ in that the former prints only to stdout (i.e. the console screen) whereas the latter can be can be captured in a variable or pipeline.

echo and write are aliases for Write-Output.

The Pipeline - Using Output from a PowerShell cmdlet

2

One of the first questions people have when they begin to use PowerShell for scripting is how to manipulate the output from a cmdlet to perform another action.

The pipeline symbol | is used at the end of a cmdlet to take the data it exports and feed it to the next cmdlet. A simple example is using Select-Object to only show the Name property of a file shown from Get-ChildItem:

Get-ChildItem | Select-Object Name
#This may be shortened to:
gci | Select Name

More advanced usage of the pipeline allows us to pipe the output of a cmdlet into a foreach loop:

Get-ChildItem | ForEach-Object {
    Copy-Item -Path $_.FullName -destination C:\NewDirectory\ 
}

Note that the example above uses the $_ symbol - when objects from the pipeline aren't specifically named using | foreach($item in $items) for example, they use this variable.

Installation or Setup

1

Windows

PowerShell is included with the Windows Management Framework. Installation and Setup are not required on modern versions of Windows.

Updates to PowerShell can be accomplished by installing a newer version of the Windows Management Framework.

Other Platforms

"Alpah" version of PowerShell 6 can be installed on other platforms. The installation packages are available here.

For example, to install on Ubuntu 16.04, download powershell_6.0.0-alpha.9-1ubuntu1.16.04.1_amd64.deb from the releases page onto the Ubuntu machine.

Run this on terminal:

sudo apt-get install libunwind8 libicu55
sudo dpkg -i powershell_6.0.0-alpha.9-1ubuntu1.16.04.1_amd64.deb

Then just run powershell

Calling .Net Library Methods

0

Static .Net library methods can be called from PowerShell by encapsulating the full class name in third bracket and then calling the method using ::

#calling Path.GetFileName()
C:\> [System.IO.Path]::GetFileName('C:\Windows\explorer.exe')
explorer.exe

Static methods can be called from the class itself, but calling non-static methods requires an instance of the .Net class (an object).

For example, the AddHours method cannot be called from the System.DateTime class itself. It requires an instance of the class :

C:\> [System.DateTime]::AddHours(15)
Method invocation failed because [System.DateTime] does not contain a method named 'AddHours'.
At line:1 char:1
+ [System.DateTime]::AddHours(15)
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (:) [], RuntimeException
    + FullyQualifiedErrorId : MethodNotFound

In this case, we first create an object, for example :

C:\> $Object = [System.DateTime]::Now

Then, we can use methods of that object, even methods which cannot be called directly from the System.DateTime class, like the AddHours method :

C:\> $Object.AddHours(15)

Monday 12 September 2016 01:51:19

Commenting

0

To comment on power scripts by prepending the line using the # (hash) symbol

# this is a comment in powershell
Get-ChildItem

Creating Objects

0

To create object New-Object cmdlet is used

# this creates a DateTime object and keeps its reference in variable called "var"
$var = New-Object System.DateTime

#calling constructor with parameters
$sr = New-Object System.IO.StreamReader -ArgumentList "file path"

In many instances, a new object will be created in order to export data or pass it to another commandlet. This can be done like so:

$newObject = New-Object -TypeName PSObject -Property @{
    ComputerName = "SERVER1"
    Role = "Interface"
    Environment = "Production"
}

Instead of storing it in a variable, you could simply pass it out of your command and into the pipeline. You could also add these objects to a collection and then show the results at the end.

Topic Outline