PowerShellTricks.com Logo

PowerShell Tricks

Search

Scripts List

Requirements: PowerShell v3 and up

Description: This one liner will tell you when the system last booted up.

systeminfo | find "System Boot Time"

Requirements: PowerShell v4 and up

Description: Count the number of open connections on each port and display it for you.

Get-NetTCPConnection | group localport -NoElement | sort count -Descending

Requirements: PowerShell v3 and up

Description: List the version of IIS currently installed.

Get-ItemProperty HKLM:SOFTWARE\Microsoft\InetStp\ | select setupstring,versionstring

Requirements: PowerShell v4 and up

Description: Find the status code and status description of a site.

curl https://www.powershelltricks.com | Select-Object StatusCode, StatusDescription

Requirements: PowerShell v3 and up

Description: Quickly list all SSL certs installed to see useful info such as friendly name, thumbprint, date of creation, expiration date.

Get-ChildItem –Path cert:\LocalMachine\My | Format-List

Requirements: PowerShell v3 and up

Description: This enables you to quickly list all of the IP addresses.

Get-WmiObject -Class Win32_NetworkAdapterConfiguration -Filter IPEnabled=TRUE | Select-Object -ExpandProperty IPAddress

Requirements: PowerShell v3 and up

Description: List all of the installed programs.

Get-WmiObject -Class Win32_Product | Select-Object -Property Name | Sort-Object Name

Requirements: PowerShell v4 and up

Description: Display all user accounts along with their groups. Narrow down to specific users or OUs if needed.

Get-ADUser -Filter * | foreach-object {
Write-Host "User:" $_.Name -Foreground green
Get-ADPrincipalGroupMembership $_.SamAccountName | Foreach-Object {
Write-Host "Member Of:" $_.name } }

Requirements: PowerShell v3 and up

Description: List all of the installed Windows Features.

Get-WindowsFeature | where {$_.Installed -match "True"} | select Name

Requirements: PowerShell v3 and up

Description: Display all of the MSSQL instances on a database server.

(Get-itemproperty 'HKLM:\SOFTWARE\Microsoft\Microsoft SQL Server').InstalledInstances

Requirements: PowerShell v3 and up

Description: This uses PS to show all pending CSRs.

Get-ChildItem cert:\LocalMachine\REQUEST\ | Sort-Object -Property Subject | fl Subject,@{n='Creation Date';e={$_.'geteffectivedatestring'()}}

Requirements: PowerShell v4 and up

Description: This script will backup IIS logs to another drive or directory and then remove all logs older than 14 days.

$source = "C:\inetpub\logs\LogFiles\"
$destination = "E:\IISLogBackups_$(Get–Date –format M).zip"
Add–Type –assembly "system.io.compression.filesystem"
[io.compression.zipfile]::CreateFromDirectory($source, $destination)
$logs = ls –Path "C:\inetpub\logs\LogFiles\*" –Recurse | Where–Object{$_.LastWriteTime –lt (Get–Date).AddDays(–14)}
$logs | Remove–Item

Requirements: PowerShell v4 and up

Description: Check the response time for a website.

measure-command {invoke-webrequest http://pokenoob.com}

Requirements: PowerShell v4 and up

Description: This script combines the more useful output of the Get-WBPolicy & Get-WBSummary cmdlets.

$MyObject = New-Object PSObject –Property @{
NextBackupTime = (Get-WBSummary).NextBackupTime
LastSuccessfulBackupTime = (Get-WBSummary).LastSuccessfulBackupTime
CurrentOperationStatus = (Get-WBSummary).CurrentOperationStatus
NumberOfVersions = (Get-WBSummary).NumberOfVersions
BackupTargets = (Get-WBPolicy).BackupTargets
VolumesToBackup = (Get-WBPolicy).VolumesToBackup
BMR = (Get-WBPolicy).BMR
SystemState = (Get-WBPolicy).SystemState
}

Requirements: PowerShell v4 and up

Description: Search the Security log for all failed login attempts within the past 3 days. Displays the info in a list which includes the username, workstation, domain, IP address & the time.

$DT = [DateTime]::Now.AddDays(-3)
Get-EventLog -LogName 'Security' -InstanceId 4625 -After $DT | Select TimeGenerated,ReplacementStrings |
% { New-Object PSObject –Property @{
Source_Computer = $_.ReplacementStrings[13]
UserName = $_.ReplacementStrings[5]
Account_Domain = $_.ReplacementStrings[6]
IP_Address = $_.ReplacementStrings[19]
Date = $_.TimeGenerated
} } | Format-List > C:\Users\$env:username\Desktop\Failed_Logon_Attempts.txt

Requirements: PowerShell v4 and up

Description: The first value defines how long the password will be. The second value defines how many characters of the password will not be letters.

Add-Type -Assembly System.Web
[Web.Security.Membership]::GeneratePassword(14,4)

Requirements: PowerShell v4 and up

Description: List all domain members, including Operating System and Service Pack installed.

Get-ADComputer -Filter * -Property * | Format-Table Name,OperatingSystem,OperatingSystemServicePack,OperatingSystemVersion -Wrap –Auto

Requirements: PowerShell v4 and up

Description: Shows disk space allocated and used for each drive.

foreach($disk in gwmi win32_logicaldisk){
$disk.deviceid
Write-Host Allocated: -ForegroundColor green
[math]::Round($disk.size/1gb,2)
Write-Host Free: -ForegroundColor green
[math]::Round($disk.freespace/1gb,2)
Write-Host -ForegroundColor red ----------------}

Requirements: PowerShell v4 and up

Description: Shows the 20 most recent server logins.

Get-WinEvent -ProviderName 'Microsoft-Windows-TerminalServices-LocalSessionManager' | where {$_.ID -eq 22} | fl | Select-Object -First 20

Requirements: PowerShell v4 and up

Description: Finds all recurring scheduled tasks and displays the next run time.

Get-Scheduledtask | Get-Scheduledtaskinfo | select taskname,nextruntime | sort nextruntime | where {$_.nextruntime -ne $NULL} | format-table * -autosize

Requirements: PowerShell v4 and up

Description: Display your public IP address using IPUnicorn.com

curl ipunicorn.com | select Content | fl

Requirements: PowerShell v4 and up

Description: Create an SSL CSR quickly via PowerShell.

Invoke-Command -ScriptBlock {
$CertName = Read-Host -Prompt 'Input the domain name'
$City = Read-Host -Prompt 'Input the City'
$State = Read-Host -Prompt 'Input the State'
$Country = Read-Host -Prompt 'Input the Country'
$CSRPath = "C:\$($CertName)_.csr"
$CSRPath = $CSRPath -replace '\*', ''
$INFPath = "C:\$($CertName)_.inf"
$INFPath = $INFPath -replace '\*', ''
$Signature = '$Windows NT$'
$INF =
@"
[Version]
Signature= "$Signature"
[NewRequest]
Subject = "CN=$CertName, OU=$OU, O=$OU, L=$City, S=$State, C=$Country"
KeySpec = 1
KeyLength = 2048
Exportable = TRUE
MachineKeySet = TRUE
SMIME = False
PrivateKeyArchive = FALSE
UserProtected = FALSE
UseExistingKeySet = FALSE
ProviderName = "Microsoft RSA SChannel Cryptographic Provider"
ProviderType = 12
RequestType = PKCS10
KeyUsage = 0xa0
[EnhancedKeyUsageExtension]
OID=1.3.6.1.5.5.7.3.1
"@
Write-Host "Certificate Request is being generated"
$INF | out-file -filepath $INFPath -force
certreq -new $INFPath $CSRPath
Get-Content $CSRPath
}
Write-Output "Certificate Request has been generated"
Write-Output "Cleanup after your pet (delete CSR files when complete)"

Requirements: PowerShell v4 and up

Description: Create a function which performs an IP location lookup. You will need to create a free account with ipstack.com in order to receive your free access key. When received, update the function below to include your access key.

function Get-IPLocation
{
Param
(
[string]$IPAddress
)
$request = Invoke-RestMethod -Method Get -Uri "http://api.ipstack.com/$IPAddress ?access_key=6*********7"
[PSCustomObject]@{
IP = $request.ip
Continent = $request.continent_name
CountryCode = $request.country_code
Country = $request.country_name
RegionCode = $request.region_code
RegionName = $request.region_name
City = $request.city
Zip = $request.zip
}
}

Requirements: PowerShell v4 and up

Description: This can be used as a scheduled task to copy the latest SQL backup to a directory for retrieval via FTP. Only the latest backup will be available each day.

net use \\fileserver1\ProdWeb /user:domain\username password
Remove-Item \\fileserver1\ProdWeb\Backup\*.bak
$Path = "O:\SQL Backups\Prod-DB`$ProdWeb\Web\FULL"
$NewestBackup = Get-ChildItem "$Path" | sort LastWriteTime | select -last 1
Copy-Item ($Path + '\' + $NewestBackup) -Destination \\ftpserver1\ProdWeb\Backup

Requirements: PowerShell v4 and up

Description: This can be used to list the installed SSL certificates for all servers in a domain.

$Servers = Get-ADComputer -Filter * | Select -Expand Name
for($i = 0; $i -lt $Servers.length; $i++){
Invoke-Command -Computername $servers[$i] -ScriptBlock {$env:computernameGet-ChildItem -Path cert:\LocalMachine\My | Format-List
} | out-file -append C:\Users\$env:username\Desktop\SSL_Cert_Details.txt
}

Requirements: PowerShell v4 and up

Description: This script will search through the security log on the the servers specified to look for event ID 4740 and then reports the time at which the account lockout occurred and on which computer the lockout event originated. In an effort in decrease the runtime, the script defaults to review the logs over the past 1 hour. .Parameter Server The security log of the computers listed in this parameter will be used. .Parameter UserName The user to look for in the security logs. .Parameter Hours Specify how far back in the logs the search should look (defaults to 1). .Example Get-LockoutInfo -Username username

Function Get-LockoutInfo {
param (
[string]$Username = "*",
[string]$Server = "dc01.domain.com",
[int]$Hours = 1
)

# Getting information from the security log of the current domain controller
$lockEvents = Get-WinEvent -FilterHashtable @{LogName="Security";ID=4740;StartTime=(Get-Date).AddHours(-$Hours)} -ComputerName $Server | `
Where-Object {$_.Properties[0].Value -like $Username}

# Instantiating array
$colEvents = @()

ForEach ($event in $lockEvents) {
# Creating PSObject
$objOut = New-Object -TypeName PSObject

# Adding properties to the object
$objOut | Add-Member -MemberType NoteProperty -Name TimeGenerated -Value $event.timeCreated
$objOut | Add-Member -MemberType NoteProperty -Name Username -Value $event.Properties[0].Value
$objOut | Add-Member -MemberType NoteProperty -Name CallingComputer -Value $event.Properties[1].Value

$colEvents += $objOut
}

$colEvents
}

Requirements: PowerShell v4 and up

Description: This creates a function which compares two folders and lists the files and folders unique to each folder.

Function Get-Folder
{param ($title)
[System.Reflection.Assembly]::LoadWithPartialName("System.windows.forms") | Out-Null

$foldername = New-Object System.Windows.Forms.FolderBrowserDialog
$foldername.rootfolder = "MyComputer"
$foldername.Description = $title

if($foldername.ShowDialog() -eq "OK")
{
$folder = $foldername.SelectedPath.ToString()
}
return $folder
}

Clear-Variable folder1,folder2

while ($folder1 -eq $null -or $folder1 -eq ""){$folder1 = Get-Folder -title "Select First folder"}
while ($folder2 -eq $null -or $folder1 -eq "" -or $folder2 -eq $folder1){$folder2 = Get-Folder -title "Select Second folder"}
while ($folder3 -eq $null -or $folder3 -eq ""){$folder3 = Get-Folder -title "Select folder for output file"}

$Source = Get-ChildItem -Path $folder1 -Recurse
$Dest = Get-ChildItem -Path $folder2 -Recurse

$diffout = @()
$outtxt = @("Full Name,Object Type,Only exists under")

$diffs = Compare-Object -ReferenceObject $Source -DifferenceObject $Dest #| Out-GridView

$diffs | ForEach-Object {

$forf = ""
if ($_.InputObject.PsIsContainer){$forf = "Folder"}
else{$forf = "File"}

$DiffDetail = New-Object PSObject

if ($_.SideIndicator -eq "<="){
$DiffDetail | Add-Member -Name "Full Name" -MemberType NoteProperty -Value $_.InputObject.FullName
$DiffDetail | Add-Member -Name "Object Type" -MemberType NoteProperty -Value "$forf"
$DiffDetail | Add-Member -Name "Only exists under" -MemberType NoteProperty -Value $folder1
$outtxt += "$($_.InputObject.FullName),$($forf),$($folder1)"}

if ($_.SideIndicator -eq "=>"){
$DiffDetail | Add-Member -Name "Full Name" -MemberType NoteProperty -Value $_.InputObject.FullName
$DiffDetail | Add-Member -Name "Object Type" -MemberType NoteProperty -Value "$forf"
$DiffDetail | Add-Member -Name "Only exists under" -MemberType NoteProperty -Value $folder2
$outtxt += "$($_.InputObject.FullName),$($forf),$($folder2)"}

$diffout += $DiffDetail

}

$dt = Get-Date -Format "yyyy-MM-dd_hh-mm-ss"
add-content "$($folder3)\$($dt)_missing.csv" $outtxt
$diffout | Out-GridView -Title "File and Folder differnces"

Requirements: PowerShell v4 and up

Description: This creates a function which compares two folders and lists the files and folders unique to each folder. It also compares files of the same name and marks them as a mismatch if the contents are different.

Function Get-Folder
{param ($title)
[System.Reflection.Assembly]::LoadWithPartialName("System.windows.forms") | Out-Null

$foldername = New-Object System.Windows.Forms.FolderBrowserDialog
$foldername.rootfolder = "MyComputer"
$foldername.Description = $title

if($foldername.ShowDialog() -eq "OK")
{
$folder = $foldername.SelectedPath.ToString()
}
return $folder
}

Clear-Variable folder1,folder2

while ($folder1 -eq $null -or $folder1 -eq ""){$folder1 = Get-Folder -title "Select First folder"}
while ($folder2 -eq $null -or $folder1 -eq "" -or $folder2 -eq $folder1){$folder2 = Get-Folder -title "Select Second folder"}
while ($folder3 -eq $null -or $folder3 -eq ""){$folder3 = Get-Folder -title "Select folder for output file"}

$mismatch = @()

# Get all files under $folder1, filter out directories
$firstFolder = Get-ChildItem -Recurse $folder1 | Where-Object { -not $_.PsIsContainer }

$firstFolder | ForEach-Object {

# Check if the file, from $folder1, exists with the same path under $folder2
If ( Test-Path ( $_.FullName.Replace($folder1, $folder2) ) ) {

# Compare the contents of the two files...
If ( (Get-FileHash $_.FullName).hash -ne (Get-FileHash $_.FullName.Replace($folder1, $folder2)).hash ) {

# List the paths of the files containing diffs
$mismatch += "The files $($_.FullName) and $($_.FullName.Replace($folder1, $folder2)) do not match"
}
}
else
{
$mismatch += "$($_.FullName) is only in `t`t $($folder1)"
}
}

$secondFolder = Get-ChildItem -Recurse $folder2 | Where-Object { -not $_.PsIsContainer }

$i = 0
$totalCount = $secondFolder.Count
$secondFolder | ForEach-Object {

# Check if the file, from $folder2, exists with the same path under $folder1
If (!(Test-Path($_.FullName.Replace($folder2, $folder1))))
{
$mismatch += "$($_.FullName) is only in `t`t $($folder2)"
}
}

$dt = Get-Date -Format "yyyy-MM-dd_hh-mm-ss"
$mismatch | Out-File "$($folder3)\$($dt)_mismatch.txt"
$mismatch | Out-GridView -Title "Mismatches"

Requirements: PowerShell v4 and up

Description: Reset a single AD account password.

$NewPassword = (Read-Host -Prompt "Provide New Password" -AsSecureString)
Set-ADAccountPassword -Identity admin01 -NewPassword $NewPassword -Reset

Requirements: PowerShell v4 and up

Description: Set the $vCenterName varibale and VM substring before running the script.

Import-Module VMware.PowerCLI
#Specify vCenter server
[string]$vCenterName = "vcenter1 server"

$outfile = "C:\Users\$env:username\Desktop\VM_IPs.csv"
Add-Content $outfile "Name,IPV4 IPs"

# Connect vCenter server session
Connect-VIServer $vCenterName -Protocol https

#Get VMs - edit the name.contains for the VMs you need
Get-VM | where-object {$_.Name.Contains("vmname substring")} |
foreach{$ipv4 = ""
for($cnt = 0; $cnt -lt $_.Guest.IPAddress.count; $cnt++){
#filter ipv6 addresses
if(!$_.Guest.IPAddress[$cnt].Contains("fe80")){

$ipv4 += $_.Guest.IPAddress[$cnt] + ";"

}

}

$vmname = ""
$vmname = $_.Name
#remove semicolon from end of string
if($ipv4[$ipv4.Length-1] -eq ";"){$ipv4 = $ipv4.Remove($ipv4.Length-1)}

$outtxt = ""
$outtxt = '"' + $vmname + '","' + $ipv4 + '"'
Add-Content $outfile $outtxt

}

Requirements: PowerShell v4 and up

Description: This will search the Security log for Event ID 1080 and select just the time of each occurrence.

Get-EventLog -LogName Security | Where-Object { $_.EventID -eq 1080 } | Select-Object TimeGenerated

Requirements: PowerShell v4 and up

Description: This will search the System log for any event with a message containing a specific keyword.

Get-WinEvent -LogName System | Where-Object {$_.Message -like "*0x80004005*"} | fl

Requirements: PowerShell v4 and up

Description: This will list all of the updates which were installed during the specific dates.

Get-HotFix | Where { $_.InstalledOn -gt "11/28/2018" -AND $_.InstalledOn -lt "6/13/2019" } | sort InstalledOn

Requirements: PowerShell v4 and up

Description: This will enable the CredSSP server role on a list of servers.

$servers = Get-Content C:\serverlist.txt
$creds = Get-Credential
foreach ($server in $servers) {
New-PSSession -ComputerName $server -Credential $creds | Out-Null
Invoke-Command -ComputerName $server -ScriptBlock {
Enable-WSManCredSSP –Role Server -Force
}
}

Requirements: PowerShell v4 and up

Description: This will check all of the servers in a list for installed updates after a specific date. Since the destination file is on a network share, CredSSP must be enabled for the kerberos double hop.

$servers = Get-Content C:\serverlist.txt
$creds = Get-Credential

foreach ($server in $servers) {
New-PSSession -ComputerName $server -Credential $creds –Authentication CredSSP | Out-Null
$a = Invoke-Command -Session (Get-PSSession) -ScriptBlock {

#Setup the table.
$tbl = New-Object System.Data.DataTable "Updates"
$col1 = New-Object System.Data.DataColumn Title
$col2 = New-Object System.Data.DataColumn Date
$col3 = New-Object System.Data.DataColumn KB
$tbl.Columns.Add($col1)
$tbl.Columns.Add($col2)
$tbl.Columns.Add($col3)

Write "Updates installed on $env:COMPUTERNAME" | Out-File -Append -FilePath "\\fileserver01\Updates\updates.txt"

$Session = New-Object -ComObject "Microsoft.Update.Session"

$Searcher = $Session.CreateUpdateSearcher()

$historyCount = $Searcher.GetTotalHistoryCount()

foreach($hotfix in $Searcher.QueryHistory(0, $historyCount)) {
Select-Object Title, Description, Date,

@{name="Operation"; expression={switch($_.operation){

1 {"Installation"}; 2 {"Uninstallation"}; 3 {"Other"}

}}}
if ($hotfix.Date -ne '12/30/1899') {
#For whatever reason ^ was needed to prevent a ton of blank entries with that date
#Set start date here
if ($hotfix.Date -ge '11/29/2018') {
$row = $tbl.NewRow()
$row.Title = $hotfix.Title
$row.Date = $hotfix.Date
#$row.KB = $hotfix.KB
$tbl.Rows.Add($row)
}
}
}
$tbl | ft | Out-File -Append -FilePath "\\fileserver01\Updates\updates.txt"
}
Get-PSSession | Remove-PSSession
}

Requirements: PowerShell v4 and up

Description: This can be used to quickly list the current version of SQL installed.

Invoke-SqlCmd -query "select @@version" -ServerInstance "localhost"

Requirements: PowerShell v4 and up

Description: Use this script with a csv file containing a list of IPs with IPAddress as the header. It will check the DHCP reservation status of each IP and output the results to a csv file.

$IPs = Import-CSV “C:\Users\$env:username\Desktop\IPs.csv”
ForEach ($item in $IPs) {
$IP = $item.(“IPAddress”)
Get-DhcpServerv4Lease -ComputerName "dhcpserver1" -IPAddress "$IP" | select IPAddress, ScopeID, AddressState | Export-Csv C:\Users\$env:username\Desktop\DHCPReservations.csv -append }

Requirements: PowerShell v4 and up

Description: This will set the TLS 1.0 & 1.1 client and server keys to disabled.

$TLS1_1 = "HKLM:\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\TLS 1.1\Client"
Set-ItemProperty -Path $TLS1_1 -Name "Enabled" -Value 0 -Type "DWord"
Set-ItemProperty -Path $TLS1_1 -Name "DisabledByDefault" -Value 1 -Type "DWord"

$TLS1_1 = "HKLM:\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\TLS 1.1\Server"
Set-ItemProperty -Path $TLS1_1 -Name "Enabled" -Value 0 -Type "DWord"
Set-ItemProperty -Path $TLS1_1 -Name "DisabledByDefault" -Value 1 -Type "DWord"

$TLS1_0 = "HKLM:\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\TLS 1.0\Client"
Set-ItemProperty -Path $TLS1_0 -Name "Enabled" -Value 0 -Type "DWord"
Set-ItemProperty -Path $TLS1_0 -Name "DisabledByDefault" -Value 1 -Type "DWord"

$TLS1_0 = "HKLM:\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\TLS 1.0\Server"
Set-ItemProperty -Path $TLS1_0 -Name "Enabled" -Value 0 -Type "DWord"
Set-ItemProperty -Path $TLS1_0 -Name "DisabledByDefault" -Value 1 -Type "DWord"

Restart-Computer

Requirements: PowerShell v4 and up

Description: List the last SQL backup times for all databases in a specified instance. Replace “MSSQLSERVER” with the name of the SQL instance to query.

$s = New-Object ('Microsoft.SqlServer.Management.Smo.Server') "MSSQLSERVER"
$dbs=$s.Databases
$dbs | SELECT Name,LastBackupDate, LastLogBackupDate | Format-Table -autosize

Requirements: PowerShell v4 and up

Description: Use this script with a csv file containing a list of printer IPs and their MAC addresses. Reservations will be created for each printer.

$Printers = Import-CSV “C:\Users\$env:username\Desktop\Printers.csv”
ForEach ($item in $Printers) {
$IP = $item.(“IPAddress”)
$MAC = $item.(“MAC”)
Add-DhcpServerv4Reservation -ComputerName "dhcpserver1" -ScopeId 192.168.10.0 -IPAddress "$IP" -ClientId "$MAC" -Description "Reservation for HR Printers" }

Requirements: PowerShell v4 and up. Two Windows Features must be installed: Web-Lgcy-Scripting and Web-WMI

Description: Use this script to list all of the IPs which were added to the SMTP relay restrictions list as Granted. Change to IPDeny to list IPs which were denied.

Get-WmiObject -Namespace "root\MicrosoftIISv2" -Class "IIsIPSecuritySetting" -Property Name,IPGrant | ` where {$_.Name -eq "SmtpSvc/1"} | `
Select-Object Name,IPGrant | `
foreach {$_.IPGrant} | Out-File "C:\temp\SMTPRelayIPs.csv"

Requirements: PowerShell v4 and up

Description: This example function comes in handy for executing tasks to remote servers. The process will first attempt to simply connect to the server and echo the hostname, then it connects using Credssp to avoid the Kerberos 2nd hop issue. This allows me to notice that I can connect with default auth and then fail credssp auth. Edit the begin, process, and end sections to match your needs and add error action preferences along the way.

Function Example-Function
{
[CmdletBinding()]
Param
(
[Parameter(ValueFromPipeline)]
[String[]]$ComputerName
)
BEGIN
{
$Creds = Get-Credential
}

PROCESS
{
Foreach ($Computer in $ComputerName) {
try {Invoke-Command -ComputerName $Computer -ScriptBlock {hostname} -ErrorAction Stop
try {Invoke-Command -ComputerName $Computer -Authentication Credssp -Credential $creds -ScriptBlock {

} # End of scriptblock
}
catch {$_.Exception.Message
Write-Host "Unable to perform task on" $env:computername -BackgroundColor DarkRed}
}
catch {$_.Exception.Message
Write-Host "Computer $Computer is not reachable" -BackgroundColor DarkRed}
}
}
END
{
Write-Host "Finished doing things to all computers"
}
} #END Function Example-Function

Requirements: PowerShell v4 and up

Description: Ever restore a VM and it comes back online with a broken trust relationship error? You can disjoin and rejoin it to the domain, or take the fast route and run the following command to reset the computer machine password to fix this issue.

$Creds = Get-Credential
Reset-ComputerMachinePassword -Server -Credential $Creds

Requirements: PowerCLI

Description: Export a list of all of the vMotion IPs used by the VM hosts in all clusters.

ForEach ($Cluster in $Clusters){
$VmHosts = $Cluster | Get-VmHost | Where {$_.ConnectionState -eq “Connected”} | Sort Name
ForEach ($VmHost in $VmHosts){
$Report += Get-VMHostNetworkAdapter -VMHost $VmHost.Name -VMKernel | Where {$_.VMotionEnabled -eq “True”} | select VmHost,IP
}
}
$Report | Export-Csv C:\Users\$env:username\Desktop\vMotionIPs.csv -NoTypeInformation -UseCulture

Requirements: PowerCLI

Description: Display the current time across all VMware hosts to check if they are all accurate.

Get-VMHost | sort Name | select Name,@{Name="Current VMHost Time";Expression={(Get-View $_.ExtensionData.ConfigManager.DateTimeSystem).QueryDateTime()}}

Requirements: PowerCLI

Description: Create a list of current snapshots.

Get-VM | Get-Snapshot | select VM, Name, Created, Description, SizeGB | fl > C:\Users\$env:username\Desktop\snapshots.txt

Requirements: PowerShell v5 with AWSPowerShell module installed.

Description: This will select the latest file from a directory and upload it to an S3 bucket. Import credentials prior to setting up, then setup a scheduled task to run nightly after SQL backups complete. TagSet is utilized to set file retention via a lifecycle policy.

Invoke-Command -ScriptBlock {
Set-AWSCredential -ProfileName SQLBackups
$Path = "S:\SQL Backups\dbserver-01\database01_db1\FULL"
$NewestBackup = gci $Path | sort LastWriteTime | select -last 1
Write-S3Object -BucketName sqlbackup-bucket -file ($Path + '\' + $NewestBackup) -key $NewestBackup.Name -TagSet @{Key="Name";Value="SQLBackup"} -StorageClass Standard_IA
}

Requirements: PowerShell v5 with AWSPowerShell module installed.

Description: Use this to setup an S3 lifecycle policy to set object retention to 30 days. In this case the prefix is blank, so update if necessary.

Invoke-Command {
Set-AWSCredential -ProfileName SQLBackups
$NewRule = [Amazon.S3.Model.LifecycleRule] @{
Expiration = @{
Days= 30
}
Id = "SQL Retention"
Filter= @{
LifecycleFilterPredicate = [Amazon.S3.Model.LifecycleAndOperator]@{
Operands= @(
[Amazon.S3.Model.LifecyclePrefixPredicate] @{
"Prefix" = ""
},
[Amazon.S3.Model.LifecycleTagPredicate] @{
"Tag"= @{
"Key" = "Name"
"Value" = "SQLBackup"
}
}
)
}
}
"Status"= 'Enabled'
}

Write-S3LifecycleConfiguration -BucketName sqlbackup-bucket -Configuration_Rule $NewRule
}