Vous êtes sur la page 1sur 2

Windows PowerShell IMPORTANT NAVIGATION COMMANDLETS TURN PAGE

www.scriptrunner.com Get-PSDrive List of drives IGET HELP

Get-Location (pwd) Retrieve current location Get-Command Get- * All commands with „Get-“ PIPELINING
Set-Location (cd) Set current location Get-Command | where mo-
Any number of commandlets can be joined using the pipe symbol |.
dule -like *ActiveDirectory* | All commands of a module
Get-Service a* | Where-Object {$_.status -eq "running"} |
ft Name, Module
INPUT AND OUTPUT COMMANDLETS Get-Item (gi) Get an element Out-File c:\temp\runningservices.txt
Get-Alias Show all aliases
Get-ChildItem (dir, ls, gpi) List all subelements Alternatively, you can store intermediate results in variables starting with $.
Format-Table (ft) Table output $services = Get-Service a* | Where-Object {$_.status -eq "running"}
Retrieve content of an element (e.g. file Get-Help Stop-Process -full Full help content for a command
Get-Content (type, cat, gc) $services | Out-File c:\temp\runningservices.txt
content)
Format-List (fl) Detailed list
Get-Help about List all „About“ documents
COMPARISON OPERATORS Set-Content (sc) Set element content The pipeline forwards NET objects. Forwarding is asynchronous
Format-Wide (fw) Multi-column list (except from some "blocking" commandlets like the sort object)
Get-Help about_WMI Show help for WMI
Add-Content (ac) Add element content
Output to consoles with colour options and Show all properties and methods of the result
Compare case Compare case Out-Host (oh) Get-Service | Get-Member
Meaning paging option objects
in-sensitive sensitive New-Item (ni, mkdir) Create an element (branch or leaf) COMMANDLET #1 COMMANDLET #2 COMMANDLET #3
Out-GridView (ogv) Table with filtering and sorting options
STRINGS AND EXPRESSIONS -lt Get-ItemProperty (gp) Retrieve attribute
-clt Less than
Embedding of a variable in a string
-ilt Out-File Save to file POWERSHELL SCRIPTING LANGUAGE
Define an attribute of an element,
-le Set-ItemProperty (sp)
"The command is $Command!" -cle Less or equal create one if necessary
-ile Out-Printer (lp) Send to printer Condition
Remove-Item
{} must be used here to delimit it from the colon -gt
-cgt Greater than (del, ri, rmdir, rm, erase)
Delete element if ((Get-Date).Year -le 2014) { "Old" } else { "New" }
DATA 
"${Command}: executed successfully" -igt Out-Clipboard Send to clipboard SAVE
-ge Loops
Move-Item (move, mv) Move element DATA
-cge Greater or equal for($i = 1; $i -le 10; $i++) { $i }
The subexpression must be parenthesized in $( ) -ige Out-Speech Speech output (requires module "PSCX")
while($i -le 10) { $i; $i++ }
"$($Result.Count) objects in result set" -eq Copy-Item (copy, cp, cpi) Copy element
-ceq Equal do { $i; $i++ } while ($i -le 10) POWERSHELL PIPELINE PROCESSOR
-ieq Out-Null Objects in pipeline are not passed on
foreach ($p in (Get-Process iexplore)) { $p.Kill() }
Use of the format operator -ne Rename-Item (rni, ren) Rename element
-cne Not equal
Get-Process | % { "{0,-40} uses {1:0,000.00}MB" -f $_.Name, ($_.ws/1MB) -ine Read-Host Read from console
Subroutines with mandatory parameters and optional parameters
} -like Similarity between strings, use of EXAMPLE:
-clike With Navigation Commandlets it's not only possible to operate on the file system function Get-DLL([Parameter(Mandatory=$true)][string]$root,
-ilike wildcards (* and ?) possible Import-CSV Get-Service a* | Where-Object { $_ .status-eq "running" } | Out-File c:\filename.txt
Import / export CSV file (drives A:, B:, C: etc.), but also on other flat and [string]$filter = "*")
Execute a string as a command Export-CSV
-notlike No similarity between strings, use of hierarchical sets like Registry (HKLM:, HKCU:), {
$Command = "Get-Service a*" -cnotlike Commandlet #1:
-inotlike wildcards (* and ?) possible Import-CLIXML Environment (ENV:), Certificate (CERT:), Active Directory (AD:), return Get-ChildItem $root -Filter "$filter.dll"
$Command += "| where status -eq ‚Running‘" Import / export XML file Get-Service a*
-match Export-CLIXML IIS-Webserver (IIS:) etc.: }
$Result = Invoke-Expression $Command -cmatch Compare with regular expression Object of type: System. ServiceProcess. ServiceController
-imatch Get-DLL c:\Windows\System32
$Command | Format-List
-notmatch User defined table output Dir HKLM://software/
-cnotmatch Does not match regular expression Commandlet #2 - Selection:
-inotmatch Get-Process | ft @{Label="Nr"; Expression={$_.ID}; Width=5}, New-Item HKLM://software/ScriptRunner Comment
Where-Object { $_ .status-eq "running" }
Type comparison, e.g. (Get-Date) -is @{Label="Name"; Expression={$_.Processname}; Width=30}, RD HKLM://software/ScriptRunner # This is a comment
-is –
POWERSHELL DATA TYPES [DateTime] @{Label="Memory MB"; Expression={$_.WorkingSet64 / 1MB};
Commandlet #3 - Storage in file system
Width=7; Format="{0:00000.0}"}
-in Out-File c:\filename.txt
Numeric types – Is included in set
[byte]
-contains
POWERSHELL CLASSES ACTIVE DIRECTORY (AD)
-notin
[int] – Is not included in set
[long]
-notcontains CONFIGURING AND USING NETWORKS Implementation of the PowerShell class
Get-ADObject Retrieve arbitrary objects from AD IMPORTANT PIPELINING COMMANDLETS
class User
[single]
{ Get-ADUser
[double] For logical conjunction, -and, -or as well as -not (alias !) are used Get-NetAdapter List network cards (also virtual ones)
# Properties Get-ADGroup Where-Object (where, ?) Filter using conditions
Example: ((1MB + 250 + $ a) -gt 2000KB) -and! ($ A -le 2KB) [int] $ID
Generate random number between 1 and 49 and store in variable $x Get-ADOrganizationalUnit Retrieve particular AD elements Truncate result set from its start/end
KB, MB, GB, TB, and PB are valid units for memory sizes. Get-NetAdapterBinding Properties of a network connection [string] $Name Get-ADDomain Select-Object (select)
[byte] $x = Get-Random -Minimum 1 -Maximum 49 reduction of object attributes, respectively
hidden [Datetime] $CreatedOn Get-ADComputer
Set-NetIPInterface Enable or disable DHCP # Static Property
Character types Sort-Object (sort) Sort objects
Set-ADObject
[char] USING .NET FRAMEWORK CLASSES New-NetIPAddress
static [Int64] $Count
Set-ADUser
Set or remove static IP address Set properties for an object
[string] Remove-NetIPAddress Set-ADGroup Group-Object (group) Group objects
# Constructor
Access to static members Set-ADComputer
Set-DnsClientServerAddress Set or remove DNS server User([int] $newid, [string] $name)
Boolean and date types Foreach-Object { $_... } (%) Loop over all objects
[System.Environment]::MachineName { New-ADUser
[bool]
[System.Console]::Beep(800, 500) Remove-NetRoute Remove gateway from network connection $this.ID = $newid New-ADGroup Create new AD object
[DateTime] Get-Member (gm) Print metadata (reflection)
$this.Name = $name New-ADOrganizationalUnit
Instantiation and access to instance members $this.CreatedOn = Get-Date
Store current date in variable $d Resolve-DnsName Resolve DNS name
$b = New-Object System.Directoryservices.DirectoryEntry Remove-ADObject Delete AD object Measure-Object (measure) Calculation: -min -max -sum -average
[User]::Count = [User]::Count + 1
[Datetime] $d = Get-Date
("WinNT://MyServer/ScriptRunner“) Enable-NetFirewallRule }
Enable or disable a Windows Firewall rule
$b.FullName Disable-NetFirewallRule # Method Rename-ADObject Rename AD object Compare-Object (compare, diff) Compare two sets of objects
Object sets
$b.Description = "PowerShell Automation" [string] GetInfo([bool] $verbose, [string] $separator)
[Array] Test-Connection Perform a ping
$b.SetInfo() { Move-ADObject Move AD object
[Hashtable]
[string] $a = "$($this.ID)$separator$($this.Name)";
Send-MailMessage Send email
Store list of services starting with "a" in variable $services
Load and use additional assembly if ($verbose) { $a += "$separator$($this.CreatedOn)" } Set-ADAccountPassword Set password OBJECT-ORIENTED ACCESS TO PIPELINE OBJECTS
[System.Reflection.Assembly]::LoadWithPartialName("Microsoft.VisualBasic") return $a
[Array] $services = Get-Service a* Invoke-WebRequest HTTP request
$input = [Microsoft.VisualBasic.Interaction]::InputBox("Please enter your } Get-ADGroupMember List group members of an AD group Number of objects in pipeline
name!","Title") # Static Method (Get-Service | where { $_.status -eq "Running" }).Count
More complex data structures New-WebServiceProxy Create a proxy for SOAP-based service static [string] GetCount() Add-ADGroupMember Add member to an AD group
[XML]
{ Print particular properties of pipeline objects
[WMI]
Export-ODataEndpointProxy Create proxy for OData-based service return "In total $([Users]::Count) users!" (Get-Date).DayOfWeek
[ADSI] Remove-ADGroupMember Remove member from an AD group
}} (Get-Process).Name
Use of the PowerShell class (Get-Process | sort ws -desc)[0].Name
$b = [User]::new(123,"Matt Scripter")
CONFIGURING POWERSHELL ACCESS TO WMI $b.ID = 1 PROCESSES, SERVICES, EVENTS, PERFORMANCE Method call in all pipeline objects
$b.Name = "Matt" (Get-Process iexplore | sort ws -desc).Kill()
$b.GetInfo($true,";")
INDICATORS
List of all WMI classes from a namespace of a computer
Set-ExecutionPolicy Unrestricted Allow all PowerShell scripts [User]::GetCount()
Get-CimClass -Namespace root/cimv2 -Computer MyServer
Get-Process Running processes
Set-ExecutionPolicy RemoteSigned / AllSigned Only allow signed PowerShell scripts SOFTWARE INSTALLATION
List all instances of a WMI class on a computer
Start-Process
Get-CimInstance Win32_LogicalDisk -Namespace root/cimv2 -Computer
Enable-PSRemoting -SkipNetworkProfileCheck Enable PowerShell remote access for this machine - even if there are public networks in the surrounding area
MyServer
USING THE COMPONENT OBJECT MODEL (COM) Stop-Process
Start/terminate process
List all types of packages that PowerShell is
Get-PackageProvider able to download and install
(Get-Host).PrivateData.ErrorBackgroundcolor ="White" Change background colour for error messages (increases contrast of red characters) Instantiate a COM class Wait-Process Wait for process to terminate (e.g. Nuget, Chocolatey, MSI)
WQL query on a computer
$ie = New-Object -com "InternetExplorer.Application" Install new package provider
Get-CimInstance -Query "Select * from Win32_Networkadapter where Install-PackageProvider chocolatey
Get-Service Windows system services (of a new package type)
adaptertype like ‘%802%‘" -Computer MyServer
Call method Register-Packagesource -Name
USING MODULES Access to an instance and change to the instance
$ie.Navigate("http://www.scriptrunner.com") Start-Service
chocolatey -Provider chocolatey
Stop-Service Register new package source for
$c = Get-CimInstance Win32_LogicalDisk -Namespace root/cimv2 -Filter Change service state -Trusted -Location
Set property Suspend-Service Chocolatey.org
Get-Module List activated modules "DeviceID=‘C:‘" -Computer MyServer http://chocolatey.org/api/v2/
$ie.visible = $true Resume-Service
$c.VolumeName = "System" -Verbose
Get-module -ListAvailable List all installed modules Set-CimInstance $c Get-EventLog Event log entries
Get-PackageSource List all registered package sources

Import-Module Enable local module for current session Alternatively with old WMI commandlets Write-Eventlog Create entry in event log Find-Package -Name chrome Search package source for software

Find-Module Search modules in PowerShell Gallery


$c = [WMI] "\\MyServer\root\cimv2:Win32_LogicalDisk.DeviceID=‘C:‘" ONLINE RESOURCES -Source chocolatey by specific word in title
$c.VolumeName = "System" Limit-EventLog Set size for event log Install software package
$c.Put() technet.microsoft.com/scriptcenter Install-Package googlechrome "GoogleChrome" from a particular
Install-Module Download and install modules from PowerShell Gallery Retrieve important performance indica-
Get-Counter -Source chocolatey package source
Calling a WMI method blogs.msdn.com/PowerShell tors
Update-Module Update module
Invoke-CimMethod -Path "\\MyServer\root\cimv2:Win32_Computersystem. github.com/ScriptRunner
Get-Counter -ListSet* List all performance indicators Get-PSDrive List all installed packages
Name=MyServer" -Name "Rename" -ArgumentList "MyNewServer"
scriptrunner.blog
© ScriptRunner by AppSphere AG 2018 Get-Counter -Counter
scriptrunner.com Retrieve particular performance indicator Uninstall-Package googlechrome Uninstall a software package
Version: PowerShell 5.0/5.1 (October 2016) "\Processor(_Total)\% ProcessorTime"
with kind permission of Dr. Holger Schwichtenberg: www.dotnet-doktor.de
 by AppSphere AG | www.scriptrunner.com
ASR\Administrator(Kerberos)

Open the submenu here Meta Menu includes links to social channels, ScriptRunner blog, and other information.
You can contact ScriptRunner support, directly select the UI language, and view the log-in user name.
ActiveDirectory x Global Filter Tags

Number of filtered elements Tag filter filters the list view by tag names

Filter: 67 -> 3 Search by action names, characters, tag names

 ActiveDirectory

Multiple selection with Status icons selected,


Sortable columns with additional information and star rating.
CTRL and left mouse button delegated, scheduled, error.

ACTIONS QUERIES TARGETS CREDENTIALS SCRIPTS

An action is a policy set for the controlled The result of a query consists of a correspon- Use ‚single target‘ for VMs, online services, The execution of scripts takes place in a Use script header information to describe the
execution of a PowerShell script on a target ding list of display and parameter values for components, and clients. A ‚container target‘ dedicated permission context. The credentials input fields and the script‘s function. Define
system. The guidelines determine who is all- a referenced PowerShell input parameter. contains a collection of single targets. For control the process in a Run As mode. the input parameters in the param block.
owed to start which script, in which context it Queries can be cascaded and start automati- Azure AD, ExOnline, SPOnline, S4BOnline, Use type definitions and param options.
is to be executed, and which inputs are neces- cally, can run in realtime, be scheduled, or run and others, use the ‚Office365 service‘ target. Positioning mandatory parameters at the top.
sary for execution. The following are assigned from cache. They support interactive search AUTOMATION After that, write all functions.
to an action: the script to be executed, the and the selection with a dropdown. Use local execution with FQDN ‚.‘ to execute Use a main section with the logical program
input parameters and corresponding queries, the script on ScriptRunner Host. To commu- To automate IT operations, you can start path and the handling of possible errors (try-
the target system, the credentials for executing You can use different types of queries: a static nicate over PowerShell remoting port 5985 ScriptRunner actions from third-party systems catch). Put details with ‚write-output‘ to the
the script on the target system, further settings list of entries, a static or dynamically generated and 5986 (SSL), PowerShell remoting must be such as monitoring, ITSM, or workflows. PowerShell output stream and use ‚out-file‘
for the PowerShell, scheduling and notificati- file, dynamic query to AD, or a query script. enabled on target and the firewall rules confi- You can use the Web service and the email for extensive reports.
ons, and also the delegation settings. You can query the AD for OUs, users, groups, gured correctly. Set the correct credential and inbound connector to do this. The third party Fill out the variable SRXEnv.ResultMessage with
Select an action and click on button in the members, member of, computers, printers or authentification option for remoting. system must authenticate itself to ScriptRunner a short summary or error message to display
admin app to configure and test it. You can by object type or with a LDAP string. In addi- To manage Exchange Server, you should use using the corresponding connector. Only it in the delegate app and add it to the result
then use the Delegate App to enter the tion, you can set search base, attribute filters, the type Exchange PowerShell with the option actions assigned to the connector can be section of the report. Develop scripts with the
parameter values and start the configured display and parameter value presentation. implicit remoting (equal to ‚import-pssession’). called and executed. ScriptRunner ISE App or other IDE. Upload or
action. sync scripts with Git, TFS, or svn.

CONTEXTUAL ACTION BAR IN MAIN MENU ACTIONS


DELEGATION REPORTS
Reload the data and refresh views. You can securely delegate ScriptRunner The metadata and parameter section displays
Create an new action, select the script and target, set PowerShell
actions to groups or individual users. The the context in order to execute the script. The
options, schedule, notification and delegation options.
settings for action name, tabs, and colors in Result/Error section shows the value of
Edit settings of the selected action(s). With multiselection, you can change tags
the Delegate App can be controlled for each $SRXenv.ResultMessage or an error message.
and delegation settings for all selected actions.
Delete the selected action(s).
action separately. The last report section shows the PowerShell
Copy a selected action and change it with Edit. output stream as on the console.
The Action details view shows the whole tree of elements that Auto generated WebForms
Example in Delegate App ->
are used for an action. You can edit and run the action as well as edit used ele-
ments directly.
Set a Schedule for a selected action.
Delegate an action to groups in the operator or user role. CONTEXTUAL HELP
Run a selected action, put in the parameters and starts.
Use Cancel to breaks up the selected running action.
One click opens the detailed help for the
The PowerShell process will be ended. Otherwise, you can use the execution settings in the administrator app. The
timeout option of the action. information is sorted according to the topics
Reports opens all reports in the reporting view for the selected action. You can of the main menu and the functional areas.
scroll through reports, compare them, or use the differential view. You can also
send, save, and copy the reports to the clipboard. EYE OF OSIRIS
Dashboard sets the action filter in the dashboard and jumps to the dashboard Interactive display for running actions. When
view. You can add additional filters to enable a fast drill-down. Use different you click on it, a display with a short status of
dashboard views such as single, daily timelines, table view, etc.
the last actions appears.

Vous aimerez peut-être aussi