Skip to content

Instantly share code, notes, and snippets.

View sassdawe's full-sized avatar
💭
Playing PowerShell

David Sass sassdawe

💭
Playing PowerShell
View GitHub Profile
@JustinGrote
JustinGrote / ThrowStdOutErrors.ps1
Created November 4, 2022 17:40
Catch only specific errors coming from native commands
filter ThrowStdOutErrors($messageFilter,[Parameter(ValueFromPipeline)]$obj) {
if ($obj -is [Management.Automation.ErrorRecord]) {
if ($obj -match $messageFilter) {
throw $obj
} else {
Write-Error $obj
return
}
}
$obj
@JustinGrote
JustinGrote / Write-FunctionError.ps1
Last active February 28, 2023 21:57
Write an Error within a function in a nice way that displays the context of the function rather than the "Write-Error" context
using namespace System.Management.Automation
using namespace Microsoft.PowerShell.Commands
function Write-FunctionError {
<#
.SYNOPSIS
Writes an error within the context of the containing CmdletBinding() function. Makes errr displays prettier
#>
param(
[Parameter(Mandatory)][String]$Message,
[ValidateNotNullOrEmpty()][ErrorCategory]$Category = 'WriteError',
@JustinGrote
JustinGrote / Trace-AICommand.ps1
Last active August 21, 2024 18:48
Trace-AICommand: Report the results and performance of any scriptblock to Azure Application Insights
#requires -version 7
#You can load this script with $(iwr https://tinyurl.com/TraceAICommand | iex)
using namespace Microsoft.ApplicationInsights
using namespace Microsoft.ApplicationInsights.Extensibility
using namespace Microsoft.ApplicationInsights.DataContracts
using namespace System.Management.Automation
using namespace System.Collections.Generic
using namespace System.Net
#Reference: https://docs.microsoft.com/en-us/azure/azure-monitor/app/console
@JustinGrote
JustinGrote / ConvertTo-DataTable.ps1
Last active February 6, 2023 19:01
Build a DataTable from an Array in Powershell. All objects should have the same properties as the first object.
using namespace System.Data
function ConvertTo-DataTable {
<#
.SYNOPSIS
Takes an array and converts it to a datatable, useful for sql or bulk transactions. All objects must be the same (or at least share properties with the first object)
.EXAMPLE
convertto-datatable @(
[PSCustomObject]@{Name = 'Test'; Food = 'Burgers' },
[PSCustomObject]@{Name = 'Test2'; Food = 'Fries' },
[PSCustomObject]@{Name = 'Test3'; Food = 'Coke' },
@JustinGrote
JustinGrote / Grant-ApplicationRoleToUserAssignedManagedIdentity.ps1
Created January 29, 2022 08:02
Use Az Module and Microsoft Graph to Grant an Application Role to a User Assigned Managed Identity
#requires -module Az.Resources
#requires -module Az.ManagedServiceIdentity
function Assert-SingleResult ([Object[]]$inputObject, [String]$Description) {
<#
.SYNOPSIS
Helper function to ensure one and only one item.
#>
if ($inputObject.count -lt 1) {
Write-Error [InvalidOperationException]"$Description was not found."
return $false
@svch0stz
svch0stz / defenderwatch.ps1
Last active November 18, 2022 01:03
WMI Watcher for Windows Defender RealtimeMonitoring
$WMI = @{
Query = "SELECT * FROM __InstanceModificationEvent WITHIN 5 WHERE TargetInstance ISA 'MSFT_MpPreference' AND TargetInstance.DisableRealtimeMonitoring=True"
Action = {
#$Global:Data = $Event
Write-Host "Defender Configuration change - DisableRealtimeMonitoring:"$Event.SourceEventArgs.NewEvent.TargetInstance.DisableRealtimeMonitoring"(Old Value:"$Event.SourceEventArgs.NewEvent.PreviousInstance.DisableRealtimeMonitoring")"
}
Namespace = 'root\microsoft\windows\defender'
SourceIdentifier = "Defender.DisableRealtimeMonitoring"
}
$Null = Register-WMIEvent @WMI
$MyScript = [powershell]::Create()
$null = $MyScript.AddScript( { Import-Module -Name Terminal-Icons } )
$Runspace = [runspacefactory]::CreateRunspace()
$MyScript.Runspace = $Runspace
$null = Register-ObjectEvent -InputObject $MyScript -EventName InvocationStateChanged -Action {
Import-Module -Name Terminal-Icons
}
@IISResetMe
IISResetMe / MagicNumber.class.ps1
Created December 19, 2020 21:18
ECMA-335 SpecialName-based operator overloading in PowerShell classes
class MagicNumber
{
hidden [int] $_value
MagicNumber([int]$value)
{
$this._value = $value
}
# ECMA-335 I.10.3.2
@Jaykul
Jaykul / About OutWithOut.md
Last active August 25, 2020 06:46
You can redirect the other output streams like *>&1 | Out-String.ps1 and these commands will capture them labelled (and optionally, in color), e.g. for | more or | less

PowerShell has a problem with it's extra output streams. The actual content of the Warning, Verbose, Debug, Information, and even Error streams doesn't have the label text like "WARNING: " or "VERBOSE: " that we're used to seeing in the host. That label is actually added by the host (hopefully, in a culture-aware way). However, this means that when you attempt to redirect all of this output, for example by redirecting all output streams to stdout, with *>&1, you don't get labels on them at all, which is confusing, and can make the output difficult to comprehend.

Take for example a function that writes in a loop:

if ($i % 5 -eq 0) {
    Write-Output $i
} else {
    Write-Verbose $i
}
@quantumcore
quantumcore / webcam.ps1
Last active August 20, 2024 07:13
Powershell Script to Record Webcam and output the .AVI file to a base64 file.
# Taken from : https://github.com/EmpireProject/Empire/blob/master/lib/modules/powershell/collection/WebcamRecorder.py
function Start-WebcamRecorder
{
<#
.SYNOPSIS
This function utilizes the DirectX and DShowNET assemblies to record video from the host's webcam.
Author: Chris Ross (@xorrior)
License: BSD 3-Clause
.DESCRIPTION
This function will capture video output from the hosts webcamera. Note that if compression is available, there isn't