ENJOY some tunes while browsing :)

Aaron Voborny

music & tech guy

Matrix-Style Collapsible Code List

Powershell Scripts (click each one to expand/collapse)

Restore Active Directory

+

# ------------------Script by Aaron Voborny---------------------------
# Automation Script that Restores a departmental OU from a backup file

# Check for the existence of an Active Directory Organizational Unit (OU) named "Finance"
$ouExists = Get-ADOrganizationalUnit -Filter { Name -eq "Finance" } -ErrorAction SilentlyContinue

if ($ouExists) {
    # Check if the OU is protected from accidental deletion
    $ouProtected = $ouExists.ProtectedFromAccidentalDeletion

    # Ensures the ProtectedFromAccidentalDeletion option is set to FALSE before running the script
    $ouExists | Set-ADOrganizationalUnit -ProtectedFromAccidentalDeletion:$false
    Write-Host "Accidental Deletion Protection has been temporarily deactivated."

    try {
        # Delete the OU
        Remove-ADOrganizationalUnit -Identity $ouExists -Recursive -Confirm:$false
        Write-Host "The 'Finance' OU already existed and has been deleted."
    } catch {
        Write-Host "Error occurred while deleting the 'Finance' OU: $_"
    }
} else {
    Write-Host "The 'Finance' OU does not exist."
}

# Create an OU named "Finance"
New-ADOrganizationalUnit -Name "Finance" -Path "DC=consultingfirm,DC=com"
Write-Host "The 'Finance' OU has been created."

# Import financePersonnel.csv into Active Directory domain and into the finance OU
Import-Csv -Path "$PSScriptRoot\financePersonnel.csv" | ForEach-Object {
    New-ADUser -Name "$($_.'First_Name') $($_.'Last_Name')" -GivenName $_.'First_Name' -Surname $_.'Last_Name' `
               -DisplayName "$($_.'First_Name') $($_.'Last_Name')" -SamAccountName $_.'First_Name' -UserPrincipalName "$($_.'First_Name')$($_.'Last_Name')@consultingfirm.com" `
               -PostalCode $_.'PostalCode' -OfficePhone $_.'OfficePhone' -MobilePhone $_.'MobilePhone' -Path "OU=Finance,DC=consultingfirm,DC=com" -PassThru
}

# Ensures the ProtectedFromAccidentalDeletion option is set to TRUE after running the script
$ouExists | Set-ADOrganizationalUnit -ProtectedFromAccidentalDeletion:$true
Write-Host "Accidental Deletion Protection has been reactivated."

# Generate output file for the submission
Get-ADUser -Filter * -SearchBase "ou=Finance,dc=consultingfirm,dc=com" -Properties DisplayName,PostalCode,OfficePhone,MobilePhone > $PSScriptRoot\AdResults.txt
Write-Host "Output file has been generated for submission."
                

Restore a SQL Database

+

# ------------------Script by Aaron Voborny---------------------------
# Automation Script that Restores a SQL Database from a backup file

try {
    # Check for the existence of a database named ClientDB
    $sqlServer = ".\SQLEXPRESS"
    $databaseName = "ClientDB"

    $sqlQuery = "SELECT COUNT(*) FROM sys.databases WHERE name = '$databaseName'"
    $databaseExistsResult = Invoke-Sqlcmd -Query $sqlQuery -ServerInstance $sqlServer
    $databaseExists = $databaseExistsResult | Select-Object -ExpandProperty Column1

    if ($databaseExists -ne $null -and $databaseExists -gt 0) {
        try {
            # Database exists, delete it
            $sqlQuery = "DROP DATABASE $databaseName"
            Invoke-Sqlcmd -Query $sqlQuery -ServerInstance $sqlServer
            Write-Host "The '$databaseName' database already existed and has been deleted."
        } catch {
            Write-Host "Error occurred while deleting the '$databaseName' database: $_"
        }
    } else {
        Write-Host "The '$databaseName' database does not exist."
    }

    # Create a new database named "ClientDB"
    $sqlQuery = "CREATE DATABASE $databaseName"
    Invoke-Sqlcmd -Query $sqlQuery -ServerInstance $sqlServer
    Write-Host "The '$databaseName' database has been created."

    # create the database and import records
    $servername = ".\SQLEXPRESS"
    $databasename = "ClientDB"
    Invoke-Sqlcmd -ServerInstance $servername -InputFile $PSScriptRoot\DBCreate.sql -Verbose
    Invoke-Sqlcmd -ServerInstance $servername -Database $databasename -InputFile $PSScriptRoot\Client_A_Contacts.sql -Verbose
    Invoke-Sqlcmd -ServerInstance $servername -Database $databasename -InputFile $PSScriptRoot\import.sql -Variable mypath="'$PSScriptroot\NewClientData.csv'" -Verbose

    # Generate output file for submission
    Invoke-Sqlcmd -Database $databaseName -ServerInstance $sqlServer -Query "SELECT * FROM dbo.Client_A_Contacts" > "$PSScriptRoot\SqlResults.txt"
} catch {
    Write-Host "Error: $_"
}
                

Schedule Users for Automatic Deletion

+

### This is my current version.  It took 3 revisions to get it to this point.

# the first 3 lines are to set the time and date in which you want to deactivate the account.  Enter in the hours in military time, minutes, seconds,
# and choose the month and day.

$time = "HH:MM:SS"
$date = "YYYY-MM-DD"
$datetime = "$date $time"

# the next 2 lines are for entering the username and running the command against that username.  This should be an account in your AD environment.

$username = "John.Doe"
$command = "Disable-LocalUser -Name $username"

# This next part is where the action happens.  We are using the 'New-ScheduledTaskAction' cmdlet to create an action that runs the "powershell.exe"
# command with the '$command' argument.  The '$command' argument contains the Disable-LocalUser command that was passed as a string.
# The 'New-ScheduledTaskAction' cmdlet returns an array of 'CimInstance' objects which is the expected type for the '-Action' parameter of the
# 'Register-ScheduledTask' cmdlet.

$action = New-ScheduledTaskAction -Execute "powershell.exe" -Argument $command

Register-ScheduledTask -TaskName "Deactivate John Doe" -Trigger (New-ScheduledTaskTrigger -Once -At $datetime) -User "Adminaccounthere" -Action $action
                

Automate Repetitive Tasks in Azure

+

██████╗░██╗░░░██╗███████╗███████╗███╗░░██╗███████╗██████╗░██████╗░
██╔══██╗██║░░░██║██╔════╝██╔════╝████╗░██║██╔════╝██╔══██╗██╔══██╗
██████╦╝██║░░░██║█████╗░░█████╗░░██╔██╗██║█████╗░░██████╔╝██║░░██║
██╔══██╗██║░░░██║██╔══╝░░██╔══╝░░██║╚████║██╔══╝░░██╔══██╗██║░░██║
██████╦╝╚██████╔╝██║░░░░░██║░░░░░██║░╚███║███████╗██║░░██║██████╔╝
╚═════╝░░╚═════╝░╚═╝░░░░░╚═╝░░░░░╚═╝░░╚══╝╚══════╝╚═╝░░╚═╝╚═════╝░

# Here is an Azure PowerShell script that automates some common repetitive tasks and workflows:

# Connect to Azure
Connect-AzureRmAccount

# Create a new resource group
New-AzureRmResourceGroup -Name "MyResourceGroup" -Location "East US"

# Create a new virtual machine
New-AzureRmVm -ResourceGroupName "MyResourceGroup" -Name "MyVM" -Location "East US" -ImageName "WindowsServer" -Size "Standard_DS1"

# Create a new virtual network
New-AzureRmVirtualNetwork -Name "MyVirtualNetwork" -ResourceGroupName "MyResourceGroup" -Location "East US" -AddressPrefix 10.0.0.0/16

# Create a new network interface
New-AzureRmNetworkInterface -Name "MyNetworkInterface" -ResourceGroupName "MyResourceGroup" -Location "East US" -VirtualNetworkName "MyVirtualNetwork" -SubnetName "default"

# Attach the network interface to the virtual machine
Add-AzureRmNetworkInterface -NetworkInterfaceName "MyNetworkInterface" -ResourceGroupName "MyResourceGroup" -VMName "MyVM"

# Create a new security group
New-AzureRmNetworkSecurityGroup -Name "MySecurityGroup" -ResourceGroupName "MyResourceGroup" -Location "East US"

# Create a new security rule
New-AzureRmNetworkSecurityRuleConfig -Name "MySecurityRule" -Protocol "Tcp" -Direction "Inbound" -Priority "100" -SourceAddressPrefix "*" -SourcePortRange "*" -DestinationAddressPrefix "*" -DestinationPortRange "80" -Access "Allow"

# Add the security rule to the security group
Add-AzureRmNetworkSecurityRuleConfig -NetworkSecurityGroupName "MySecurityGroup" -ResourceGroupName "MyResourceGroup" -SecurityRule $MySecurityRule

# Assign the security group to the network interface
Set-AzureRmNetworkInterface -Name "MyNetworkInterface" -ResourceGroupName "MyResourceGroup" -NetworkSecurityGroupId $MySecurityGroup.Id

# Create an Azure policy
$policy = New-AzureRmPolicyDefinition -Name "MyPolicy" -PolicyRule "{`"if`":{`"allOf`":[{`"field`":`"type`",`"equals`":`"Microsoft.Compute/virtualMachines`"},{`"field`":`"Microsoft.Compute/virtualMachines/sku.name`",`"equals`":`"Standard_DS1_v2`"}]},`"then`":{`"effect`":`"deny`"}}"

# Assign the policy to the resource group
New-AzureRmPolicyAssignment -Name "MyPolicyAssignment" -Scope "/subscriptions/yourSubscriptionId/resourceGroups/MyResourceGroup" -PolicyDefinition $policy

# This is just an example and may need to be modified or extended to meet the specific requirements of your organization. 
# Also, some of the parameters used in the script, like the location, should be changed to match your environment.

# It's also worth noting that this script is for demonstration purposes only and should not be used in a production 
# environment without thorough testing and validation. Additionally, it's important to follow best practices for securing 
# your scripts, such as storing them in a secure location and ensuring they are kept up to date.

# As a cloud security engineer, you can use Azure PowerShell in combination with other Azure services to automate your 
# security workflows, you can also use Azure PowerShell to automate the collection of security-related information from 
# your resources and environments, generating reports and alerts, and also automating the remediation of security 
# vulnerabilities.

# In general, Azure PowerShell can be a powerful tool for automating and managing Azure resources, including security-related
# tasks, and can help cloud security engineers to be more efficient, save time and reduce the possibility of human errors.

                

Create Alert Rules in Azure

+


██████╗░██╗░░░██╗███████╗███████╗███╗░░██╗███████╗██████╗░██████╗░
██╔══██╗██║░░░██║██╔════╝██╔════╝████╗░██║██╔════╝██╔══██╗██╔══██╗
██████╦╝██║░░░██║█████╗░░█████╗░░██╔██╗██║█████╗░░██████╔╝██║░░██║
██╔══██╗██║░░░██║██╔══╝░░██╔══╝░░██║╚████║██╔══╝░░██╔══██╗██║░░██║
██████╦╝╚██████╔╝██║░░░░░██║░░░░░██║░╚███║███████╗██║░░██║██████╔╝
╚═════╝░░╚═════╝░╚═╝░░░░░╚═╝░░░░░╚═╝░░╚══╝╚══════╝╚═╝░░╚═╝╚═════╝░

# Here is a script that monitors and sends alerts out for some of the most critical security-related events
# that can occur on a network or system:

# Connect to Azure
Connect-AzureRmAccount

# Create a new Log Analytics workspace
$logAnalyticsWorkspace = New-AzureRmLogAnalyticsWorkspace -ResourceGroupName "MyResourceGroup" -WorkspaceName "MyLogAnalyticsWorkspace" -Location "East US"

# Create a new Log Analytics solution
New-AzureRmLASolution -Workspace $logAnalyticsWorkspace -Name "Security" -SolutionTemplate "Security"

# Get the Log Analytics workspace ID
$workspaceId = (Get-AzureRmLogAnalyticsWorkspace -Name "MyLogAnalyticsWorkspace").WorkspaceId

# Get the Log Analytics primary key
$workspaceKey = (Get-AzureRmLogAnalyticsWorkspaceSharedKeys -ResourceGroupName "MyResourceGroup" -Name "MyLogAnalyticsWorkspace").PrimarySharedKey

# Create a new Log Analytics data source
New-AzureRmLogAnalyticsDataSource -Name "MyDataSource" -ResourceGroupName "MyResourceGroup" -WorkspaceName "MyLogAnalyticsWorkspace" -LogAnalyticsWorkspaceId $workspaceId -SharedKey $workspaceKey -SourceType "WindowsEvent"

# Create a new Log Analytics alert rule
$webhookUrl = "https://webhookurl.com"
New-AzureRmLogAnalyticsAlertRule -Name "MyAlertRule" -ResourceGroupName "MyResourceGroup" -WorkspaceName "MyLogAnalyticsWorkspace" -Condition "Event[EventID=4625 and EventData[Data[@Name='FailureReason']='An account failed to log on']" -Action "MyWebhook" -WebhookProperties $webhookUrl

# This script starts by connecting to Azure and creating a new Log Analytics workspace, which is used to collect,
# analyze, and visualize security-related data from your Azure resources. Next, it creates a new Log Analytics 
# solution, which is a pre-configured set of views and alerts that can be used to monitor for specific 
# security-related events.

# Then it retrieve the Log Analytics workspace ID and primary key, these are used to create a new data source, 
# which is used to collect data from a specific data source like windows event, in this case.

# Next, the script creates a new Log Analytics alert rule, which is used to send an alert when a specific 
# condition is met. In this example, the alert rule sends an alert when the event ID 4625 and the failure 
# reason is 'An account failed to log on' occurs. The alert is sent to a specified webhook, in this case the 
# webhookUrl value should be replaced with the actual URL you want to use.

# As before, this script is just an example and will require further customization to meet the specific
# needs of your organization.

                

Create a New User in Active Directory

+

# Creating a New User in Active Directory
# To create a new user in Active Directory, use the New-ADUser cmdlet.

# Here is the basic syntax:

New-ADUser -Name "John Doe" -GivenName "John" -Surname "Doe" -SamAccountName "jdoe" -UserPrincipalName "jdoe@example.com" -AccountPassword (Read-Host -AsSecureString "Enter password") -Enabled $true

# This will create a new user with the name "John Doe", given name "John", surname "Doe", samAccountName "jdoe", and userPrincipalName "jdoe@example.com". The -AccountPassword parameter allows you to specify a password for the user, and the -Enabled parameter specifies whether the account is enabled or disabled.

# You can also specify other properties for the user, such as the department, office, and description, using the -Department, -Office, and -Description parameters, respectively.

                

Modify an Existing User in Active Directory

+

# Modifying an Existing User in Active Directory

# To modify an existing user in Active Directory, use the Set-ADUser cmdlet.

# Here is the basic syntax:

Set-ADUser -Identity "jdoe" -Title "Manager" -Department "IT" -Office "New York" -Description "Systems manager"

# This will modify the user with the samAccountName "jdoe" and set their title to "Manager", department to "IT", office to "New York", and description to "Systems manager".

# You can also modify other properties of the user using the appropriate parameters, such as -GivenName, -Surname, and -EmailAddress.

                

Delete an Existing User from Active Directory

+

# Deleting an Existing User in Active Directory
# To delete an existing user in Active Directory, use the Remove-ADUser cmdlet.

# Here is the basic syntax:

Remove-ADUser -Identity "jdoe"

# This will delete the user with the samAccountName "jdoe".

# Note that this will permanently delete the user and their associated information from Active Directory.

                

Bulk Updating Proxy Addresses (script #1)

+

# Using the 'Get' cmdlet in an elevated PowerShell Prompt, run the following command:

Get-ADUser -Filter * -SearchBase "OU=Knowledge,OU=Users,DC=companydomain,DC=com"
      
# NOTE:  It is important to change the information in quotations to match an OU that exists in your organization's Active Directory Environment.

                

Delete an Existing User from Active Directory

+

# Deleting an Existing User in Active Directory
# To delete an existing user in Active Directory, use the Remove-ADUser cmdlet.

# Here is the basic syntax:

Remove-ADUser -Identity "jdoe"

# This will delete the user with the samAccountName "jdoe".

# Note that this will permanently delete the user and their associated information from Active Directory.

                

Bulk Updating Proxy Addresses (part 1)

+

# Using the 'Get' cmdlet in an elevated PowerShell Prompt, run the following command:

Get-ADUser -Filter * -SearchBase "OU=Knowledge,OU=Users,DC=companydomain,DC=com"
      
# NOTE:  It is important to change the information in quotations to match an OU that exists in your organization's Active Directory Environment.

                

Bulk Updating Proxy Addresses (part 2)

+

# In your elevated PowerShell Prompt, run a command which pulls the .csv and triggers the proxyAddresses attribute to be updated with the information in the proxyAddresses column in your CSV for users in the selected OU based on their SAM Account Name for the unique identifier. That command will look something like this:

Import-Csv "C:\Users\adminaccount\scripts\bulk-update-proxy-addresses.csv" | foreach {Set-ADUser -Identity 
$_.samaccountname -add @{Proxyaddresses=$_.Proxyaddresses -split ","}}
      
# NOTE:  It is important to change the information in quotations to match a file path that exists in your environment.

# Extra information:  The "," just before the final two brackets in the final script tells the domain controller to
# add multiple fields, delimiting them by commas.  This can be useful for attributes such as Proxy Addresses and
# Direct Reports where you may need to make multiple entries.
      
# A FRIENDLY REMINDER:  Always make sure to run scripts like this on small test groups first to verify it functions as
# intended.  Making mistakes on bulk updates can cause uneccessary rework and tie up critical resources.  
# MEASURE TWICE, CUT ONCE!!!!!

                

Check to See if RSAT is installed

+

Get-WindowsCapability -Name RSAT* -Online | Select-Object -Property DisplayName, State

                

Install RSAT

+

Get-WindowsCapability -Name RSAT* -Online | Add-WindowsCapability -Online

                

Monitor Failed Logins (README)

+

# Monitor-Failed-Logins
# Here is a detailed guide on how to monitor failed user logins on a domain using PowerShell.

# Prerequisites
# You will need to have access to a domain controller.
# You will need to have the ActiveDirectory module installed on your machine. You can check if it is already installed by running the following command:

Get-Module -ListAvailable | Where-Object {$_.Name -eq "ActiveDirectory"}

# If the ActiveDirectory module is not installed, you can install it by running the following command:

Install-Module -Name ActiveDirectory

                

Delete an Existing User from Active Directory

+

# Deleting an Existing User in Active Directory
# To delete an existing user in Active Directory, use the Remove-ADUser cmdlet.

# Here is the basic syntax:

Remove-ADUser -Identity "jdoe"

# This will delete the user with the samAccountName "jdoe".

# Note that this will permanently delete the user and their associated information from Active Directory.

                

Bulk Updating Proxy Addresses (script #1)

+

# Using the 'Get' cmdlet in an elevated PowerShell Prompt, run the following command:

Get-ADUser -Filter * -SearchBase "OU=Knowledge,OU=Users,DC=companydomain,DC=com"
      
# NOTE:  It is important to change the information in quotations to match an OU that exists in your organization's Active Directory Environment.