Skip to content

Instantly share code, notes, and snippets.

View adbertram's full-sized avatar

Adam Bertram adbertram

View GitHub Profile
"Smith, John" -replace "(\w+),\s*(\w+)", '$2 $1'
## John Smith
function Write-CustomLog {
param([string]$Message)
$callerInfo = (Get-PSCallStack)[1]
$scriptName = Split-Path -Leaf $callerInfo.ScriptName
$lineNumber = $callerInfo.ScriptLineNumber
$functionName = $callerInfo.FunctionName
$logEntry = "{0:yyyy-MM-dd HH:mm:ss} - {1}:{2} - {3} - {4}" -f `
(Get-Date), $scriptName, $lineNumber, $functionName, $Message
$logEntries = @(
"2024-06-09",
"Error: Disk full",
404,
"2024-06-08",
"Error: Network unreachable",
500
)
foreach ($entry in $logEntries) {
function Remove-ItemSafely {
[CmdletBinding(SupportsShouldProcess, ConfirmImpact = 'High')]
param([string]$path)
if ($PSCmdlet.ShouldProcess($path, "Remove")) {
Remove-Item -Path $path
}
}
PS> Remove-ItemSafely -Path '\oh\god\wrong\file.txt' -WhatIf
function Get-ListOfFiles {
[OutputType('System.IO.FileInfo')]
[CmdletBinding()]
param(
[string]$Path
)
Get-ChildItem -File -Path $Path
}
Get-ListOfFiles -Path "C:\Temp" | ForEach-Object {
function Get-DatabaseData {
[CmdletBinding()]
param (
[Parameter(Mandatory)]
[string]$DatabaseType
)
dynamicparam {
$paramDictionary = New-Object System.Management.Automation.RuntimeDefinedParameterDictionary
$attributes = New-Object System.Collections.ObjectModel.Collection[System.Attribute]
function Set-LogLevel {
param (
[ValidateSet("Debug", "Info", "Warning", "Error")]
[string]$Level
)
Write-Output "Log level set to $Level"
}
# Example usage:
## Instead of this
$group = 'some group name'
## Do this
$groupName = 'some group name'
## Because a group could be an object with properties like id, name, displayname, etc
# Define a custom object for a server or whatever object you want
$server = [pscustomobject]@{
Name = "Server1"
IPAddress = "192.168.0.1"
}
# Add a ScriptMethod to check if the server is online
## This can run any code you may like to associated with an object
$server | Add-Member -MemberType ScriptMethod -Name "IsOnline" -Value {
param ($Timeout = 1000)
## e.g. Ensure Get-Content always returns verbose information
$PSDefaultParameterValues['Get-Content:Verbose'] = $true