Skip to content

Month: June 2024

How to Sign Scripts in PowerShell

PowerShell is a powerful scripting language used for task automation and configuration management across various platforms. While its versatility is one of its greatest strengths, it also introduces potential security risks, particularly when running scripts from untrusted sources. Signing PowerShell scripts is a crucial step in ensuring the integrity and authenticity of the scripts you run, thereby protecting your systems from malicious code. This guide will walk you through the process of signing PowerShell scripts.

Why Sign PowerShell Scripts?

Before diving into the how-to, it’s important to understand why script signing is essential:

  1. Security: Signing scripts helps ensure that the script has not been tampered with and is from a trusted source.
  2. Compliance: Many organisations have policies that require scripts to be signed for auditing and compliance purposes.
  3. Trust: Users can verify the identity of the script author, fostering trust in the script’s legitimacy.
  4. Execution Policy: PowerShell has various execution policies (e.g., AllSigned, RemoteSigned) that control the conditions under which scripts can run. Signing scripts is necessary to meet the requirements of stricter policies.

Prerequisites for Script Signing

Before you can sign a PowerShell script, you need:

  1. A Code Signing Certificate: This can be obtained from a trusted Certificate Authority (CA) or generated internally if your organisation uses a Public Key Infrastructure (PKI).
  2. PowerShell: Ensure you have PowerShell 5.1 or later, as it includes the necessary cmdlets for script signing.

Generating a Self-Signed Certificate

For demonstration purposes, we’ll create a self-signed certificate. In a production environment, it is recommended to use a certificate issued by a trusted CA.

Create a Self-Signed Certificate:

$cert = New-SelfSignedCertificate -CertStoreLocation Cert:\CurrentUser\My -Subject "CN=PowerShell Script Signing"

This command creates a new self-signed certificate in the current user’s certificate store with the subject “PowerShell Script Signing”.

Export the Certificate:

$certPath = "C:\path\to\cert.pfx"
$password = ConvertTo-SecureString -String "YourPassword" -Force -AsPlainText
Export-PfxCertificate -Cert "Cert:\CurrentUser\My\$($cert.Thumbprint)" -FilePath $certPath -Password $password

This exports the certificate to a .pfx file, secured with a password.

Importing the Certificate

To sign scripts, the certificate must be imported into the certificate store:

Import the Certificate:

$password = ConvertTo-SecureString -String "YourPassword" -Force -AsPlainText
Import-PfxCertificate -FilePath "C:\path\to\cert.pfx" -CertStoreLocation Cert:\CurrentUser\My -Password $password

This command imports the certificate into the current user’s personal certificate store.

Signing a PowerShell Script

With the certificate in place, you can now sign your PowerShell script:

Get the Certificate:

$cert = Get-ChildItem -Path Cert:\CurrentUser\My | Where-Object { $_.Subject -eq "CN=PowerShell Script Signing" }

Sign the Script:

Set-AuthenticodeSignature -FilePath "C:\path\to\script.ps1" -Certificate $cert

This command signs the script using the specified certificate.

Verifying the Script Signature

To verify that the script is properly signed:

Check the Signature:

$signature = Get-AuthenticodeSignature -FilePath "C:\path\to\script.ps1"

This command retrieves the signature information for the script. The Status property should indicate that the script is signed and valid.

Execution Policies and Script Signing

PowerShell execution policies govern the conditions under which scripts can run. The relevant policies for script signing are:

  1. AllSigned: All scripts and configuration files must be signed by a trusted publisher.
  2. RemoteSigned: Downloaded scripts must be signed by a trusted publisher.

To set an execution policy:

Set-ExecutionPolicy -ExecutionPolicy AllSigned -Scope CurrentUser

This sets the execution policy to AllSigned for the current user, ensuring that only signed scripts can run.


Signing PowerShell scripts is a crucial step in enhancing the security and integrity of your automation tasks. By following this guide, you can create and use certificates to sign your scripts, thereby ensuring that your scripts are from a trusted source and have not been tampered with. Remember, while self-signed certificates are useful for testing and development, always use certificates from a trusted CA for production environments.

Exploring PowerShell Arrays: A Comprehensive Guide

In programming, an array is a data structure that allows you to store multiple values in a single variable. Arrays are particularly useful for managing collections of related data. In PowerShell, an array can hold items of different types, such as numbers, strings, or even other arrays. PowerShell provides robust capabilities for handling arrays. In this guide we explore the different types of arrays in PowerShell and how to use them.

Types of Arrays in PowerShell

  • Simple Arrays
  • Multidimensional Arrays
  • Jagged Arrays
  • ArrayLists

Let’s go into detail on each type of Array:

Simple Arrays

A simple array in PowerShell is a collection of items of the same or different types. You can create an array using the @() syntax or by simply listing items separated by commas.

# Creating a simple array
$simpleArray = @(1, 2, 3, 4, 5)

# Alternative way
$simpleArray = 1, 2, 3, 4, 5

# Accessing elements
Write-Output $simpleArray[0]  # Outputs: 1

# Adding an element
$simpleArray += 6

# Display the array

Multidimensional Arrays

Multidimensional arrays store data in a grid format, making them ideal for representing matrices or tables. You can create a multidimensional array using the New-Object cmdlet.

# Creating a 2x2 multidimensional array
$multiArray = New-Object 'object[,]' 2,2

# Assigning values
$multiArray[0,0] = 'A'
$multiArray[0,1] = 'B'
$multiArray[1,0] = 'C'
$multiArray[1,1] = 'D'

# Accessing elements
Write-Output $multiArray[0,1]  # Outputs: B

# Display the array

Jagged Arrays

Jagged arrays are arrays of arrays, where each inner array can be of different lengths. This structure provides greater flexibility compared to multidimensional arrays.

# Creating a jagged array
$jaggedArray = @()
$jaggedArray += ,@(1, 2, 3)
$jaggedArray += ,@(4, 5)
$jaggedArray += ,@(6, 7, 8, 9)

# Accessing elements
Write-Output $jaggedArray[0][1]  # Outputs: 2

# Display the array
$jaggedArray | ForEach-Object { $_ }


ArrayLists, part of the .NET framework, provide dynamic arrays that can expand as needed. They offer more flexibility than simple arrays, especially when you need to perform many additions and deletions.

# Creating an ArrayList
$arrayList = [System.Collections.ArrayList]::new()

# Adding elements
$arrayList.Add(1) | Out-Null
$arrayList.Add(2) | Out-Null
$arrayList.Add(3) | Out-Null

# Accessing elements
Write-Output $arrayList[1]  # Outputs: 2

# Removing an element

# Display the array


PowerShell arrays are powerful tools for managing collections of data. Understanding the different types of arrays—simple arrays, multidimensional arrays, jagged arrays, and ArrayLists—can enhance your scripting capabilities. Each type serves different purposes and choosing the right one depends on the specific needs of your task.

Base64 Encoding with PowerShell

Base64 encoding is a method used to encode binary data into an ASCII string format by translating it into a radix-64 representation. It is commonly used in various applications, including encoding email attachments, JSON web tokens, and data storage. This method ensures that the data remains intact without modification during transport.

PowerShell includes built-in support for base64 encoding and decoding. In this guide, we’ll explore how to perform base64 encoding in PowerShell.

What is Base64 Encoding?

Base64 encoding converts binary data into a text format using 64 different ASCII characters. These characters include uppercase letters (A-Z), lowercase letters (a-z), numbers (0-9), and two additional symbols (+ and /). This encoding is particularly useful for encoding data that needs to be safely transmitted over media that are designed to deal with textual data.

PowerShell and Base64 Encoding

PowerShell provides several ways to handle base64 encoding. The most straightforward method involves using the [Convert]::ToBase64String() method for encoding and [Convert]::FromBase64String() for decoding.

Encoding a string to Base64

Here is a PowerShell script to encode the string “” to base64:

# Define the string to encode
$plainText = ""

# Convert the string to a byte array
$bytes = [System.Text.Encoding]::UTF8.GetBytes($plainText)

# Encode the byte array to base64
$base64Encoded = [Convert]::ToBase64String($bytes)

# Display the base64 encoded string
Write-Output $base64Encoded




PowerShell, with its robust scripting capabilities, provides straightforward methods for performing base64 encoding and decoding.

By utilising the [System.Text.Encoding]::UTF8.GetBytes() method to convert a string into a byte array and [Convert]::ToBase64String() to encode it, PowerShell allows for efficient and effective data encoding. This process is particularly useful in scenarios such as data serialisation, web development, and secure data transfer.

Recommended Reading: Base64 Decoding with PowerShell

Base64 Decoding with PowerShell

Base64 encoding is a common technique used to represent binary data in an ASCII string format. It’s often used for encoding data in various contexts, including email via MIME, storing complex data in XML or JSON, and encoding credentials in web development. Decoding base64 data is equally important to retrieve the original information. This guide will teach you the process of decoding a base64 string using PowerShell.

Understanding Base64 Encoding

Base64 encoding converts binary data into an ASCII string using a set of 64 different characters (A-Z, a-z, 0-9, +, /). This makes it suitable for transferring data over media that are designed to deal with text. However, to use the data in its original form, we need to decode it back from the base64 format.

Decoding Base64 in PowerShell

PowerShell provides a straightforward way to decode base64 strings using the [System.Convert]::FromBase64String method.

Decoding a Secret Base64 String

Suppose you have a base64-encoded string and you want to decode it to reveal the original text. Let’s assume the base64 string is U2NyaXB0V2l6YXJkcy5OZXQ=, which decodes to ScriptWizards.Net.

Here’s the PowerShell script to decode this base64 string:

# Define the base64-encoded string
$base64EncodedString = "U2NyaXB0V2l6YXJkcy5OZXQ="

# Convert the base64 string to a byte array
$base64ByteArray = [System.Convert]::FromBase64String($base64EncodedString)

# Convert the byte array back to the original string
$decodedString = [System.Text.Encoding]::UTF8.GetString($base64ByteArray)

# Output the decoded string
Write-Output $decodedString




Defining the Base64-Encoded String: The variable $base64EncodedString holds the base64-encoded string you want to decode.

Converting Base64 String to Byte Array: The [System.Convert]::FromBase64String method converts the base64-encoded string into a byte array. This method takes the base64 string as input and returns an array of bytes.

Converting Byte Array to Original String: The [System.Text.Encoding]::UTF8.GetString method converts the byte array back into the original string. This method takes a byte array as input and returns the corresponding string.

Outputting the Decoded String: Write-Output prints the decoded string to the console.


Decoding base64 strings in PowerShell is a simple process that leverages the .NET framework’s built-in methods for converting base64-encoded data back into its original form. This can be particularly useful for handling encoded data in various applications, such as securely transmitting information or encoding configuration files.

Recommended Reading: Base64 Encoding with PowerShell

Top 10 PowerCLI Commands for VMware vSphere

PowerShell PowerCLI is a powerful command-line tool for managing and automating VMware vSphere environments. Whether you’re a seasoned VMware administrator or a beginner looking to streamline your workflows, PowerCLI offers a robust set of commands to make your tasks easier. Here are the top 10 PowerCLI commands every VMware vSphere administrator should know.


The Connect-VIServer cmdlet establishes a connection to a vCenter Server or an ESXi host.

Connect-VIServer -Server "vcenter_server_name" -User "username" -Password "password"


The Get-VM cmdlet retrieves information about virtual machines (VMs) in the connected vCenter Server or ESXi host.

Get-VM -Name "VMName"


The New-VM cmdlet creates a new virtual machine.

New-VM -Name "VMName" -ResourcePool "ResourcePoolName" -Datastore "DatastoreName" -Template "TemplateName"

This command creates a new VM named VMName using the specified resource pool, datastore, and template.


The Set-VM cmdlet modifies the configuration of a virtual machine.

Set-VM -VM "VMName" -MemoryGB 16 -NumCpu 8

This command configures the VM VMName to have 16 GB of memory and 8 CPUs.


The Start-VM cmdlet powers on a virtual machine.

Start-VM -VM "VMName"


The Stop-VM cmdlet powers off a virtual machine.

Stop-VM -VM "VMName" -Confirm:$false

This command powers off the VM named VMname without prompting for confirmation.


The Remove-VM cmdlet deletes a virtual machine.

Remove-VM -VM "VMName" -DeletePermanently -Confirm:$false

This command permanently deletes the VM named VMName without prompting for confirmation.


The Get-VMHost cmdlet retrieves information about ESXi hosts.

Get-VMHost -Name "ESXiHostName"

This command retrieves information about the ESXi host named ESXiHostName.


The Set-VMHost cmdlet configures settings on an ESXi host.

Set-VMHost -VMHost ESXi01 -State Maintenance

This command puts the ESXi host ESXi01 into maintenance mode.


The Get-Datastore cmdlet retrieves information about datastores.

Get-Datastore -Name "DatastoreName"


These top 10 PowerShell PowerCLI commands provide a solid foundation for managing VMware vSphere environments. From connecting to vCenter Servers to creating and configuring VMs, these commands help streamline administrative tasks and automate routine operations. By mastering these commands, VMware administrators can enhance their productivity and ensure efficient management of their virtual infrastructure.

How to Take a Screenshot with PowerShell

Taking screenshots programmatically can be incredibly useful for automating tasks or creating documentation. PowerShell provides a way to take screenshots using .NET classes. Below is a guide to capturing a screenshot and saving it as a .jpg file.

Capture The Entire Screen

Below is a script that captures the screen and saves it as a .jpg file in C:\Temp\.

# Define the location and file name
$directory = "C:\Temp\"
$filename = "screenshot.jpg"
$filepath = $directory + $filename

# Create a bitmap object
Add-Type -AssemblyName System.Drawing
$bitmap = New-Object System.Drawing.Bitmap([System.Windows.Forms.Screen]::PrimaryScreen.Bounds.Width, [System.Windows.Forms.Screen]::PrimaryScreen.Bounds.Height)

# Create a graphics object from the bitmap
$graphics = [System.Drawing.Graphics]::FromImage($bitmap)

# Capture the screen
$graphics.CopyFromScreen(0, 0, 0, 0, $bitmap.Size)

# Save the bitmap as a .jpg file
$bitmap.Save($filepath, [System.Drawing.Imaging.ImageFormat]::Jpeg)

# Cleanup

Write-Host "Screenshot saved to $filepath"

Capturing a Specific Area

Specify the top-left corner (x, y) and the width and height of the rectangle you want to capture.

$x = 100        # x-coordinate of the top-left corner
$y = 100        # y-coordinate of the top-left corner
$width = 500    # width of the rectangle
$height = 300   # height of the rectangle

Use the coordinates and dimensions defined above in the below script:

$x = 100        # x-coordinate of the top-left corner
$y = 100        # y-coordinate of the top-left corner
$width = 500    # width of the rectangle
$height = 300   # height of the rectangle

# Define the location and file name
$directory = "C:\Temp\"
$filename = "area_screenshot.jpg"
$filepath = $directory + $filename
# Create a bitmap object with specified dimensions
Add-Type -AssemblyName System.Drawing
$bitmap = New-Object System.Drawing.Bitmap($width, $height)
# Create a graphics object from the bitmap
$graphics = [System.Drawing.Graphics]::FromImage($bitmap)
# Capture the specified area of the screen
$graphics.CopyFromScreen($x, $y, 0, 0, $bitmap.Size)
# Save the bitmap as a .jpg file
$bitmap.Save($filepath, [System.Drawing.Imaging.ImageFormat]::Jpeg)
# Cleanup
Write-Host "Screenshot of the specified area saved to $filepath"


PowerShell provides powerful capabilities for capturing screenshots, whether you need the entire screen, or a specific area. By adjusting the script parameters, you can tailor the screenshot capture process to meet your specific needs.

© 2024 - Powered by Coffee & Magic