Skip to content

ScriptWizards.Net Posts

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

Output:

ScriptWizards.Net

Explanation

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.

Conclusion

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.

Connect-VIServer

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"

Get-VM

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

Get-VM -Name "VMName"

New-VM

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.

Set-VM

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.

Start-VM

The Start-VM cmdlet powers on a virtual machine.

Start-VM -VM "VMName"

Stop-VM

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.

Remove-VM

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.

Get-VMHost

The Get-VMHost cmdlet retrieves information about ESXi hosts.

Get-VMHost -Name "ESXiHostName"

This command retrieves information about the ESXi host named ESXiHostName.

Set-VMHost

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.

Get-Datastore

The Get-Datastore cmdlet retrieves information about datastores.

Get-Datastore -Name "DatastoreName"

Conclusion

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
$graphics.Dispose()
$bitmap.Dispose()

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
$graphics.Dispose()
$bitmap.Dispose()
 
Write-Host "Screenshot of the specified area saved to $filepath"

Conclusion

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.

Understanding PowerShell’s Split Function

One of PowerShell’s versatile functions is the -split operator, which allows users to split strings into an array of substrings based on a specified delimiter. This function is particularly useful for parsing and manipulating text data. In this article, we will explore the usage of PowerShell’s -split function through various examples.

Basic Usage

The simplest use of the -split operator is to divide a string by a single character delimiter. For instance, splitting a comma-separated list:

$string = "apple,banana,orange"
$array = $string -split ","
$array

Output:

apple
banana
orange

In this example, the string is split wherever a comma is found, resulting in an array of three elements: apple, banana, and orange.

Splitting with Multiple Delimiters

PowerShell allows the use of regular expressions with the -split operator, enabling more complex splitting criteria. To split a string by both commas and semicolons:

$string = "apple,banana;orange"
$array = $string -split "[,;]"
$array

Output:

apple
banana
orange

Here, the regular expression [,] matches both commas and semicolons, splitting the string accordingly.

Limiting the Number of Substrings

You can also specify the maximum number of substrings to return by providing a second argument to the -split operator. This is useful when you only want to split a string a limited number of times:

$string = "one,two,three,four"
$array = $string -split ",", 3
$array

Output:

one
two
three,four

In this case, the string is split into three parts: one, two, and three,four. The remaining part of the string after the second delimiter is included in the last element.

Splitting with a String Delimiter

Sometimes, the delimiter might be more than a single character. PowerShell handles this seamlessly:

$string = "appleXXbananaXXorange"
$array = $string -split "XX"
$array

Output:

apple
banana
orange

Here, the string XX is used as the delimiter, splitting the string into apple, banana, and orange.

Using Named Parameters

PowerShell also provides a method-like syntax for splitting strings using the Split method of the String object, which can make the code more readable and allows the use of named parameters:

$string = "apple,banana,orange"
$array = $string.Split(',', [StringSplitOptions]::None)
$array

Output:

apple
banana
orange

In this example, the Split method is used with the delimiter , and the StringSplitOptions.None option, which means no special options are applied during the split.

Advanced Example: Splitting and Trimming

Often, you may need to split a string and remove any leading or trailing whitespace from the resulting substrings. This can be achieved using the Trim method in conjunction with the -split operator:

$string = " apple , banana , orange "
$array = ($string -split ",").Trim()
$array

Output:

apple
banana
orange

This ensures that any extraneous whitespace is removed from each element after splitting.

Conclusion

PowerShell’s -split function is a flexible and powerful tool for string manipulation. Whether you are working with simple delimiters or complex regular expressions, this function can handle a wide variety of scenarios. By understanding the -split operator, you can efficiently parse and process text data in your PowerShell scripts.

Analysing HTTP Headers with PowerShell

HTTP headers are essential for client-server communication in web applications, providing metadata about the request or response. Analysing HTTP headers can help in debugging, performance tuning, and understanding the interactions between clients and servers. PowerShell, with its robust scripting capabilities, offers a straightforward way to inspect HTTP headers. This article will guide you through the process of analysing HTTP headers using PowerShell, complete with code examples.

Fetching HTTP Headers

To analyse HTTP headers, we need to make a web request and retrieve the headers from the response. PowerShell’s Invoke-WebRequest cmdlet is perfect for this task.

Here are the steps:

  1. Making a Web Request: Use Invoke-WebRequest to send a request to a specified URL.
  2. Extracting Headers: The response object from Invoke-WebRequest includes a Headers property containing the HTTP headers.
  3. Displaying Headers: Format and display the headers in a readable format.

Code Example

Below is a PowerShell script that fetches and displays HTTP headers from a specified URL:

# Define the URL you want to query
$url = "https://www.scriptwizards.net"

# Make the web request
$response = Invoke-WebRequest -Uri $url -Method Get

# Extract the headers
$headers = $response.Headers

# Display the headers
Write-Host "HTTP Headers for $url`n"
foreach ($header in $headers.GetEnumerator()) {
    Write-Host "$($header.Key): $($header.Value)"
}

Output:

Advanced Usage

You can further customise the script to handle different types of web requests or to save the headers to a file for later analysis.

Handling Different Request Methods

To analyse headers for POST requests or other HTTP methods, change the -Method parameter:

$response = Invoke-WebRequest -Uri $url -Method Post

Saving Headers to a File

To save the headers to a .txt file, you can modify the script as follows:

# Define the URL you want to query
$url = "https://www.scriptwizards.net"
 
# Make the web request
$response = Invoke-WebRequest -Uri $url -Method Get
 
# Extract the headers
$headers = $response.Headers

# Define the file path
$outputFile = "C:\headers.txt"
 
# Open the file for writing
$file = [System.IO.StreamWriter]::new($outputFile)
 
# Write the headers to the file
$file.WriteLine("HTTP Headers for $url`n")
foreach ($header in $headers.GetEnumerator()) {
    Write-Host "$($header.Key): $($header.Value)"
    $file.WriteLine("$($header.Key): $($header.Value)")
}
 
# Close the file
$file.Close()

Conclusion

Analysing HTTP headers with PowerShell is a powerful way to debug and understand web requests. The Invoke-WebRequest cmdlet makes it easy to fetch and display headers, while the flexibility of PowerShell allows for customisation to fit specific needs. Whether you’re a developer, a system administrator, or a network engineer, mastering this technique can significantly enhance your web troubleshooting toolkit.

Random Number Generation in PowerShell

Random number generation is a fundamental aspect of computing, used in various applications such as simulations, cryptography, and gaming. PowerShell, a powerful scripting language and automation framework developed by Microsoft, provides several ways to generate random numbers. This article explores different methods to generate random numbers in PowerShell, along with full code examples.

Using the Get-Random Cmdlet

The most straightforward way to generate random numbers in PowerShell is by using the built-in Get-Random cmdlet. This cmdlet allows for generating random numbers within a specified range or from a collection of items.

Generating a Single Random Number

To generate a single random number, you can simply call Get-Random without any parameters:

# Generate a random number
$randomNumber = Get-Random
Write-Output "Random number: $randomNumber"

Specifying a Range

You can also specify a range for the random number. For example, to generate a random number between 1 and 100:

# Generate a random number between 1 and 100
$randomNumber = Get-Random -Minimum 1 -Maximum 101
Write-Output "Random number between 1 and 100: $randomNumber"

Note that the -Maximum parameter is exclusive, meaning the upper limit is not included in the range.

Selecting Random Elements from an Array

Get-Random can be used to select random elements from an array. For example, to randomly select an element from an array of strings:

# Array of strings
$colors = @("Red", "Green", "Blue", "Yellow", "Purple")

# Select a random color
$randomColor = Get-Random -InputObject $colors
Write-Output "Random color: $randomColor"

Generating Multiple Random Numbers

To generate multiple random numbers, you can use a loop or specify the -Count parameter with Get-Random.

Using a Loop

# Generate 5 random numbers between 1 and 100
for ($i = 0; $i -lt 5; $i++) {
    $randomNumber = Get-Random -Minimum 1 -Maximum 101
    Write-Output "Random number $($i + 1): $randomNumber"
}

Using the -Count Parameter

# Generate 5 random numbers between 1 and 100 using the -Count parameter
$range = 1..100
$randomNumbers = Get-Random -InputObject $range -Count 5
Write-Output "Random numbers: $randomNumbers"

Cryptographic Random Numbers

For cryptographic purposes, where higher security is needed, you can use the System.Security.Cryptography.RNGCryptoServiceProvider class to generate cryptographically secure random numbers.

# Load the required assembly
Add-Type -AssemblyName System.Security

# Create an instance of the RNGCryptoServiceProvider
$cryptoProvider = New-Object System.Security.Cryptography.RNGCryptoServiceProvider

# Buffer to hold the random bytes
$randomBytes = New-Object byte[] 4

# Fill the buffer with random bytes
$cryptoProvider.GetBytes($randomBytes)

# Convert the bytes to an integer
$randomNumber = [BitConverter]::ToUInt32($randomBytes, 0)

Write-Output "Cryptographically secure random number: $randomNumber"

Conclusion

PowerShell provides a versatile and easy-to-use method for generating random numbers through the Get-Random cmdlet, suitable for general purposes. For applications requiring higher security, such as cryptographic operations, leveraging the RNGCryptoServiceProvider class ensures the randomness meets stringent security standards. Whether you need a single random number, multiple random values, or secure random numbers, PowerShell has you covered with simple and effective solutions.

© 2024 ScriptWizards.net - Powered by Coffee & Magic