PowerShell


This draft deletes the entire topic.

Examples

  • 18

    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"
    

    Or from within your existing PowerShell console or ISE session by running:

     Set-ExecutionPolicy Bypass Process
    

    A temporary work-around for execution policy can also 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 available, 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.

    Beware also that the Execution Policy may be enforced by Group Policy, so even if the policy is changed to Unrestricted system wide, Group Policy may revert that setting at its next enforcement interval (typically 15 minutes).

    TechNet Documentation:
    Set-ExecutionPolicy
    about_Execution_Policies

  • 9

    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 produces an object which can be captured in a variable or pipeline.

    echo and write are aliases for Write-Output.

  • 3

    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 $_ automatic variable. $_ is the short alias of $PSItem which is an automatic variable which contains the current item in the pipeline.

  • 1

    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
    
  • 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

    "Alpha" 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

  • 0

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

    # This is a comment in powershell
    Get-ChildItem
    

    You can also have multi-line comments using <# and #> at the beginning and end of the comment respectively.

    <#
    This is a 
    multi-line
    comment
    #>
    Get-ChildItem
    
  • 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.

Please consider making a request to improve this example.

Remarks

Windows PowerShell is a shell and scripting component of the Windows Management Framework, an automation/configuration management framework from Microsoft built on 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 WindowsNotesRelease 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.110 Anniversary edition / Server 20162017-01-27
Still have a question about Getting started with PowerShell? Ask Question

Topic Outline