Skip to content

ScriptWizards.Net Posts

Featured Post

* Script Wizards *

Welcome, young sorcerers of the digital realm, to the sacred halls of ScriptWizards.Net! I am but a humble Script Wizard, a sage of the scripting arts, who has traversed the vast expanses of time and space delving into the arcane mysteries of programming.

Within these digital scrolls, you shall find the eldritch secrets of PowerShell & Python, the ancient languages of automation, woven with threads of magic and logic. Here, amidst the binary winds and the electric hum of servers, I shall impart unto you the wisdom garnered from centuries of study and practice. Fellow Wizard, know you are amongst friends, in this sanctuary of bits and bytes..

Python Bytes

Advanced Disk Management in PowerShell

Managing disks is a fundamental aspect of system administration. Whether provisioning storage, creating partitions, or renaming disks, PowerShell provides a robust suite of commands to streamline these operations. In this article, we’ll explore advanced disk management in PowerShell, covering various functionalities and providing code examples.

Retrieving Disk Information

Before performing disk management tasks, understanding how to retrieve disk information is essential. PowerShell’s Get-Disk cmdlet serves this purpose, fetching details about disks on a computer, including properties such as size, type, and status.

$disks = Get-Disk

foreach ($disk in $disks) {
    Write-Output "Disk $($disk.Number): $($disk.Size) bytes, $($disk.FriendlyName), $($disk.HealthStatus)"
}

Managing Disks

Initialize Disk: Prepare a disk for use by initializing it with the Initialize-Disk cmdlet.

$diskNumber = 1
Initialize-Disk -Number $diskNumber -PartitionStyle GPT

Create Partition: Once initialized, create partitions using the New-Partition cmdlet.

$partitionSize = 10GB
New-Partition -DiskNumber $diskNumber -UseMaximumSize -AssignDriveLetter -IsActive | Format-Volume -FileSystem NTFS -NewFileSystemLabel "Data"

Renaming Disks: To rename a disk, utilize the Set-Disk cmdlet.

$diskNumber = 1
$newName = "NewDiskName"
Set-Disk -Number $diskNumber -FriendlyName $newName

Removing Disks: Removing a disk involves cleaning up partitions and then using the Remove-Disk cmdlet.

$diskNumber = 1
Get-Disk -Number $diskNumber | Clear-Disk -RemoveData -Confirm:$false
Remove-Disk -Number $diskNumber -Confirm:$false

Full Code Example:

This PowerShell script checks for an offline disk, initializes it with a GPT partition style, creates a partition using the maximum available size, formats it with the NTFS file system and the label “Backup Data”, and changes the drive letter to E:

If any error occurs during the process, it will be caught and displayed.

try {
    # Add the disk
    $disk = Get-Disk | Where-Object { $_.OperationalStatus -eq 'Offline' } | Select-Object -First 1
    if (-not $disk) {
        throw "No offline disk found. Please insert a new disk."
    }

    # Initialize the disk
    Initialize-Disk -Number $disk.Number -PartitionStyle GPT

    # Create a partition and format it
    $partition = New-Partition -DiskNumber $disk.Number -UseMaximumSize -IsActive
    Format-Volume -Partition $partition -FileSystem NTFS -NewFileSystemLabel "Backup Data"

    # Change the drive letter
    $volume = Get-Partition -DiskNumber $disk.Number | Get-Volume
    Set-Volume -DriveLetter E -Volume $volume

    Write-Output "Disk added, initialized, partitioned, and drive letter changed to E:\ successfully."
}
catch {
    Write-Error "An error occurred: $_"
}
finally {
    # Cleanup code, if any
}

Conclusion

PowerShell equips system administrators with a comprehensive set of cmdlets for advanced disk management tasks, enabling automation and efficiency. By mastering these cmdlets and incorporating robust error handling, administrators ensure the smooth functioning of their storage infrastructure.

Building a Port Sniffer with PowerShell

In the world of network monitoring and security, the ability to analyse traffic across multiple ports is crucial. Port sniffers are essential tools, enabling administrators to intercept and scrutinize data flow through specific ports.

In this code example, we’ll delve into an advanced PowerShell-based port sniffer, capable of monitoring a range of ports and engaging in bidirectional communication with clients. This enhanced version extends beyond traditional single-port monitoring, empowering users with comprehensive network analysis capabilities while facilitating dynamic interactions with connected clients.

PowerShell Port Sniffer Script:

# Define the range of ports to listen on
$startPort = 8000
$endPort = 8010
 
# Create TCP listener objects for each port in the range
$listeners = @()
try {
    for ($port = $startPort; $port -le $endPort; $port++) {
        $listener = [System.Net.Sockets.TcpListener] $port
        $listener.Start()
        $listeners += $listener
        Write-Host "Port Sniffer listening on port $port..."
    }
 
    # Infinite loop to continuously listen for connections on all ports
    while ($true) {
        foreach ($listener in $listeners) {
            if ($listener.Pending()) {
                $client = $listener.AcceptTcpClient()
                $clientIP = $client.Client.RemoteEndPoint.Address
                $clientPort = $listener.Server.LocalEndpoint.Port  # Corrected line
                Write-Host "Connection from: $clientIP on port $clientPort"
                 
                # Send a response to the client
                $stream = $client.GetStream()
                $response = [System.Text.Encoding]::ASCII.GetBytes("Hello from ScriptWizards.net!")
                $stream.Write($response, 0, $response.Length)
                 
                # Close the client connection
                $client.Close()
            }
        }
    }
}
finally {
    # Close all TCP listeners
    foreach ($listener in $listeners) {
        $listener.Stop()
    }
}

  • We define a range of ports using $startPort and $endPort.
  • In the loop, we create a TCP listener object for each port in the range and start listening on it.
  • Inside the infinite loop, we iterate through each listener and check if there’s any pending connection using $listener.Pending().
  • If a connection is pending, we accept the client connection, retrieve its IP address and connection port, and display it.
  • Then, we send a response back to the client, confirming the connection and providing a greeting message.
  • The TCP listeners are enclosed in a try-finally block. This ensures that even if an exception occurs, the finally block will execute, closing the TCP listeners.
  • In the finally block, all TCP listeners are explicitly stopped using the Stop() method.

Conclusion

In summary, this PowerShell port sniffer script continuously listens for incoming connections on a range of specified ports. When a connection is established, it acknowledges the connection by sending a response to the client. This two-way communication capability enhances the functionality of the port sniffer, making it a versatile tool for network monitoring and interaction.

PowerShell Operators: A Comprehensive Guide

PowerShell, as a versatile scripting language and command-line shell, offers a wide array of operators to perform various tasks, from simple arithmetic operations to complex string manipulations and comparison operations. Understanding these operators is crucial for writing efficient and effective PowerShell scripts. In this guide, we’ll explore the different types of operators in PowerShell with comprehensive code examples.

Arithmetic Operators

Arithmetic operators are used for performing mathematical operations on numeric values. PowerShell supports the following arithmetic operators:

  1. Addition (+): Adds two values.
  2. Subtraction (-): Subtracts the right operand from the left operand.
  3. Multiplication (*): Multiplies two values.
  4. Division (/): Divides the left operand by the right operand.
  5. Modulus (%): Returns the remainder of a division operation.
# Arithmetic Operators Example
$a = 10
$b = 3

# Addition
$result = $a + $b
Write-Host "Addition Result: $result"

# Subtraction
$result = $a - $b
Write-Host "Subtraction Result: $result"

# Multiplication
$result = $a * $b
Write-Host "Multiplication Result: $result"

# Division
$result = $a / $b
Write-Host "Division Result: $result"

# Modulus
$result = $a % $b
Write-Host "Modulus Result: $result"

Assignment Operators

Assignment operators are used to assign values to variables. PowerShell supports various assignment operators, including:

  1. Assignment (=): Assigns the value of the right operand to the variable on the left.
  2. Addition Assignment (+=): Adds the value of the right operand to the variable on the left.
  3. Subtraction Assignment (-=): Subtracts the value of the right operand from the variable on the left.
  4. Multiplication Assignment (*=): Multiplies the variable on the left by the value of the right operand.
  5. Division Assignment (/=): Divides the variable on the left by the value of the right operand.
# Assignment Operators Example
$x = 10

# Addition Assignment
$x += 5
Write-Host "Addition Assignment Result: $x"

# Subtraction Assignment
$x -= 3
Write-Host "Subtraction Assignment Result: $x"

# Multiplication Assignment
$x *= 2
Write-Host "Multiplication Assignment Result: $x"

# Division Assignment
$x /= 4
Write-Host "Division Assignment Result: $x"

Comparison Operators

Comparison operators are used to compare values. PowerShell supports a variety of comparison operators, including:

  1. Equal (-eq): Checks if two values are equal.
  2. Not Equal (-ne): Checks if two values are not equal.
  3. Greater Than (-gt): Checks if the left operand is greater than the right operand.
  4. Less Than (-lt): Checks if the left operand is less than the right operand.
  5. Greater Than or Equal To (-ge): Checks if the left operand is greater than or equal to the right operand.
  6. Less Than or Equal To (-le): Checks if the left operand is less than or equal to the right operand.
# Comparison Operators Example
$num1 = 10
$num2 = 5

# Equal
if ($num1 -eq $num2) {
    Write-Host "Equal: True"
} else {
    Write-Host "Equal: False"
}

# Greater Than
if ($num1 -gt $num2) {
    Write-Host "Greater Than: True"
} else {
    Write-Host "Greater Than: False"
}

# Less Than
if ($num1 -lt $num2) {
    Write-Host "Less Than: True"
} else {
    Write-Host "Less Than: False"
}

Logical Operators

Logical operators are used to combine multiple conditions. PowerShell supports the following logical operators:

  1. And (-and): Returns true if both conditions are true.
  2. Or (-or): Returns true if at least one condition is true.
  3. Not (-not): Negates the result of a condition.
# Logical Operators Example
$condition1 = $true
$condition2 = $false

# And
if ($condition1 -and $condition2) {
    Write-Host "And: True"
} else {
    Write-Host "And: False"
}

# Or
if ($condition1 -or $condition2) {
    Write-Host "Or: True"
} else {
    Write-Host "Or: False"
}

# Not
if (-not $condition1) {
    Write-Host "Not: True"
} else {
    Write-Host "Not: False"
}

String Operators

String operators are used for concatenating and formatting strings. PowerShell supports the following string operators:

  1. Concatenation (+): Concatenates two strings.
  2. Format (-f): Formats a string with specified values.
# String Operators Example
$str1 = "Hello"
$str2 = "World"

# Concatenation
$concatenatedString = $str1 + " " + $str2
Write-Host "Concatenated String: $concatenatedString"

# Format
$formattedString = "{0}, {1}!" -f $str1, $str2
Write-Host "Formatted String: $formattedString"

Understanding PowerShell operators is fundamental for writing efficient scripts and performing various operations. By mastering these operators, you can manipulate data, control program flow, and automate tasks effectively in PowerShell. Experimenting with these operators in different scenarios will enhance your scripting skills and enable you to harness the full power of PowerShell.

Managing Windows Firewall with PowerShell

The Windows Firewall is a crucial component of the Windows operating system, providing security by controlling inbound and outbound network traffic. Managing the Windows Firewall traditionally involves navigating through the graphical user interface (GUI), but with PowerShell, you can automate and streamline firewall management tasks. In this guide, we’ll delve into using PowerShell to manage the Windows Firewall, covering essential concepts & commands.

Understanding Windows Firewall Profiles

Before diving into PowerShell commands, it’s essential to understand Windows Firewall Profiles. There are three firewall profiles:

  1. Domain Profile: Applies when your computer is connected to a domain network.
  2. Private Profile: Applies when your computer is connected to a private network, such as a home or work network.
  3. Public Profile: Applies when your computer is connected to a public network, such as a coffee shop or airport Wi-Fi.

Basic PowerShell Commands for Firewall Management

Let’s start with some basic PowerShell commands to interact with the Windows Firewall:

Enable or Disable the Firewall

# Enable Windows Firewall
Set-NetFirewallProfile -Profile Domain, Public, Private -Enabled True

# Disable Windows Firewall
Set-NetFirewallProfile -Profile Domain, Public, Private -Enabled False

Check Firewall Status

# Get the status of all firewall profiles
Get-NetFirewallProfile | Select Name, Enabled

Add an Inbound Firewall Rule

# Example: Allow inbound traffic on port 80 (HTTP)
New-NetFirewallRule -DisplayName "Allow HTTP" -Direction Inbound -Protocol TCP -LocalPort 80 -Action Allow

Add an Outbound Firewall Rule

# Example: Allow outbound traffic on port 443 (HTTPS)
New-NetFirewallRule -DisplayName "Allow HTTPS" -Direction Outbound -Protocol TCP -LocalPort 443 -Action Allow

Managing Firewall Rules

Now, let’s explore how to manage firewall rules using PowerShell:

View Firewall Rules

# Get all firewall rules
Get-NetFirewallRule

# Filter rules by name or other properties
Get-NetFirewallRule -DisplayName "Allow HTTP"

Disable a Firewall Rule

# Disable a specific firewall rule by display name
Disable-NetFirewallRule -DisplayName "Block FTP"

Remove a Firewall Rule

# Remove a specific firewall rule by display name
Remove-NetFirewallRule -DisplayName "Block FTP"

Export and Import Firewall Rules

# Export firewall rules to a file
Export-NetFirewallRule -Path "C:\FirewallRules.xml"

# Import firewall rules from a file
Import-NetFirewallRule -Path "C:\FirewallRules.xml"

Blocking a Specific Application

Suppose you want to block a specific application, such as a game, from accessing the internet. You can achieve this using PowerShell:

# Block outbound traffic for a specific application
New-NetFirewallRule -DisplayName "Block Game" -Direction Outbound -Program "C:\Path\To\Game.exe" -Action Block

Conclusion

PowerShell provides a powerful interface for managing the Windows Firewall, offering automation and flexibility in configuring firewall settings. By mastering PowerShell commands for firewall management, you can efficiently control network traffic and enhance the security of your Windows environment. With the examples provided in this guide, you can start harnessing the power of PowerShell to effectively manage the Windows Firewall.

Unlocking the Power of Mathematics in PowerShell

While PowerShell is renowned for its prowess in handling system management tasks, its potential in mathematical computations often goes overlooked. Yet, PowerShell boasts a robust set of mathematical operators and functions that can handle a myriad of calculations with ease. In this article, we’ll delve into the realm of mathematics within PowerShell, exploring its capabilities and demonstrating how to perform various calculations using practical examples.

Basic Arithmetic Operations

Let’s start with the fundamentals: addition, subtraction, multiplication, and division. PowerShell supports these operations using familiar mathematical symbols.

# Addition
$sum = 5 + 3
Write-Output "The sum is: $sum"

# Subtraction
$difference = 10 - 4
Write-Output "The difference is: $difference"

# Multiplication
$product = 6 * 2
Write-Output "The product is: $product"

# Division
$quotient = 20 / 5
Write-Output "The quotient is: $quotient"

Exponents and Roots

PowerShell also allows you to perform exponentiation and calculate roots using the ** operator for exponentiation and the sqrt() function for square roots.

# Exponentiation
$power = 2 ** 3 # 2 raised to the power of 3
Write-Output "2 raised to the power of 3 is: $power"

# Square root
$squareRoot = [math]::sqrt(16) # Square root of 16
Write-Output "The square root of 16 is: $squareRoot"

Trigonometric Functions

For more advanced mathematical computations involving angles, PowerShell provides trigonometric functions such as sine, cosine, and tangent.

# Sine function (argument in radians)
$sineValue = [math]::Sin([math]::PI / 6) # Sine of pi/6 (30 degrees)
Write-Output "The sine of 30 degrees is: $sineValue"

# Cosine function (argument in radians)
$cosineValue = [math]::Cos([math]::PI / 3) # Cosine of pi/3 (60 degrees)
Write-Output "The cosine of 60 degrees is: $cosineValue"

# Tangent function (argument in radians)
$tangentValue = [math]::Tan([math]::PI / 4) # Tangent of pi/4 (45 degrees)
Write-Output "The tangent of 45 degrees is: $tangentValue"

Logarithmic Functions

Logarithmic functions are also supported in PowerShell, allowing you to compute logarithms base 10 (log10()) and natural logarithms (ln()).

# Logarithm base 10
$logBase10 = [math]::Log10(100) # Log base 10 of 100
Write-Output "Log base 10 of 100 is: $logBase10"

# Natural logarithm
$naturalLog = [math]::Log([math]::E) # Natural logarithm of Euler's number (e)
Write-Output "Natural logarithm of e is: $naturalLog"

Handling Complex Numbers

While PowerShell primarily deals with real numbers, you can also perform computations involving complex numbers using appropriate libraries or custom functions.

# Define complex numbers
$complex1 = New-Object System.Numerics.Complex 3, 4 # 3 + 4i
$complex2 = New-Object System.Numerics.Complex 2, 5 # 2 + 5i

# Addition of complex numbers
$complexSum = $complex1.Add($complex2)
Write-Output "The sum of $complex1 and $complex2 is: $complexSum"

# Multiplication of complex numbers
$complexProduct = $complex1.Multiply($complex2)
Write-Output "The product of $complex1 and $complex2 is: $complexProduct"

Conclusion

PowerShell’s mathematical capabilities extend far beyond simple arithmetic operations. From trigonometric functions to logarithms and even handling complex numbers, PowerShell equips users with a robust set of tools for diverse mathematical computations. By leveraging these capabilities, users can streamline automation tasks, perform data analysis, and tackle complex mathematical problems with ease. So, the next time you find yourself in need of mathematical muscle within your PowerShell scripts, remember, the power is at your fingertips.

Setting Out of Office on Microsoft Exchange Mailbox with PowerShell

As system and infrastructure engineers, automating tasks is a fundamental aspect of our roles. Setting an out of office (OOO) reply on a Microsoft Exchange mailbox is a common task, especially when users are away from work. PowerShell provides a powerful way to accomplish this task programmatically, ensuring consistency and efficiency across your organisation.

Setting Out of Office with PowerShell

Prerequisites:

  1. Access to Microsoft Exchange server.
  2. Permissions to manage mailboxes.
  3. PowerShell ExchangeOnlineManagement module installed (Exchange Online)
  4. PowerShell ExchangeManagementShell module installed (On-premise Exchange)

Here’s how you can Install the ExchangeOnlineManagement & ExchangeManagementShellmodules:

This command should be run before attempting to use cmdlets like Connect-ExchangeOnline, Set-MailboxAutoReplyConfiguration, and Disconnect-ExchangeOnline. Make sure you have the module installed on your system before running the script. You can install the module using the following command:

# Install Exchange Online Module
Install-Module ExchangeOnlineManagement

# Install Exchange on-premise Module
Install-Module ExchangeManagementShell

Here’s how you can import the ExchangeOnlineManagement & ExchangeManagementShellmodules:

# Import Exchange Online Module
Import-Module ExchangeOnlineManagement

# Import Exchange on-premise Module
Import-Module ExchangeManagementShell

Once the required module is installed & imported, you can proceed with executing the script to manage out of office replies on Exchange mailboxes.

Connect to Exchange Server:

Before we can manage mailboxes, we need to establish a connection to the Exchange server. This can be achieved using the Connect-ExchangeOnline cmdlet or New-PSSession and Import-PSSession for on-premises Exchange servers.

# For Exchange Online
Connect-ExchangeOnline -UserPrincipalName <UPN> -ShowProgress $true

# For on-premises Exchange
$Session = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri http://

Set Out of Office Message:

Once connected to the Exchange server, we can set the out of office message for a specific user. This is done using the Set-MailboxAutoReplyConfiguration cmdlet. Below is an example code snippet to set the out of office message for a user named “John Doe” with a start and end date.

Set-MailboxAutoReplyConfiguration -Identity "John Doe" -AutoReplyState Enabled -InternalMessage "Out of office message for internal senders" -ExternalMessage "Out of office message for external senders" -StartTime "2024-04-25T08:00:00" -EndTime "2024-04-30T17:00:00"

In the above code:

  • -Identity: Specifies the user for whom the out of office message is set.
  • -AutoReplyState: Enables the out of office reply.
  • -InternalMessage: Specifies the message to be sent to internal senders.
  • -ExternalMessage: Specifies the message to be sent to external senders.
  • -StartTime and -EndTime: Define the period during which the out of office message will be active.

Disconnect from Exchange Server:

Once the task is complete, it’s good practice to disconnect from the Exchange server to release resources.

# For Exchange Online
Disconnect-ExchangeOnline -Confirm:$false

# For on-premises Exchange
Remove-PSSession $Session

Full Code Examples

Here is a full PowerShell script for Microsoft Exchange Online with error handling utilising the code from above:

Import-Module ExchangeOnlineManagement

# Connect to Exchange Online
try {
    Connect-ExchangeOnline -UserPrincipalName <UPN> -ShowProgress $true -ErrorAction Stop
}
catch {
    Write-Error "Failed to connect to Exchange Online: $_"
    exit
}

# Set Out of Office Message
try {
    Set-MailboxAutoReplyConfiguration -Identity "John Doe" -AutoReplyState Enabled -InternalMessage "Out of office message for internal senders" -ExternalMessage "Out of office message for external senders" -StartTime "2024-04-25T08:00:00" -EndTime "2024-04-30T17:00:00" -ErrorAction Stop
}
catch {
    Write-Error "Failed to set out of office message: $_"
    Disconnect-ExchangeOnline -Confirm:$false
    exit
}

# Disconnect from Exchange Online
try {
    Disconnect-ExchangeOnline -Confirm:$false
}
catch {
    Write-Error "Failed to disconnect from Exchange Online: $_"
    exit
}

Here is a full PowerShell script for Microsoft Exchange on-premise with error handling utilising the code from above:

Import-Module ExchangeManagementShell

# Connect to Exchange Server
try {
    $Session = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri http://your_exchange_server_uri/PowerShell/ -Authentication Kerberos
    Import-PSSession $Session -DisableNameChecking
}
catch {
    Write-Error "Failed to connect to Exchange Server: $_"
    exit
}

# Set Out of Office Message
try {
    Set-MailboxAutoReplyConfiguration -Identity "John Doe" -AutoReplyState Enabled -InternalMessage "Out of office message for internal senders" -ExternalMessage "Out of office message for external senders" -StartTime "2024-04-25T08:00:00" -EndTime "2024-04-30T17:00:00" -ErrorAction Stop
}
catch {
    Write-Error "Failed to set out of office message: $_"
    Remove-PSSession $Session
    exit
}

# Disconnect from Exchange Server
try {
    Remove-PSSession $Session
}
catch {
    Write-Error "Failed to disconnect from Exchange Server: $_"
    exit
}

Conclusion

Utilising PowerShell for automating out of office replies on Microsoft Exchange mailboxes offers a streamlined approach for administrators. By integrating robust error handling into the script, system and infrastructure engineers can ensure reliable execution of mailbox management tasks. This automation not only saves time but also promotes consistency and accuracy in managing out of office messages across the organisation’s Exchange environment.

© 2024 ScriptWizards.net - Powered by Coffee & Magic