Skip to content

Instantly share code, notes, and snippets.

@jdhitsolutions
Last active February 2, 2022 21:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jdhitsolutions/5ac874ee8aed0f9bf92838b6d2402f7a to your computer and use it in GitHub Desktop.
Save jdhitsolutions/5ac874ee8aed0f9bf92838b6d2402f7a to your computer and use it in GitHub Desktop.
This is my demo file from my RTPSUG on PowerShell 7.
#requires -version 7.1.2
Return "This is a walk-through demo script file"
#region demo prep
# Are you running in PowerShell 7?
#make my errors easier to read
$host.PrivateData.ErrorForegroundColor = "yellow"
#clear any default settings
$PSDefaultParameterValues.clear()
cd c:\
Clear-Host
#fold all regions in VSCode: Ctrl+K,Ctrl+8
#endregion
#region PS7 variables
Get-Variable is*
$PSEdition
$PSVersionTable
#in linux
wsl pwsh -noprofile -command "&{(get-variable PSversiontable).value}"
# wsl pwsh -noprofile -command {$psversiontable}
#endregion
#region New operators
#chain commands
<#
More for console work than scripting
read help ABOUT_PIPELINE_CHAIN_OPERATORS
#>
Clear-Host
#success
1 -gt 0 && Get-Date
#this isn't an If statement
0 -gt 1 && Get-Date
Get-service foo && Get-Date
#chaining can affect output
$srv = "thinkx1-jh"
test-wsman $srv && Get-Volume -CimSession $srv
test-wsman $srv && Get-Volume -CimSession $srv | Out-Default
#failure
Get-Service foo || "oops"
#chaining multiple
($a = test-wsman $srv) && ($b = Get-Volume -CimSession $srv) && ($c = Get-Ciminstance Win32_PhysicalMemory -cimsession $srv)
$a
$b
$c
#ternary
# help about_if
# if ( ) { 'then'} [else { 'otherwise'}]
# <true/false test> ? <true code> : <false code>
10 -gt 5 ? "Yes it is" : "No it isn't"
10 -lt 5 ? "Yes it is" : "No it isn't"
(Get-Date).DayOfWeek -eq 'wednesday' ? "run midweek backup" : "do nothing"
$srv = "thinkx1-jh"
(test-wsman $srv) ? (Get-Volume -CimSession $srv) : (Write-Warning "Can't connect to $srv")
$srv = "foobar"
(test-wsman $srv -ErrorAction SilentlyContinue) ? (Get-Volume -CimSession $srv) : (Write-Warning "Can't connect to $srv")
#you could still use Try/Catch for this type of thing
#there is no ElseIf option
#endregion
#region Get-Error
help Get-Error
cls
#better error formatting
Get-Error -Newest 1
#error object is improved
$error
$error[-1] | Get-Error
$error | Select-Object @{Name = "Command";Expression = {$_.invocationinfo.line}},
TargetObject,@{Name = "Category";Expression = {$_.categoryinfo.Category}},
@{Name = "Activity";Expression = {$_.categoryinfo.Activity}},
@{Name = "Reason";Expression = {$_.categoryinfo.Reason}}
#endregion
#region PSStyles
cls
$PSStyle
#display may vary based on Windows Terminal color scheme
# `e is for PowerShell 7
#some settings may override $host.privatedata or be controlled by the host
$PSStyle.Formatting
write-warning "Danger, Will Robinson!"
$PSStyle.Formatting.Warning = "`e[31;5m"
write-warning "More danger, Will Robinson!"
#not all settings may change in vscode code host with $PSStyle
cls
#table headers
get-process -id $pid
$PSStyle.Formatting.TableHeader = "`e[38;5;222m"
get-process -id $pid
#or use on of the built-in colors
$PSStyle.Foreground
$PSStyle.Background
$PSStyle.Formatting.TableHeader = $PSStyle.Background.BrightBlack
Get-Process | Select-Object -first 10
$PSStyle.Formatting.TableHeader = $psstyle.Foreground.FromRgb(100,240,150)
#directory
#I've customized my settings
$psstyle.FileInfo
dir c:\work | more
#requires
Get-ExperimentalFeature PSAnsiRenderingFileInfo
# https://4sysops.com/archives/using-powershell-with-psstyle/
#endregion
#region More Console experience improvements
cls
# Command prediction (technically a PSReadline feature)
Get-module PSReadLine
#PredictionSource and InlinePredictionColor
Get-PSReadLineOption
#define these in your profile
Set-PSReadLineOption -PredictionSource History
#or use an ANSI escape sequence
Set-PSReadLineOption -Colors @{InlinePrediction=$psstyle.foreground.green}
Set-PSReadLineKeyHandler -Chord "ctrl+f" -Function ForwardWord
cls
#demo prediction use in the console
# console gridview
# Install-Module Microsoft.PowerShell.consoleGuiTools
Get-Service | Out-ConsoleGridView
dir c:\work -file | ocgv |
Compress-Archive -destinationpath c:\work\sample.zip -PassThru -Force
#Does not work in a remoting session
# progress bar
cls
#watch closely
Get-PSReleaseAsset -Family Windows -Preview -Format msi -Only64Bit |
Save-PSReleaseAsset -path c:\work
$psstyle.Progress
#view can be minimal or classic
$psstyle.Progress.Style = "`e[38;5;121m"
#you lose some data
#endregion
#region ForEach -parallel
# workflows not supported in v7
<#
-Parallel doesn't always mean faster because of
the runspace overhead
#>
#the following takes almost 40 seconds to complete using a traditional approach
$t = {
param ([string]$Path)
Write-Host "[$(Get-Date -f 'hh:mm:ss.ffff')] BEGIN Measuring $path" -ForegroundColor yellow
Get-ChildItem -path $path -recurse -file -erroraction SilentlyContinue |
Measure-Object -sum -Property Length -Maximum -Minimum |
Select-Object @{Name = "Computername"; Expression = { $env:COMPUTERNAME } },
@{Name = "Path"; Expression = { Convert-Path $path } },
Count, Sum, Maximum, Minimum
Write-Host "[$(Get-Date -f 'hh:mm:ss.ffff')] END Measuring $path" -ForegroundColor yellow
}
Measure-Command {
"c:\work", "c:\scripts", "d:\temp", "C:\users\jeff\Documents", "c:\windows" |
ForEach-Object -process { Invoke-Command -scriptblock $t -argumentlist $_ }
}
#this may be faster using -parallel
Measure-Command {
"c:\work", "c:\scripts", "d:\temp", "C:\users\jeff\Documents", "c:\windows" | ForEach-Object -parallel {
$path = $_
Write-Host "[$(Get-Date -f 'hh:mm:ss.ffff')] BEGIN Measuring $path" -ForegroundColor yellow
Get-ChildItem -path $path -recurse -file -erroraction SilentlyContinue |
Measure-Object -sum -Property Length -Maximum -Minimum |
Select-Object @{Name = "Computername"; Expression = { $env:COMPUTERNAME } },
@{Name = "Path"; Expression = { Convert-Path $path } },
Count, Sum, Maximum, Minimum
Write-Host "[$(Get-Date -f 'hh:mm:ss.ffff')] END Measuring $path" -ForegroundColor yellow
}
} #23 seconds
Measure-Command {
$r = 'srv1', 'srv2', 'win10', 'dom1', 'dom2' | ForEach-Object {
Get-WinEvent -FilterHashtable @{Logname = "system"; Level = 2, 3 } -MaxEvents 100 -ComputerName $_
}
} #about 5 seconds
Measure-Command {
$s = 'srv1', 'srv2', 'win10', 'dom1','dom2' | ForEach-Object -parallel {
Get-WinEvent -FilterHashtable @{Logname = "system"; Level = 2, 3 } -MaxEvents 100 -ComputerName $_
}
} #2.2 seconds
#endregion
#region SSH Remoting
#VS Code terminal doesn't like this. Demo in console.
help Enter-PSSession
#I've setup SSH keys for this host
enter-pssession -HostName wilma -UserName jeff -SSHTransport
$PSVersionTable
Get-Process
Exit
#fedora
New-PSSession -UserName jeff -HostName fred-company-com -SSHTransport
#windows 2016
New-PSSession -UserName artd -HostName srv1 -SSHTransport
New-PSSession -ComputerName dom2,dom1,srv2 -Credential company\artd
$all =Get-PSSession
$all
invoke-command {get-process -id $pid } -session $all
invoke-command { [Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12} -session $all
invoke-command {
#Install-PackageProvider -name nuget -force -forcebootstrap
Install-Module psfunctioninfo -force
} -session $all
Invoke-Command { Get-Module PSFunctionInfo -ListAvailable} -session $all
# reset demo
# Invoke-Command { Uninstall-Module PSFunctionInfo -force} -session $all
# $all | remove-pssession
#endregion
# get a free* ebook at https://leanpub.com/ps7now
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment