tutorials|March 03, 2021|3 min read

Explore useful Automation Techniques with Powershell on Windows

TL;DR

Handy PowerShell snippets for Windows automation including getting script directory, script name, environment variables, and other common tasks.

Explore useful Automation Techniques with Powershell on Windows

Introduction

We will list few interesting automation techniques with powershell.

Get the directory of your current script

$script_path = dir "$($myInvocation.MyCommand.Definition)"
$script_path = $script_path.DirectoryName

Get the name of your script

$script_name = $MyInvocation.MyCommand.Name

Writing something to console

Write-Output "================================================"
Write-Output ""
Write-Output "  My Fancy Banner"
Write-Output ""
Write-Output "  - Installs All Dependencies"
Write-Output ""
Write-Output "  To run silently add -Silent"
Write-Output "================================================"
Write-Output ""

Import Modules

If you have written powershell script in another file, you can include that with Import-Module

$script_path = dir "$($myInvocation.MyCommand.Definition)"
$script_path = $script_path.DirectoryName

Import-Module $script_path\Modules\my-module.psm1

Check user Admin or not

First we can write functions

function Get-IsAdministrator
{
    $Identity = [System.Security.Principal.WindowsIdentity]::GetCurrent()
    $Principal = New-Object System.Security.Principal.WindowsPrincipal($Identity)
    $Principal.IsInRole([System.Security.Principal.WindowsBuiltInRole]::Administrator)
}


function Get-IsUacEnabled
{
    (Get-ItemProperty HKLM:\Software\Microsoft\Windows\CurrentVersion\Policies\System).EnableLua -ne 0
}

Then use them,

If (!(Get-IsAdministrator)) {
  ...
}

# check for UAC enabled user
If (Get-IsUacEnabled) {
  ...
}

Run powershell as Administrator, if not

If (!(Get-IsAdministrator)) {
    If (Get-IsUacEnabled) {
        # We are not running "as Administrator" - so relaunch as administrator
        # Create a new process object that starts PowerShell
        $newProcess = new-object System.Diagnostics.ProcessStartInfo "PowerShell";

        # Specify the current script path and name as a parameter
        $newProcess.Arguments = $myInvocation.MyCommand.Definition

        # Specify the current working directory
        $newProcess.WorkingDirectory = "$script_path"

        # Indicate that the process should be elevated
        $newProcess.Verb = "runas";

        # Start the new process
        [System.Diagnostics.Process]::Start($newProcess);

        # Exit from the current, unelevated, process
        Exit
    } Else {
        Throw "You must be administrator to run this script"
    }
}

Create File or Directory

New-Item "Dir_Name" -ItemType Directory -Force

Delete File or Directory

Remove-Item "my_file"

Delete Directory recursively

Remove-Item "folder" -Force -Recurse

Detecting 32-bit ot 64-bit architecture

If ([System.IntPtr]::Size -ne 4) {
    Write-Output "Detected 64bit Architecture..."

    ...
} Else {
    Write-Output "Detected 32bit Architecture"

Check for file existence

Test-Path "file_path"

# Example

If (Test-Path "file_path") {
    # Found file
    Write-Output " - File Found . . ."
}

Download File from URL

DownloadFileWithProgress $url $file

Where url is the actual http url from where you want to download file. And file is the destination file where you want to write.

Start a process with command options

Start-Process $file -ArgumentList <command options>

Example of installing NSIS,

# Downloading nsis
$file = "nsis.exe"
$url = "URL for NSIS"
DownloadFileWithProgress $url $file

Start-Process $file -ArgumentList '/S' -Wait -NoNewWindow -PassThru

Updating System variable PATH

Temporarily adding a path to PATH variable

To temporarily add a path to PATH variable,

$env:Path += ";my_path"

Note: Do not forgot to use +. Else, it will overwrite previous path

Add a path to PATH permanently

$env:Path += ";my_path"
[Environment]::SetEnvironmentVariable
     ("Path", $env:Path, [System.EnvironmentVariableTarget]::Machine)

Add path when its not added

We will first get PATH variable, and check if our desired value is there. If its not there, we will add that.

$Path = (Get-ItemProperty -Path 'Registry::HKEY_LOCAL_MACHINE\System\CurrentControlSet\Control\Session Manager\Environment' -Name PATH).Path

$my_value = "xyz"

If (!($Path.ToLower().Contains("$my_value".ToLower()))) {
    $newPath  = "$my_value"
    Set-ItemProperty -Path 'Registry::HKEY_LOCAL_MACHINE\System\CurrentControlSet\Control\Session Manager\Environment' -Name PATH -Value $newPath
    $env:Path = $newPath
}

Get folder items and get its count

if ( (Get-ChildItem "my_folder | Measure-Object).Count -eq 0 ) {
        # folder empty
  ...
}

Copy and Move Files/Folders

For single file

Copy-Item "my_file" "des_dir" -Force

Move-Item "my_file" "des_dir"" -Force

For multiple files using *

Copy-Item "my_folder\*.dll" "dest_folder" -Force

Move-Item "my_folder\*.dll" "dest_folder" -Force

Replace File Content Dyamically

Example, your file path is: /my/path/file.txt

And, you want to replace STR_TO_REPLACE string with target string TARGET_STRING

(Get-Content -path /my/path/file.txt -Raw) -replace 'STR_TO_REPLACE', 'TARGET_STRING' | Set-Content -Path /my/path/file.txt

And, if you have your value set in some environment variable name: MY_ENV_VAR,

(Get-Content -path /my/path/file.txt -Raw) -replace 'BRANCH_NOT_SET', $env:MY_ENV_VAR | Set-Content -Path /my/path/file.txt

Related Posts

How to Copy Local Docker Image to Another Host Without Repository and Load

How to Copy Local Docker Image to Another Host Without Repository and Load

Introduction Consider a scenario where you are building a docker image on your…

How to install Perl from Command Line for Automation on Windows and Dockerfile

How to install Perl from Command Line for Automation on Windows and Dockerfile

Introduction Often in automation, we need to install stuff from command line…

How to Install packages from command line and Dockerfile with Chocolatey

How to Install packages from command line and Dockerfile with Chocolatey

Introduction We will introduce a Package Manager for Windows: . In automations…

How to connect to a running mysql service on host from a docker container on same host

How to connect to a running mysql service on host from a docker container on same host

Introduction I have a host running mysql (not on a container). I have to run an…

Docker: unauthorized: incorrect username or password.

Docker: unauthorized: incorrect username or password.

While running docker commands with some images, I started getting error: The…

Docker image for Drupal 7, and Php extension MongoDB installed.

Docker image for Drupal 7, and Php extension MongoDB installed.

You have drupal 7 image from docker hub, and want to connect tomongo db via php…

Latest Posts

Claude Code Skills — Build a Better Engineering Workflow with AI-Powered Code Reviews, Security Scans, and More

Claude Code Skills — Build a Better Engineering Workflow with AI-Powered Code Reviews, Security Scans, and More

Most developers use Claude Code like a search engine — ask a question, get an…

Building an AI Voicebot for Visitor Check-In — A Practical Guide to Handling the Messy Parts

Building an AI Voicebot for Visitor Check-In — A Practical Guide to Handling the Messy Parts

Every office lobby has the same problem: a visitor walks in, nobody’s at the…

Server Security Best Practices — Complete Hardening Guide for Production Systems

Server Security Best Practices — Complete Hardening Guide for Production Systems

Every breach post-mortem tells the same story: an unpatched service, a…

Staff Engineer Study Plan for MAANG Interviews — The Complete 12-Week Roadmap

Staff Engineer Study Plan for MAANG Interviews — The Complete 12-Week Roadmap

If you’re a Senior Engineer (L5) preparing for Staff (L6+) roles at MAANG…

XSS and CSRF Explained — The Complete Guide with Real Attack Examples and Defenses

XSS and CSRF Explained — The Complete Guide with Real Attack Examples and Defenses

XSS and CSRF have been in the OWASP Top 10 for over a decade. They’re among the…

OWASP Top 10 (2021) — Every Vulnerability Explained with Code

OWASP Top 10 (2021) — Every Vulnerability Explained with Code

The OWASP Top 10 is the industry standard for web application security risks. If…