Scripting

    What are PowerShell Scripts?

    PowerShell scripts are lists of commands executed by PowerShell scripting engine. They are text documents with instructions written using PowerShell scripting language. They are used to automate computer processes. All PowerShell scripts are saved as .PS1 extension.

    How to run scripts?

    Using PowerShell: To run a script which is saved at C:\Temp\Script1.ps1, just type the full path C:\Temp\Script1.ps1 or if in the same directory, .\Script1.ps1

    Windows Explorer: Right click the script file and select Run with PowerShell

    Execution Policy

    To prevent the execution of malicious scripts, PowerShell enforces an execution policy. By default, the execution policy is set to Restricted, which means that PowerShell scripts will not run. You can determine the current execution policy by using the following cmdlet:

    Get-ExecutionPolicy

    The execution policies you can use are:

    • Restricted – Scripts won’t run.
    • RemoteSigned – Scripts created locally will run, but those downloaded from the Internet will not (unless they are digitally signed by a trusted publisher).
    • AllSigned – Scripts will run only if a trusted publisher has signed them.
    • Unrestricted – Scripts will run regardless of where they have come from and whether they are signed.

    You can set PowerShell’s execution policy by using the following cmdlet:

    Set-ExecutionPolicy <policy name>

    Scripting Tools:

    PowerShell ISE:

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

    Visual Studio Code:

    Visual Studio Code is a source-code editor made by Microsoft for Windows, Linux and macOS. Features include support for debugging, syntax highlighting, intelligent code completion, snippets, code refactoring, and embedded Git. This tool is very popular now a days. VS Code can be downloaded from https://code.visualstudio.com/download

    You can also use any text editor like notepad, notepad++ etc. to create PowerShell scripts.

     

    PowerShell is a powerful scripting language and task automation framework that is built into Windows operating systems. It is based on the .NET framework and provides a versatile command-line interface to interact with the operating system, as well as perform complex operations and create scripts to automate tasks.

    Here's a brief introduction to PowerShell scripting:

    Variables: PowerShell variables are prefixed with the dollar symbol ($). You can assign a value to a variable using the equal sign (=).

    $name = "John" 
    $age = 25

    Data Types: PowerShell supports a variety of data types, including strings, integers, floats, booleans, and arrays.

    [string]$name = "John" 
    [int]$age = 25

    Control Structures: PowerShell supports common programming control structures, such as if/else, switch, for, and while.

    # If/else statement 
    if ($age -gt 18) 
    { 
        Write-Host "You are an adult." 
    } 
    else 
    { 
        Write-Host "You are a minor." 
    } 
    
    # Switch statement 
    switch ($age) 
    { 
        {$_ -lt 18} { "You are a minor." } 
        {$_ -ge 18} { "You are an adult." } 
    } 
    
    # For loop 
    for ($i = 0; $i -lt 10; $i++) 
    { 
        Write-Host $i 
    } 
    
    # While loop 
    $i = 0 
    while ($i -lt 10) 
    { 
        Write-Host $i $i++ 
    }

    Functions: You can create reusable code by defining functions in PowerShell.

    function Get-Greeting 
    {
    param( [string]$name )
    return "Hello, $name!"
    }
    $greeting = Get-Greeting -name "John"
    Write-Host $greeting



    Working with Files and Folders: PowerShell provides cmdlets (command-let) to work with files and folders, such as Get-ChildItem, New-Item, Remove-Item, and Copy-Item.

    # List all items in the current directory 
    Get-ChildItem 
    
    # Create a new folder 
    New-Item -Path "NewFolder" -ItemType "Directory" 
    
    # Remove a folder 
    Remove-Item -Path "NewFolder" -Recurse -Force 
    
    # Copy a file 
    Copy-Item -Path "source.txt" -Destination "destination.txt"

    Error Handling: PowerShell supports error handling using try/catch/finally blocks.

    • try { # Code that may throw an error } 
      
      catch { # Code to execute when an error is caught } 
      
      finally { # Code to execute regardless of whether an error occurred }
    • Importing and Exporting Data: PowerShell supports importing and exporting data in various formats, such as CSV, JSON, and XML.
    # Import a CSV file 
    $data = Import-Csv -Path "data.csv" 
    
    # Export data to a JSON file 
    $data | ConvertTo-Json | Set-Content -Path "data.json"

    These are just a few examples of what you can do with PowerShell scripting. There is a wealth of cmdlets and features to explore that can make your scripts even more powerful and flexible.