ScriptRunner PowerShell Poster 2020 en
ScriptRunner PowerShell Poster 2020 en
www.scriptrunner.com
CONFIGURING POWERSHELL EXCHANGE ONLINE INPUT AND OUTPUT COMMANDLETS CONFIGURING AND USING NETWORKS ACTIVE DIRECTORY
Set-ExecutionPolicy Unrestricted Unrestricted allow all PowerShell scripts Connect-ExchangeOnline Establish connection Format-Table (ft) Table output Get-NetAdapter List network cards (also virtual ones) Get-ADObject Retrieve arbitrary objects from AD
Set-ExecutionPolicy RemoteSigned / AllSigned Only allow signed PowerShell scripts Format-List (fl) Detailed list Get-NetAdapterBinding Properties of a network connection Get-ADUser Retrieve particular AD elements
Get-ExoMailbox -Resultsize Unlimited Retrieve specific Exchange Get-ADGroup
Enable-PSRemoting -SkipNetworkProfileCheck Enable PowerShell remote access for this machine - even if there are public networks Get-ExoMailbox | Get-ExoMailboxStatistics Online elements Format-Wide (fw) Multi-column list Set-NetIPInterface Enable or disable DHCP Get-ADOrganizationalUnit
Get-Recipient Get-ADDomain
(Get-Host).PrivateData.ErrorBackgroundcolor ='White' Change background colour for error messages (increases contrast of red characters) Get-DistributionGroup Out-Host (oh) Output to consoles with colour options and paging option New-NetIPAddress Set or remove static IP address Get-ADComputer
Get-MailboxPermission Remove-NetIPAddress
Get-TransportRule Out-GridView (ogv) Table with filtering and sorting options Set-ADObject Set properties for an object
USING MODULES Set-DnsClientServerAddress Set or remove DNS server Set-ADUser
Get-Mailbox –ResultSize Unlimited | Where Retrieve mailboxes with Out-File Save to file Set-ADGroup
{$_.GrantSendOnBehalfTo -ne $null} | "send on behalf" Remove-NetRoute Remove gateway from network connection Set-ADComputer
Get-Module List activated modules
Select UserprincipalName, configured Out-Printer (lp) Send to printer
GrantSendOnBehalfTo Resolve-DnsName Resolve DNS name New-ADUser Create new AD object
Get-Module -ListAvailable List all installed modules
Out-Clipboard Send to clipboard New-ADGroup
Set-Mailbox Configure specific Ex- Enable-NetFirewallRule Enable or disable a Windows Firewall rule New-ADOrganizationalUnit
Import-Module Enable local module for current session
Set-MailboxPermission change Online elements Out-Speech Speech output (requieres module “PSCX”) Disable-NetFirewallRule
Set-TransportRule Remove-ADObject Delete AD object
Find-Module Search modules in PowerShell Gallery
Set-MailboxAutoReplyConfiguration Out-Null Objects in pipeline are not passed on Test-Connection Perform a ping
Rename-ADObject Rename AD object
Install-Module Download and install modules from PowerShell Gallery
New-Mailbox Create new Exchange Read-Host Read from console Send-MailMessage Send email
New-DistributionGroup Online elements Move-ADObject Move AD object
Update-Module Update module
New-TransportRule Import-CSV Import/ export CSV file Invoke-WebRequest HTTP request
Export-CSV Set-ADAccountPassword Set password
USING .NET FRAMEWORK CLASSES OBJECT-ORIENTED ACCESS TO PIPELINE OBJECTS New-Mailbox -Shared -Name 'Sales Dept' Create a shared Exchange New-WebServiceProxy Create a proxy for SOAP-based service
-DisplayName 'Sales Department' Online mailbox Import-CLIXML Import/ export XML file Get-ADGroupMember List group members of an AD group
Export-CLIXML Export-ODataEndpoint-Proxy Create a proxy for OData-based service
Access to static members Number of objects in pipeline Remove-Mailbox Delete Exchange Add-ADGroupMember Add member to an AD group
[System.Environment]::MachineName (Get-Service | where { $_.status -eq 'Running' }).Count Online mailbox
[System.Console]::Beep(800, 500)
User defined table output
ACCESS TO WMI Remove-ADGroupMember Remove member from an AD group
Get-Process | ft @{Label='Nr'; Expression={$_.ID}; Width=5},
Print particular properties of pipeline objects *requires ExchangeOnlineManagement module @{Label='Name'; Expression={$_.Processname}; Width=30},
Instantiation and access to instance members (Get-Date).DayOfWeek
$b = New-Object System.Directoryservices.DirectoryEntry (Get-Process).Name
@{Label='Memory MB'; Expression={$_.WorkingSet64 / 1MB}; List of all WMI classes from a namespace of a computer PIPELINING
Width=7; Format='{0:00000.0}'} Get-CimClass -Namespace root/cimv2 -Computer MyServer
('WinNT://MyServer/ScriptRunner') (Get-Process | sort ws -desc)[0].Name
$b.FullName
List all instances of a WMI class on a computer Any number of commandlets can be joined using the pipe symbol |.
$b.Description = 'PowerShell Automation' Method call in all pipeline objects POWERSHELL 7 Get-CimInstance Win32_LogicalDisk -Namespace root/cimv2 -Computer Get-Service a* | Where-Object {$_.status -eq 'running'} |
$b.SetInfo() (Get-Process iexplore | sort ws -desc).Kill()
MyServer Out-File c:\temp\runningservices.txt
Load and use additional assembly The PowerShell 7 GitHub Repository https://github.com/PowerShell/PowerShell WQL query on a computer Alternatively, you can store intermediate results in variables starting with $.
[System.Reflection.Assembly]::LoadWithPartialName('Microsoft.VisualBasic')
Get-CimInstance -Query "Select * from Win32_Networkadapter where $services = Get-Service a* | Where-Object {$_.status -eq 'running'}
$input = [Microsoft.VisualBasic.Interaction]::InputBox('Please enter your iex "& { $(irm https://aka.ms/install-powershell.ps1) } -UseMSI" Installs the latest PowerShell 7 version on a Windows machine adaptertype like '%802%'" -Computer MyServer $services | Out-File c:\temp\runningservices.txt
Name!','Title')
ForEach-Object -Parallel -ThrottleLimit 10 Parallel execution of pipeline output Access to an instance and change to the instance The pipeline forwards .NET objects. Forwarding is asynchronous
$c = Get-CimInstance Win32_LogicalDisk -Namespace root/cimv2 -Filter
STRINGS AND EXPRESSIONS POWERSHELL SCRIPTING LANGUAGE Import-Module AzureAD -UseWindowsPowerShell Runs cmdlets of the imported module in a Windows PowerShell process. "DeviceID='C:'" -Computer MyServer
(except from some "blocking" commandlets like the sort object)
Set-CimInstance $c
$x = $null The null-coalescing operator ?? returns the value of its left-hand operand if it isn’t null. COMMANDLET #1 COMMANDLET #2 COMMANDLET #3
Embedding of a variable in a string Condition
"The command is $Command!" if ((Get-Date).Year -le 2014) { 'Old' } else { 'New' } $x ?? 100 Otherwise, it evaluates the right-hand operand and returns its result. Alternatively with old WMI commandlets
Output: 100 $c = [WMI] "\\MyServer\root\cimv2:Win32_LogicalDisk.DeviceID='C:'"
{} must be used here to delimit it from the colon Loops $c.Put()
"${Command}: executed successfully" for($i = 1; $i -le 10; $i++) { $i } Get-ChildItem -Path 'application.log" || New-Item -Path 'application.log' Pipeline chain operator "||" executes the right-hand pipeline if the left-hand pipeline failed.
while($i -le 10) { $i; $i++ } Calling a WMI method DATA
Get-ChildItem -Path 'C:\temp' && Copy-Item 'test.txt' -Path 'C:\temp' Pipeline chain operator "&&" executes the right-hand pipeline if the left-hand pipeline Invoke-CimMethod -Path "\\MyServer\root\cimv2:Win32_Computersystem. SAVE
The subexpression must be parenthesized in $( ) do { $i; $i++ } while ($i -le 10) DATA
"$($Result.Count) objects in result set" foreach ($p in (Get-Process iexplore)) { $p.Kill() } succeeded. Name=MyServer" -Name 'Rename' -ArgumentList 'MyNewServer'
$IsWindows ? 'yes' : 'no' Ternary operator "?" evaluates the condition POWERSHELL PIPELINE PROCESSOR
Use of the format operator Subroutines with mandatory parameters and optional parameters
Get-Process | % { '{0,-40} uses {1:0,000.00}MB' -f $_.Name, ($_.ws/1MB) function Get-DLL([Parameter(Mandatory=$true)][string]$root, Expression to execute if the condition is true, followed by ":" PROCESSES, SERVICES, EVENTS, PERFORMANCE
} [string]$filter = '*') EXAMPLE:
{ $ErrorView = 'ConsiseView' Improves the readability of interactive and script errors Get-Service a* | Where-Object { $_.status -eq 'running' } | Out-File c:\file-
Get-Process Running processes
Execute a string as a command return Get-ChildItem $root -Filter "$filter.dll" name.txt
$Command = 'Get-Service a*' }
$Command += "| where status -eq 'Running'" Get-DLL c:\Windows\System32 SPLATTING COMPARISON OPERATORS Start-Process Start/terminate process
Commandlet #1:
Stop-Process
$Result = Invoke-Expression $Command Get-Service a*
$Command | Format-List Comment $params = @{ Splatting is a technique to pass a collection of Object of type: System. ServiceProcess. ServiceController
Compare case Compare case Meaning Wait-Process Wait for process to terminate
$Result | Format-List # This is a comment parameter values to a command using a single in-sensitive sensitive
ParameterName1 = 'Value1' variable instead of sending them as separate Commandlet #2 - selection:
Get-Service Windows system services
arguments. -lt -clt Less than Where-Object { $_.status -eq 'running' }
POWERSHELL DATA TYPES ParameterName2 = 'Value2' -ilt Start-Service Change service state
Commandlet #3 - storage in file system:
Benefits: Stop-Service
ParameterName3 = 'Value3' -le -cle Less or equal Out-file c:\filename.txt
[byte] Numeric types [Datetime] $d = Get-Date Store current date in variable $d Better readability Suspend-Service
-ile Resume-Service
[int] } Improved reusability
[long] [Array] Object sets Conditionally adding parameter
-gt -cgt Greater than Get-WinEvent Event log entries
IMPORTANT PIPELINING COMMANDLETS
[single] [Hashtable] Get-Something @params -igt
[double]
[Array] $services = Get-Service a* Store list of services starting with "a" in variable $services New-WinEvent Create entry in event log Where-Object (where, ?) Filter using conditions
-ge -cge Greater or equal
[byte] $x = Get-Random Generate random number between
$params = @{
Setting up a list of parameters for the Get- -ige Limit-EventLog Set size for event log
-Minimum 1 -Maximum 49 1 and 49 and store in variable $x [XML] More complex data structures Select-Object (select) Truncate result set from its start/end
ChildItem cmdlet. If a specific condition is met,
[WMI] reduction of object attributes, respectively
Path = 'C:\ProgramData\ it adds the -Recurse parameter to retrieve items -eq -ceq Equal Get-Counter Retrieve important performance indicators
[char] Character types [ADSI]
ScriptRunner\Service' from the specified directory and all its subdirec- -ieq
[string] Sort-Object (sort) Sort objects
tories; otherwise, it retrieves items only from the
[psobject].Assembly.GetType A complete list of TypeAccelerators is accessible Get-Counter -ListSet * List all performance indicators
} specified directory. -ne -cne Not equal
[bool] Boolean and date types ('System.Management.Automation. Group-Object (group) Group objects
if(<condition>) { -ine Get-Counter -Counter Retrieve particular performance indicator
[DateTime] TypeAccelerators')::Get
'\Processor(_Total)\% Foreach-Object { $_... } (%) Loop over all objects
$params.Add('Recurse', $true) -like -clike Similarity between strings, use of ProcessorTime'
-ilike wildcards (* and ?) possible
SECRET MANAGEMENT MODULE } Get-Member (gm) Print metadata (reflection)
Get-ChildItem @params
-notlike -cnotlike No similarity between strings, use of GET HELP Measure-Object (measure) Calculation: -min -max -sum -average
Install-Module -Name Microsoft.PowerShell.SecretManagement Install the Secret Management module -inotlike wildcards (* and ?) possible
Install the Secret Store module Get-Command Get-* All commands with "Get-" Compare-Object (compare, diff) Compare two sets of objects
Install-Module -Name Microsoft.PowerShell.SecretStore -match -cmatch Compare with regular expression
-imatch
Register-MySecretVault -Name SecretStore -ModuleName Microsoft.PowerShell.SecretStore -DefaultVault Register a local secret vault Get-Command -Module All commands of a module
-notmatch -cnotmatch Does not match regular expression *ActiveDirectory* | Format-
Get-SecretVault Show current secret vaults Table Name, Module
MORE ON POWERSHELL
-inotmatch
Get-SecretStoreConfiguration Show secret store configuration
-is - Type comparison, e.g. (Get-Date) -is Get-Alias Show all aliases
Get-SecretInfo Show list of existing secrets [DateTime] DISCOVER MORE POWERSHELL
Get-Help Stop-Process -full Full help content for a command
CHEAT SHEETS HERE:
POWERSHELL SECURITY E-BOOK POWERSHELL SCRIPT COLLECTION
Get-Secret -Name MySecret Show details of a secret -in - Is included in set
Click here for e-book Click here for ActionPacks -contains Get-Help about List all "About" documents
Set-Secret Create a new secret
-notin - Is not included in set Get-Help about_WMI Show help for WMI POWERSHELL EXCHANGE CHEAT SHEET POWERSHELL TEAMS CHEAT SHEET
Set-Secret -Name 'NewCred001' -Secret (Get-Credential '[email protected]') Create a new PSCredential secret SCRIPTRUNNER BLOG POWERSHELL WEBINARS -notcontains
Get-Service | Get-Member Show all properties and methods Click here for cheat sheet Click here for cheat sheet
Set-SecretStoreConfiguration Set secret store configuration of the result objects
Click here for the blog Click here for webinars For logical conjunction, -and, -or as well as -not (alias !) are used
Example: ((1MB + $a + $b) -gt 2000KB) -and !($a -le 2KB)
© ScriptRunner Software GmbH | Kindly supported by Dr. Holger Schwichtenberg: www.dotnet-doktor.de KB, MB, GB, TB, and PB are valid units for memory sizes.