Wednesday, November 29, 2017

How To Create PowerShell Function


Overview

In this post we will walk-through the steps as to how to PowerShell functions are helpful in saving time when you have repetitive task(s) to be executed.

Applies To



  • Tested on Windows 10, Windows 2008 R2 and Windows 2012.

  • Pre-Requisites



  • Launch PowerShell Command Console or PowerShell ISE.
  • To run this script, Execution Policy should be set to either of these “AllSigned” or “RemoteSigned” or “Unrestricted”, you can get current execution policy by running the command; “Get-ExecutionPolicy”. Each Policy type and its purpose is shown in the below table.

  • Policy Type Purpose
    Restricted No scripts can be run. Windows PowerShell can be used only in interactive mode.
    AllSigned Only scripts signed by a trusted publisher can be run.
    RemoteSigned Downloaded scripts must be signed by a trusted publisher before they can be run.
    Unrestricted No restrictions; all Windows PowerShell scripts can be run.

    PowerShell Script – Function

    This PowerShell script call function without any function arguments / parameters.

    Code Snippet


    Function Call_Function_Write_Welcome_Message
    {
        Clear-Host
        Write-Host "`nListing Function information that was created`n"
        dir function: | Where-Object Name -Like "Call_function_Write_Welcome_Message"
        Write-Host "`n__________________________________________"
        Write-Host "`nPurpose of Function printing Hello Message"
        Write-Host "__________________________________________"
        Write-Host "`nHello – PowerShell Script"
        [console]::beep(500,300)
    }
    

    Call Function

    To invoke /call the function, simply call the function name from the PowerShell CLI or PowerShell ISE.


    Call_Function_Write_Welcome_Message

    PowerShell Output

    When the function is called / executed; below output will be displayed.







    SlideShare Info

    A step by step guide with screenshot is uploaded to Slideshare.


    No comments:

    Post a Comment