ScriptRunner PowerShell Poster 2020 - EN
ScriptRunner PowerShell Poster 2020 - EN
ScriptRunner PowerShell Poster 2020 - EN
www.scriptrunner.com
GET HELP
TURN PAGE
Get-Command Get- * All commands with „Get-“
STRINGS AND EXPRESSIONS Output to consoles with colour options and COMMANDLET #1 COMMANDLET #2 COMMANDLET #3
Compare case Compare case
Meaning
Out-Host (oh)
paging option
Get-Item (gi) Get an element POWERSHELL SCRIPTING LANGUAGE
in-sensitive sensitive
Embedding of a variable in a string Get-ChildItem (dir, ls, gci) List all subelements
"The command is $Command!" Condition
-lt if ((Get-Date).Year -le 2014) { "Old" } else { "New" }
-clt Less than Get-Content (type, cat, gc)
{} must be used here to delimit it from the colon -ilt Out-File content)
"${Command}: executed successfully" -le Loops
-cle Less or equal DATA
-ile Out-Printer (lp) Send to printer Set-Content (sc) Set element content for($i = 1; $i -le 10; $i++) { $i }
The subexpression must be parenthesized in $( ) while($i -le 10) { $i; $i++ }
-gt DATA
-cgt Greater than Add-Content (ac) Add element content do { $i; $i++ } while ($i -le 10)
"$($Result.Count) objects in result set" -igt Out-Clipboard Send to clipboard
foreach ($p in (Get-Process iexplore)) { $p.Kill() }
-ge
Use of the format operator -cge Greater or equal New-Item (ni, mkdir) Create an element (branch or leaf) POWERSHELL PIPELINE PROCESSOR
-ige Out-Speech Speech output (requires module "PSCX")
Get-Process | % { "{0,-40} uses {1:0,000.00}MB" -f $_.Name, ($_.ws/1MB) Subroutines with mandatory parameters and optional parameters
-eq function Get-DLL([Parameter(Mandatory=$true)][string]$root,
} -ceq Equal Out-Null Objects in pipeline are not passed on Get-ItemProperty (gp) Retrieve attribute
-ieq
EXAMPLE:
Execute a string as a command -ne {
-cne Not equal Read-Host Read from console Set-ItemProperty (sp) -
-ine create one if necessary
$Command = "Get-Service a*" name.txt
$Command += "| where status -eq ‚Running‘" -like Similarity between strings, use of Remove-Item }
-clike Delete element Get-DLL c:\Windows\System32
$Result = Invoke-Expression $Command -ilike wildcards (* and ?) possible (del, ri, rmdir, rm, erase) Commandlet #1:
$Command | Format-List -notlike No similarity between strings, use of Get-Service a*
-cnotlike Import-CLIXML Move-Item (move, mv) Move element Comment
$Result | Format-List -inotlike wildcards (* and ?) possible Object of type: System. ServiceProcess. ServiceController
Export-CLIXML # This is a comment
-match Copy-Item (copy, cp, cpi) Copy element
-cmatch Compare with regular expression
-imatch Commandlet #2 - Selection:
POWERSHELL DATA TYPES Where-Object { $_ .status-eq "running" }
-notmatch Get-Process | ft @{Label="Nr"; Expression={$_.ID}; Width=5}, Rename-Item (rni, ren) Rename element
-cnotmatch Does not match regular expression
Numeric types -inotmatch @{Label="Name"; Expression={$_.Processname}; Width=30},
ACTIVE DIRECTORY (AD) *requires Module Active Directory
[byte] Type comparison, e.g. (Get-Date) -is @{Label="Memory MB"; Expression={$_.WorkingSet64 / 1MB};
-is –
[int] [DateTime] Width=7; Format="{0:00000.0}"} Get-ADObject Retrieve arbitrary objects from AD
system
[long] -in
– Is included in set
[single] -contains
hierarchical sets like Registry (HKLM:, HKCU:),
Get-ADUser IMPORTANT PIPELINING COMMANDLETS
[double] -notin Get-ADGroup
-notcontains
– Is not included in set CONFIGURING AND USING NETWORKS Get-ADOrganizationalUnit Retrieve particular AD elements
IIS-Webserver (IIS:) etc.: Where-Object (where, ?) Filter using conditions
Generate random number between 1 and 49 and store in variable $x Get-ADDomain
[byte] $x = Get-Random -Minimum 1 -Maximum 49 Get-NetAdapter List network cards (also virtual ones) Get-ADComputer Truncate result set from its start/end
Dir HKLM://software/ Select-Object (select)
For logical conjunction, -and, -or as well as -not (alias !) are used New-Item HKLM://software/ScriptRunner Set-ADObject reduction of object attributes, respectively
Character types Example: ((1MB + 250 + $ a) -gt 2000KB) -and! ($ A -le 2KB) Get-NetAdapterBinding Properties of a network connection RD HKLM://software/ScriptRunner Set-ADUser
[char] KB, MB, GB, TB, and PB are valid units for memory sizes. Set properties for an object Sort-Object (sort) Sort objects
Set-ADGroup
[string]
Set-NetIPInterface Enable or disable DHCP Set-ADComputer
Group-Object (group) Group objects
Boolean and date types USING .NET FRAMEWORK CLASSES New-NetIPAddress New-ADUser
[bool] Set or remove static IP address New-ADGroup
Remove-NetIPAddress POWERSHELL CLASSES New-ADOrganizationa-
Create new AD object Foreach-Object { $_... } (%) Loop over all objects
[DateTime] Set-DnsClientServerAd-
Access to static members Set or remove DNS server lUnit
[System.Environment]::MachineName dress Implementation of the PowerShell class Get-Member (gm)
Store current date in variable $d
[System.Console]::Beep(800, 500) class User Remove-ADObject Delete AD object
[Datetime] $d = Get-Date Remove-NetRoute Remove gateway from network connection Measure-Object (measure) Calculation: -min -max -sum -average
{
Instantiation and access to instance members # Properties Rename-ADObject Rename AD object
Object sets Resolve-DnsName Resolve DNS name Compare-Object (compare,
$b = New-Object System.Directoryservices.DirectoryEntry [int] $ID Compare two sets of objects
[Array] diff)
("WinNT://MyServer/ScriptRunner“) Enable-NetFirewallRule [string] $Name Move-ADObject Move AD object
[Hashtable] Enable or disable a Windows Firewall rule
$b.FullName Disable-NetFirewallRule hidden [Datetime] $CreatedOn
$b.Description = "PowerShell Automation" # Static Property
Store list of services starting with "a" in variable $services Set-ADAccountPassword Set password
[Array] $services = Get-Service a*
$b.SetInfo() Test-Connection Perform a ping static [Int64] $Count OBJECT-ORIENTED ACCESS TO PIPELINE OBJECTS
Get-ADGroupMember List group members of an AD group
Load and use additional assembly Send-MailMessage Send email # Constructor Number of objects in pipeline
More complex data structures
- User([int] $newid, [string] $name) (Get-Service | where { $_.status -eq "Running" }).Count
[XML] Add-ADGroupMember Add member to an AD group
sic") Invoke-WebRequest HTTP request {
[WMI]
$this.ID = $newid Print particular properties of pipeline objects
[ADSI] Remove-ADGroupMember Remove member from an AD group
name!","Title") New-WebServiceProxy Create a proxy for SOAP-based service $this.Name = $name (Get-Date).DayOfWeek
$this.CreatedOn = Get-Date (Get-Process).Name
A complete list of TypeAccelerators is accessible with: Export-ODataEndpoint-
Create proxy for OData-based service [User]::Count = [User]::Count + 1 (Get-Process | sort ws -desc)[0].Name
[psobject].Assembly.GetType(‘System.Management.Automation. Proxy }
TypeAccelerators’)::Get PROCESSES, SERVICES, EVENTS, PERFORMANCE
# Method Method call in all pipeline objects
[string] GetInfo([bool] $verbose, [string] $separator) INDICATORS (Get-Process iexplore | sort ws -desc).Kill()
{
CONFIGURING POWERSHELL ACCESS TO WMI [string] $a = "$($this.ID)$separator$($this.Name)";
if ($verbose) { $a += "$separator$($this.CreatedOn)" } Get-Process Running processes
List of all WMI classes from a namespace of a computer
Set-ExecutionPolicy Unrestricted Allow all PowerShell scripts return $a SOFTWARE INSTALLATION
Get-CimClass -Namespace root/cimv2 -Computer MyServer Start-Process
} Start/terminate process
Set-ExecutionPolicy RemoteSigned / AllSigned Only allow signed PowerShell scripts # Static Method Stop-Process
List all instances of a WMI class on a computer List all types of packages that
static [string] GetCount() Get-PackageProvider PowerShell is able to download and
Get-CimInstance Win32_LogicalDisk -Namespace root/cimv2 -Computer Wait-Process Wait for process to terminate
Enable PowerShell remote access for this machine - even if there are public networks { install (e.g. Nuget, Chocolatey, MSI)
MyServer
return "In total $([Users]::Count) users!"
Get-Service Windows system services Install-PackageProvider choco- Install new package provider
(Get-Host).PrivateData.ErrorBackgroundcolor ="White" Change background colour for error messages (increases contrast of red characters) }}
WQL query on a computer latey (of a new package type)
Use of the PowerShell class Start-Service
Get-CimInstance -Query "Select * from Win32_Networkadapter where Register-Packagesource -Name
$b = [User]::new(123,"Matt Scripter") Stop-Service
adaptertype like ‘%802%‘" -Computer MyServer Change service state chocolatey -Provider chocolatey
$b.ID = 1 Suspend-Service Register new package source for
-Trusted -Location
USING MODULES Access to an instance and change to the instance
$b.Name = "Matt" Resume-Service http://chocolatey.org/api/v2/
Chocolatey.org
$b.GetInfo($true,";")
$c = Get-CimInstance Win32_LogicalDisk -Namespace root/cimv2 -Filter
[User]::GetCount() Get-Win Event Event log entries
Get-Module List activated modules "DeviceID=‘C:‘" -Computer MyServer
Get-PackageSource List all registered package sources
Get-Module -ListAvailable List all installed modules Set-CimInstance $c New-WinEvent Create entry in event log
Find-Package -Name chrome Search package source for software
-Source chocolatey
Import-Module Enable local module for current session Alternatively with old WMI commandlets ONLINE RESOURCES Limit-EventLog Set size for event log
$c = [WMI] "\\MyServer\root\cimv2:Win32_LogicalDisk.DeviceID=‘C:‘" Install software package
Find-Module Search modules in PowerShell Gallery Retrieve important performance Install-Package googlechrome
technet.microsoft.com/scriptcenter Get-Counter "GoogleChrome" from a particular
indicators -Source chocolatey
$c.Put() package source
Install-Module Download and install modules from PowerShell Gallery blogs.msdn.com/PowerShell
Get-Counter -ListSet * List all performance indicators
Calling a WMI method github.com/ScriptRunner Get-Package List all installed packages
Update-Module Update module
Invoke-CimMethod -Path "\\MyServer\root\cimv2:Win32_Computersys- Get-Counter -Counter
scriptrunner.com/blog Retrieve particular performance indi-
tem. "\Processor(_Total)\% Processor- Uninstall-Package googlechrome Uninstall a software package
cator
© ScriptRunner Software GmbH Name=MyServer" -Name "Rename" -ArgumentList "MyNewServer" scriptrunner.com Time"
Filter: 67 -> 3
ActiveDirectory
+ Team