Day1:
Commands as well as notes:
Advice: Always READ the Description close each ascendance that y'all run, to brand sure enough y'all empathize what the ascendance does!
We tin re-create the commands inwards the History department as well as re-create them inwards ISE, to ameliorate empathize them!
The ascendance below volition give us the condition of the stopped services on the Windows box:
Anatomy of a PowerShell Command
Help inwards PowerShell
Other Helpful Commands as well as Techniques
Objects as well as the Pipeline
Formatting inwards PowerShell
Command Basics:
- all commands should travel using a format of 'Verb-noun'
- Do Something - To Something
- Get-Verb
Day2:
-- -----------
1 get-verb
2 get-verb -verb S*
three cls
iv get-service -Name M* -ComputerName Client1,DC01
five get-service -Name M* -ComputerName Win81Pro
6 get-service -Name M* -ComputerName Client1,DC01
vii get-help
8 aid get-service -full
ix aid *about*
10 aid about_aliases
11 update-help
12 cls
13 larn -command
14 aid get-command
15 cls
16 get-command - examples
17 get-command - examples,...
18 aid get-command -examples
19 get-command -type cmdlet
20 get-command -type New
21 get-command -verb New
example:
get-service | where-object condition -eq "Stopped" | out-file c:\scripts\services.txt
PowerShell Data every bit Objects:
Property Property Property
^ ^ ^
Name DisplayName Status
spooler Print Spooler Running <-- Object
wuauserv Windows Update Stopped <-- Object
get-service | get-member
get-service | get-member | more
get-service | select-object Name,Status
get-service | select-object Name,Status| out-file c:\scripts\services.txt
get-service | where-object condition -eq "stopped"
get-service | where-object condition -eq "stopped"| Format-List
get-service|format-list|more
get-service|fl Name,Status|more
get-service|format-table
get-service|format-table -AutoSize
get-service|format-table -Wrap
get-service|format-table -Wrap -autosize
get-service|FT -wrap Name,Status
get-service|FT -wrap Name,Status
get-service|Out-GridView
Day3:
Gathering Information alongside PowerShell:
Troubleshooting Steps:
Identify the Issues
Find Root Cause
Determine as well as Implement a Solution
Verify Results
Always apply in 1 lawsuit solution at a time! Don't apply to a greater extent than than 1 solution to the issue!
Related to:
Computer as well as Hardware
Networking
Registry
Files as well as Printers
Active Directory Objects
Process:
Gathering Info Process - will exercise the Get-Command (to detect the ascendance that nosotros are looking for) - Help (to read close the commands as well as examples of the command) - and when nosotros wishing to lay a sure enough information from an object, nosotros volition use Get-Member.
For most commands nosotros volition travel using Get-Verb.
In social club to larn information close the Operating System y'all demand access to the Windows Management Instrumentation (WMI) - Get-WMIobject.
Common Information Model (CIM) - Get-CimInstance
When nosotros access WMI Information, nosotros access the WMI Repository. In at that topographic point nosotros have CIMv2, WIN32_Processor, Device ID and Name.
Gathering Operating System as well as Hardware Information alongside PowerShell:
Get-Counter
Get-WMIObject
Get-CIMInstance
Get-EventLog
- to troubleshoot an number alongside a user's figurer slowness
Check committed memory:
get-command *counter*
- Get-Counter
- Get-Counter -listset *memory*
- Get-Counter -listset *memory* | where CounterSetName -eq 'Memory'
- Get-Counter -listset *memory* | where CounterSetName -eq 'Memory' |select -expand Paths
- Get-Counter "\memory\% Committed Bytes inwards use"
- Get-CIMInstance WIN32_PhysicalMemory
Check difficult drive:
- Get-CimClass -ClassName *disk*
- Get-WmiObject -Class Win32_logicaldisk (this brings dorsum the local disks information)
Check organisation BIOS:
- Get-CimClass *BIOS*
- Get-WMIObject Win32_BIOS
- Get-CimInstance Win32_BIOS (we larn the same information every bit alongside the ascendance higher upwards it)
or:
- Get-CimInstance Win32_BIOS |select Name,Version
Check the final fourth dimension the organisation was rebooted:
- gcm *event*
- aid Get-EventLog
- help Get-EventLog -Examples
We volition travel looking through the latest K events, at an eventID of -1074, to run into the final fourth dimension the organisation rebooted:
- Get-EventLog -log organisation -newest K | where-object eventid -eq '1074' | format-table machinename, username, timegenerated -autosize
Gathering Networking Information:
Ipconfig
Get-NetIPAddressConfiguration
Get-SMBMapping
New-SMBMapping
IPConfig:
- GCM *IP* (we volition select the best command)
- Get-NetIpAddress
- Get-NetIPConfiguration
Troubleshoot DNS:
- we await for DNS customer commands
- help get-DNSclient
- get-DNSClient
- get-DNSclientServerAddress
- Get-DNSClientCache
Mapping a network drive:
- GCM *SMB*
- aid Get-SMBMapping -Examples
- Get-SMBMapping
- aid new-smbMapping
- help new-smbMapping -Examples
- New-SMBMapping - LocalPath S: -RemotePath \\DC01\Shares
- Get-SMBMapping
Test Network Connections:
- ping 4.2.2.1
- tracert 4.2.2.1
- Test-NetConnection 4.2.2.1
- Test-NetConnection 4.2.2.1 -TraceRoute
- Test-NetConnection -CommonTCPPort HTTP -ComputerName cnn.com
Gathering Registry Information alongside PowerShell:
Get-PSProvider
Get-Item
Get-ItemProperty
Get-ItemProperty
- aid Get-PSProvider
- Get-PSProvider
- Set-Location HKLM:
PS HKLM:\> dir
PS HKLM:\> cd software
PS HKLM:\> set-ItemProperty -Path .\WiredCoffee -Name PackageInstalled -Value 0
(you powerfulness demand Administrator permisions)
Run As Admin:
sl hklm:\software
PS HKLM:\> Set-ItemProperty -Path .\WiredCoffee -Name PackageInstalled -value 0
PS HKLM:\> Get-Item .\WiredCoffee
Working alongside Files as well as Printers:
Working alongside File as well as Printers inwards PowerShell:
- Get-ChildItem
- Copy-Item
- Move-Item
- Rename-Item
- Get-Printer
- Add-Printer
- Remove-Printer
You are looking for a file stored on a network drive, without knowing the name, but solely knowing the file type:
- aid Get-ChildItem
- aid Get-ChildItem -Examples
- Get-ChildItem
- Get-ChildItem -path M:\ -Recurse
- Get-ChildItem -path M:\ -Recurse -Include *.PNG
Now nosotros demand to re-create the establish file locally:
- gcm *copy*
- aid Copy-Item
- help Copy-Item -Examples
- copy-item m:\DesktopBackgrounds -Destination c:\Backgrounds -Recurse -Verbose
- Get-ChildItem c:\
- Get-ChildItem c:\BackGrounds -Recurse
Move the folder to some other folder inwards the C: drive:
- Move-Item c:\Backgrounds -Destination c:\MovedFolder -Verbose
- Get-childItem C:\
- Get-ChildItem C:\MovedFolder -Recurse
Rename the folder, if needed:
- Rename-Item C:\Moved Folder -NewName c:\RenamedFolder
- Get-ChildItem C:\
File Permissions:
- icacls.exe | more
Check permissions on a folder:
- icacls.exe M:\DesktopBackground
Working alongside printers:
- gcm *printer*
- get-Printer (it volition exhibit the local printers)
- get-Printer -ComputerName DC01
- get-Printer -ComputerName DC01 | formatlist
- help add-Printer
- add-Printer -ConnectionName \\dc01\MKTG-PR-101
- Get-Printer
- Remove-Printer -Name "\\dc01\MKTG PR 101"
Working alongside Active Directory Information inwards PowerShell:
- Get-ADUser
- Search-ADAccount
- Get-ADComputer
- Get-ADGroup
- Get-ADGroupMember
- Add-ADGroupMember
View the Information on a User Account:
- gcm *user*
- Help Get-ADUser
- Get-ADUser -Examples
- Get-ADUser -Identity jgarcia
- Get-ADUser -Identity jgarcia -Property
- Get-ADUser -Identity jgarcia -Property *|more
- Search-ADAccount -lockedout | select name
- Search-ADAccount -AccountDisabled | select name
- Get-ADComputer -Filter *
- Get-ADComputer -Identity Client02 -Properties * |more
View Group Memberships:
- Get-Command *group*
- Help Get-ADGroup -Examples
- Get-ADGroup |more
View the ones related to Marketing, alongside component of the championship "MKGT":
- get-ADGroup -filter * | where Name -like "*MKTG*"
- Get-ADGroup -filter {Name -like "*mktg*"} (you filter the closest to the command)
- Get-ADGroupMember -Identity "MKTG Users" |select Name
- Add-ADGroupMember (and y'all tin instantly piece of work interactively inwards AD!!!!)(you powerfulness demand to piece of work alongside this alongside Administrator permissions)
- get-ADUser -filter * -Properties * | get-member | more
- get-ADUser -Property Name,City,Department -filter {Department -eq "MKTG" -and City -eq "Seattle"} |FilterTable SamAccountName, City, Department -Autosize
- get-ADUser -Property Name,City,Department -filter {Department -eq "MKTG" -and City -eq "Seattle"} |FilterTable SamAccountName, City, Department -Autosize > Marketing.txt
Advice: Have a laid methodology for Troubleshooting!
Use commands such as:
- Get-Help
- Get-Command
- Get-Member
Day4:
Remoting alongside PowerShell:
PowerShell Remoting Basics
Enabling Remoting
Working alongside Variables
Remoting alongside PowerShell
Powershell relies on 1 unmarried service WinRM (Windows remote management). WinRM is responsible for maintaining sessions betwixt nodes. WinRM needs Listener to travel setup! Connections exercise WS-MAN (with HTTP/HTTPS). The Listener needs to travel ready on the Target computer!
Enabling Remoting:
- Enable Remoting (run enable-ps remoting on the target computer)
- Set Permissions (give the user access, using set-pssessions)
- Permissions to perform work (add users, or exercise local admins)
- Modify Windows Firewall ('set-windowsfirewall' rules commands)
Requirements for Remoting alongside PowerShell:
Enable-PSRemoting
Get-PSSessionConfiguration
Set-PSSessionConfiguration
Set-NetFirewallRule
Commands:
- y'all volition demand admin permissions, or remoting is non setup:
Get-Service -computername Client02
- When y'all run the ascendance below, read the message below. It volition betoken a firewall number or remote figurer issue:
Enter-PSSession -ComputerName Client02
Example:
Run every bit Admin the ascendance below, to configure PSRemoting:
Enable-PSRemoting
Add inwards the Local Groups, the users/groups that volition receive got access through PowerShell on the remote computer!
Set-PSSessionConfiguration -Name Microsoft.Powershell -ShowSecurityDescriptorUI (add the remote back upwards grouping that volition receive got access, alongside R/W permissions)
Back on the 1st computer, nosotros volition run into that nosotros non tin access the 2d computer, remotely through PowerShell.
Get-item WSMAN:\localhost\Client\TrustedHosts (to depository fiscal establishment check for trusted hosts for this 2d computer)
If at that topographic point aren't any, nosotros wishing to add together some trusted hosts:
Set-Item WSMAN:\localhost\Client\Trustedhosts -Value * (trusted for every system)( nosotros tin also exercise domain names or IP addresses):
Set-Item WSMAN:\localhost\Client\Trustedhosts -Value "WebServer01"
If nosotros re-run the offset command, nosotros volition notice that nosotros instantly receive got trusted hosts!
Let us also larn our firewall setup to piece of work alongside legacy commands:
Get-NetFirewallRule | where DisplayName -Like "*Windows Management Instrumentation*"|select Displayname,name,enabled
- this would allow us to practice inbound traffic for WMI
- the ascendance higher upwards would give us all the WMI rules.
Get-NetFirewallRule |where Displayname -Like "*Windows Management Instrumentation*" |Set-NetFirewallRule -Enabled True -Verbose
(The ascendance higher upwards volition enable all the Rules that showed every bit False above)
Now nosotros should travel able to remotely larn by our remote workstation!
Working alongside Variables:
This is for having to type less commands, as well as using containers for sure enough most used repetitive commands, to lessen our typing efforts.
Get-Variable
$ComputerName = "Client02"
Write-Output
Show to a greater extent than variable details:
Get-Variable |More
Examples:
sl C:\
sl $HOME
cls
Example (set a variable for Client02:
$ComputerName = "Client02"
-if y'all type $Computername, it volition output the mention of "Client02"
Write-Output "The mention of the remote figurer is $Computername" (to impress out the variable)
Write-Output 'The mention of the remote figurer is $Computername' (to impress out the actual text)
Options for Remoting alongside PowerShell:
- - Computername parameter (in commands for remote computers)
- *-PSSession cmdlets (create, come inwards PS sessions, on remote computers)
- Invoke-Command (designed for scripting, to run against a remote system. It's used for a script. It uses XML to transfer data)
- New-CimSession (good for PS 3.0 computers. Good every bit a workaround, for when some commands don't work, for legacy machines)
Example:
help get-service -detailed
$Computername = "client02"
Get-Service -ComputerName $computername | Select Name,Status
Make a remote connection/session:
gcm *-PSSession (gmc = getcommand)
Enter-PSSession -Computername $computername (it volition start a session alongside Client02)
On the remote figurer type:
Get-Service | Select Name,Status
Exit
Check on opened upwards PS sessions:
Get-PSSession
Remove PS Session:
Get-PSSession |Remove-PSSession
Get-PSSession
Invoke-Command:
Help Invoke-Command -Examples
Invoke-Command -ComputerName $computername -ScriptBlock {Get-Service|select Name, Status}
Invoke-Command -ComputerName $computername -ScriptBlock {Get-Service|select Name, Status} |Out-File C:\scripts\InvokeService.txt
Notepad C:\scripts\InvokeService.txt
Cim-Sessions (in the parantheses, nosotros tin run some other command, inwards some other ascendance session):
Get-DnsClientServerAddress -CimSession (New-CimSession -ComputerName $computername)
Day5:
Building alongside PowerShell
Running Scripts inwards PowerShell
Basics of a Parametized Script
Using the PowerShell ISE
Building a Remote Information Gathering Script
A script is only a bunch of commands from the CLI, alongside the .PS1 extension.
This is how nosotros build tools for automation! This is non programming! Learn .Net or C++ instead, but for repetitive tasks as well as automation, PowerShell is for you!
By default, PS does non allow the execution of scripts for safety reasons!
We volition travel using the Set-ExecutionPolicy to either alter the policy, as well as hence that nosotros tin run the script we downloaded or that some other someone gave us.
- nosotros piece of work from an elevated PS compaction as well as nosotros run:
Get-StoppedServices.ps1
(we larn an error, because nosotros are missing the .\ inwards front end of the PS1 script)
.\Get-StoppedServices.ps1
(we larn some other mistake message close scripts beingness disabled on the system)
Help Set-ExecutionPolicy -full
Set-ExecutionPolicy Unrestricted
(choose Yes)
Get-ExecutionPolicy
(we larn Unrestricted every bit a response)
.\Get-StoppedServices.ps1
(now the script runs)
Using PowerShell ISE
Viewing an Existing Script
Creating a New Script
Introduction to the Script Browser
Run your ISE every bit an Administrator:
get-service -ComputerName Client02
(run alongside F8 to larn the output)
(by using the ISE, it gives us proposition commands nosotros wishing to use) (great tool)
- let's charge upwards the Get-StoppedServices.ps1 to await at the script
Get-OSInfo.ps1
$ComputerName = Read-Host "Enter ComputerName"
Get-CimInstance - ClassName Win32_OperatingSystem `
-ComputerName $Computername |
Select-Object -Property CSName, LastBootUpTime
Script Basics:
- Variables
- Parameters
- Logic
- Member Enumeration
Working alongside Script Basics:
Setting Variables
Creating a Parameter
If construct
Foreach Construct
Member Enumeration
Get-ServiceStatus.ps1
#script displays the condition of services running on a specified machine
#Creates a mandatory parameter for ComputerName to travel input
Param (
[Parameter (Mandatory=$true)][string]$ComputerName
)
#creates a variable that contains the output of Get-Service since this has multiple objects, it's referred to every bit an array
$Service = Get-Service -ComputerName $ComputerName
#ForEach Construct volition run through each object (aka each service) inwards $Service
#it volition perform all actions contained inwards the script block for each object
Foreach ($a inwards $service) {
#creates variables containing condition as well as displayname properties
$ServiceStatus = $a.Status
$ServiceDisplayName = $a.DisplayName
#If Else makes conclusion based on $ServiceStatus value
if($ServiceStatus -eq "Running")
{
Write-Output "$ServiceDisplayName is $ServiceStatus"
}
else
{
Write-Output "$ServiceDisplayName is $ServiceStatus"
}
}
Let's run the script above:
Set-ExecutionPolicy Unrestricted
.\Get-ServiceStatus.ps1
Get-OSVersion.ps1
$OS= Get-CimInstance Win32_OperatingSystem | select Caption
$OSv2 = (Get-CimInstance Win32_OperatingSystem).Caption
$OSv3 = (Get-CimInstance Win32_OperatingSystem).WindowsDirectory
Building a Script
Use ISE to run the commands:
Run all commands every bit one-liners -> Add variables as well as parameters -> Add logic run for multiple instances - Keep it simple
Building a Remote Information Gathering Script
Determine Script Tasks
Building Commands
Adding commands to script
Creating variables as well as parameters
Running against remote systems
Get-HelpdeskSupport.ps1
Determine script tasks:
#Username
#computerName
#IP address as well as DNS Name
Reso
#DNS Server of Target
#OS description
#SystemMemory
#Last Reboot
#FreeSpace
#Last User logon engagement & time
#Retrieve Group Membership of AD user account
#Printer
#Write Output to Screen & Make available for pipeline commands
The actual script above:
#IP address as well as DNS Name
$DNSFQDN = Resolve-DnsName -Name $ComputerName | select Name,IPaddress
#DNS Server of Target
$DNSServer = (Get-DnsClientServerAddress `
-cimsession (New-CimSession -ComputerName $ComputerName) `
-InterfaceAlias "ethernet0" -AddressFamily IPv4).ServerAddresses
#OS description
$OS=(Get-CimInstance Win32_OperatingSystem -ComputerName $ComputerName).Caption
#SystemMemory
$memory = ((((Get-CimInstance Win32_PhysicalMemory -ComputerName $ComputerName).Capacity | stair out -Sum).Sum)/1gb)
#Last Reboot
$Reboot = (Get-CimInstance -Class Win32_OperatingSystem -ComputerName $ComputerName).LastBootUpTime
#DiskSpace/FreeSpace
$drive = Invoke-Command -ComputerName $ComputerName {Get-PSDrive | where Name -EQ "C"}
$Freespace = [Math]::Round(($drive.free)/1gb,2)
# for higher upwards - (Get-CimInstance -ComputerName client02 {Get-PSDrive | where Name -EQ "C"}).free
#Last User logon engagement & time
$LastLogonUser = (Get-ADUser -Identity $Username -Property *).LastLogonDate
if($LastLogonUser -eq $null){
$LastLogonUser = "User has non logged onto network since concern human relationship creation"
}
#Retrieve Group Membership of AD user account
$ADGroupMembership = (get-aduser -Identity $Username -property *).memberof
#User accounts on System
(Get-CimInstance Win32_UserAccount -CimSession $ComputerName).Caption
#Printer
$Printers = Get-Printer -ComputerName $Username | Select -Property Name,DriverName, Type |ft -AutoSize
#Write Output to Screen & Make available for pipeline commands
Write-Output "Username: $username " ; ""
Write-Output $UserAccounts;""
Write-Output "DNS Name & IP Address of Target:"
Write-Output $DNSFQDN;""
Write-Output "DNS Server of Target: $DNSServer";""
Write-Output "Last User Logon Attempts: $LastLogonUser ";""
Write-Output "Computername: $Computername ";""
Write-Output "Total System RAM: $memory GB ";""
Write-Output "Freespace on C: $Freespace GB";""
Write-Output "Printers Installed: "
Write-Output $Printers
Write-Output "Group Membership ( Displayed every bit Distinguished Name )"
Write-Output $ADGroupMembership
.\get-helpdesksupportdata.ps1 -ComputerName Client02 -Username jgarcia
.\get-helpdesksupportdata.ps1 -ComputerName Client02 -Username jgarcia | out-file jgarcia.txt
Day6:
Introducing Desired State Configuration
Next Steps
Part of Windows Management Framework iv as well as PowerShell 4
Allow administrators to force configurations to computers
Create DSC configuration via PowerShell script -> MOF files that contains configuration instructions -> that volition force the desired configuration to a figurer (PowerShell manages application of configurations)
Viewing a DSC configuration
Create a MOF file
gcm *-dsc*
help start-dscconfiguration
Look for SimpleConfigv2.ps1 from Jason Helmick for an representative of a config file.
Next Steps:
- start using the PowerShell ascendance prompt CLI
- Ask for help
- inquire yourself: Can I exercise PowerShell?
- ROI (return on investment) on the usage of PowerShell, as well as hence exercise your fourth dimension as well as PowerShell responsibly!
- await into using PowerShell v3/v4 Essentials for information technology Admins Part 1 - 4
- await into PowerShell Toolmaking Fundamentals
- as well as also Windows PowerShell Desired State configuration Fundamentals
THE END
Commands as well as notes:
Advice: Always READ the Description close each ascendance that y'all run, to brand sure enough y'all empathize what the ascendance does!
- get-service
- ise (Integrated Scripting Environment) tool
- ps1 - is the extension of PowerShell Scripts
We tin re-create the commands inwards the History department as well as re-create them inwards ISE, to ameliorate empathize them!
The ascendance below volition give us the condition of the stopped services on the Windows box:
- get-service | where-object Status -eq 'Stopped'
- get-service | where-object Status -eq 'Stopped' | export-csv c:\scripts\services2.csv
- notepad c:\scripts\services2.csv
- get-service | where-object Status -eq 'Stopped' | select-object Status,Name,Displayname | export-csv c:\scripts\services3.csv
- notepad c:\scripts\services3.csv
- $PSversiontable
- get-command (huge listing of Server 2012 related commands)
Anatomy of a PowerShell Command
Help inwards PowerShell
Other Helpful Commands as well as Techniques
Objects as well as the Pipeline
Formatting inwards PowerShell
Command Basics:
- all commands should travel using a format of 'Verb-noun'
- Do Something - To Something
- Get-Verb
Day2:
Get-Verb:
get-verb volition display all the verbs the verbs that are available inwards PowerShell.
get-verb | more - to pipage whatever additional options
get-verb -verb S*
Verb Group
---- -----
Search Common
Select Common
Set Common
Show Common
Skip Common
Split Common
Step Common
Switch Common
Save Data
Sync Data
Start Lifecycle
Stop Lifecycle
Submit Lifecycle
Suspend Lifecycle
Send Communications
---- -----
Search Common
Select Common
Set Common
Show Common
Skip Common
Split Common
Step Common
Switch Common
Save Data
Sync Data
Start Lifecycle
Stop Lifecycle
Submit Lifecycle
Suspend Lifecycle
Send Communications
PS C:\Users\User> get-service -Name M* -ComputerName Client1,DC01
get-service : Cannot opened upwards Service Control Manager on figurer 'Client1'. This performance powerfulness require other privileges.
At line:1 char:1
+ get-service -Name M* -ComputerName Client1,DC01
+
+ CategoryInfo : NotSpecified: (:) [Get-Service], InvalidOperationException
+ FullyQualifiedErrorId : System.InvalidOperationException,Microsoft.PowerShell.Commands.GetServiceCommand
get-service : Cannot opened upwards Service Control Manager on figurer 'Client1'. This performance powerfulness require other privileges.
At line:1 char:1
+ get-service -Name M* -ComputerName Client1,DC01
+
+ CategoryInfo : NotSpecified: (:) [Get-Service], InvalidOperationException
+ FullyQualifiedErrorId : System.InvalidOperationException,Microsoft.PowerShell.Commands.GetServiceCommand
- nosotros larn the mistake message because nosotros demand to run the ascendance higher upwards alongside elevated permissions.
PS C:\Windows\System32> get-service -Name M* -ComputerName Client1,DC01
Let's condense our information!
gsv - alias for get-service
We tin also type:
gsv M* - comp Client1,DC01
Get-Help:
- to read close cmdlets, search terms
get-help *DNS* | more - to search for DNS inwards the middle of the module names, functions, etc.
get-help get-service | more - to detect out to a greater extent than close the syntax of get-service
help get-service -full -it volition practice the same thing
help get-service -online - it volition accept us to the Internet to TechNet.
help *about*
help about_aliases
Update the aid ascendance inwards PS:
update-help
If y'all larn an mistake message of:
Researching inwards PS (PowerShell):
help get-command - to start with
One of the best commands to practice inquiry alongside is:
help get-command -examples
get-command -type cmdlet
get-command -verb New
get-command -name *IP*
get-command -name *IP* |more
get-command -name *IP* -module NETTCPIP |more
CommandType Name Version Source
----------- ---- ------- ------
Alias gip -> Get-NetIPConfiguration 1.0.0.0 NETTCPIP
Function Get-NetIPAddress 1.0.0.0 NETTCPIP
Function Get-NetIPConfiguration 1.0.0.0 NETTCPIP
Function Get-NetIPInterface 1.0.0.0 NETTCPIP
Function Get-NetIPv4Protocol 1.0.0.0 NETTCPIP
Function Get-NetIPv6Protocol 1.0.0.0 NETTCPIP
Function New-NetIPAddress 1.0.0.0 NETTCPIP
Function Remove-NetIPAddress 1.0.0.0 NETTCPIP
Function Set-NetIPAddress 1.0.0.0 NETTCPIP
Function Set-NetIPInterface 1.0.0.0 NETTCPIP
Function Set-NetIPv4Protocol 1.0.0.0 NETTCPIP
Function Set-NetIPv6Protocol 1.0.0.0 NETTCPIP
----------- ---- ------- ------
Alias gip -> Get-NetIPConfiguration 1.0.0.0 NETTCPIP
Function Get-NetIPAddress 1.0.0.0 NETTCPIP
Function Get-NetIPConfiguration 1.0.0.0 NETTCPIP
Function Get-NetIPInterface 1.0.0.0 NETTCPIP
Function Get-NetIPv4Protocol 1.0.0.0 NETTCPIP
Function Get-NetIPv6Protocol 1.0.0.0 NETTCPIP
Function New-NetIPAddress 1.0.0.0 NETTCPIP
Function Remove-NetIPAddress 1.0.0.0 NETTCPIP
Function Set-NetIPAddress 1.0.0.0 NETTCPIP
Function Set-NetIPInterface 1.0.0.0 NETTCPIP
Function Set-NetIPv4Protocol 1.0.0.0 NETTCPIP
Function Set-NetIPv6Protocol 1.0.0.0 NETTCPIP
Note: PowerShell is instance INsensitive!
Working alongside Get-History:
help get-history
- if y'all closed the window where y'all ran your commands, the history volition also travel gone.
- brand sure enough y'all capture your history earlier y'all closed the window.
get-history
Id CommandLine-- -----------
1 get-verb
2 get-verb -verb S*
three cls
iv get-service -Name M* -ComputerName Client1,DC01
five get-service -Name M* -ComputerName Win81Pro
6 get-service -Name M* -ComputerName Client1,DC01
vii get-help
8 aid get-service -full
ix aid *about*
10 aid about_aliases
11 update-help
12 cls
13 larn -command
14 aid get-command
15 cls
16 get-command - examples
17 get-command - examples,...
18 aid get-command -examples
19 get-command -type cmdlet
20 get-command -type New
21 get-command -verb New
22 get-command -name *IP*
23 get-command -name *IP* -module NETTCPIP |more
24 aid Get-NetIPConfiguration |more 25 Get-NetIPConfiguration
23 get-command -name *IP* -module NETTCPIP |more
24 aid Get-NetIPConfiguration |more 25 Get-NetIPConfiguration
invoke-history -Id 18
Save/Output the history to a file:
get-history | out-file c:\scripts\GetHistory01.txt
Open the .txt file alongside the history commands:
Notepad c:\scripts\GetHistory01.txt
help Start-Transcript
start-transcript -path c:\scripts\Transcript01.txt
stop-transcript
Pipelining inwards PS:
Get Something | Do Something | Output Somethingexample:
get-service | where-object condition -eq "Stopped" | out-file c:\scripts\services.txt
PowerShell Data every bit Objects:
Property Property Property
^ ^ ^
Name DisplayName Status
spooler Print Spooler Running <-- Object
wuauserv Windows Update Stopped <-- Object
vss Volume Shadow Copy Stopped <-- Object
Pipelining Basics:
aid get-memberget-service | get-member
get-service | get-member | more
get-service | select-object Name,Status
get-service | select-object Name,Status| out-file c:\scripts\services.txt
get-service | where-object condition -eq "stopped"
get-service | where-object condition -eq "stopped"| Format-List
Formatting:
aid format-listget-service|format-list|more
get-service|fl Name,Status|more
get-service|format-table
get-service|format-table -AutoSize
get-service|format-table -Wrap
get-service|format-table -Wrap -autosize
get-service|FT -wrap Name,Status
get-service|FT -wrap Name,Status
get-service|Out-GridView
Day3:
Gathering Information alongside PowerShell:
Troubleshooting Steps:
Identify the Issues
Find Root Cause
Determine as well as Implement a Solution
Verify Results
Always apply in 1 lawsuit solution at a time! Don't apply to a greater extent than than 1 solution to the issue!
Related to:
Computer as well as Hardware
Networking
Registry
Files as well as Printers
Active Directory Objects
Process:
Gathering Info Process - will exercise the Get-Command (to detect the ascendance that nosotros are looking for) - Help (to read close the commands as well as examples of the command) - and when nosotros wishing to lay a sure enough information from an object, nosotros volition use Get-Member.
For most commands nosotros volition travel using Get-Verb.
In social club to larn information close the Operating System y'all demand access to the Windows Management Instrumentation (WMI) - Get-WMIobject.
Common Information Model (CIM) - Get-CimInstance
When nosotros access WMI Information, nosotros access the WMI Repository. In at that topographic point nosotros have CIMv2, WIN32_Processor, Device ID and Name.
Gathering Operating System as well as Hardware Information alongside PowerShell:
Get-Counter
Get-WMIObject
Get-CIMInstance
Get-EventLog
- to troubleshoot an number alongside a user's figurer slowness
Check committed memory:
get-command *counter*
- Get-Counter
- Get-Counter -listset *memory*
- Get-Counter -listset *memory* | where CounterSetName -eq 'Memory'
- Get-Counter -listset *memory* | where CounterSetName -eq 'Memory' |select -expand Paths
- Get-Counter "\memory\% Committed Bytes inwards use"
- Get-CIMInstance WIN32_PhysicalMemory
Check difficult drive:
- Get-CimClass -ClassName *disk*
- Get-WmiObject -Class Win32_logicaldisk (this brings dorsum the local disks information)
Check organisation BIOS:
- Get-CimClass *BIOS*
- Get-WMIObject Win32_BIOS
- Get-CimInstance Win32_BIOS (we larn the same information every bit alongside the ascendance higher upwards it)
or:
- Get-CimInstance Win32_BIOS |select Name,Version
Check the final fourth dimension the organisation was rebooted:
- gcm *event*
- aid Get-EventLog
- help Get-EventLog -Examples
We volition travel looking through the latest K events, at an eventID of -1074, to run into the final fourth dimension the organisation rebooted:
- Get-EventLog -log organisation -newest K | where-object eventid -eq '1074' | format-table machinename, username, timegenerated -autosize
Gathering Networking Information:
Ipconfig
Get-NetIPAddressConfiguration
Get-SMBMapping
New-SMBMapping
IPConfig:
- GCM *IP* (we volition select the best command)
- Get-NetIpAddress
- Get-NetIPConfiguration
Troubleshoot DNS:
- we await for DNS customer commands
- help get-DNSclient
- get-DNSClient
- get-DNSclientServerAddress
- Get-DNSClientCache
Mapping a network drive:
- GCM *SMB*
- aid Get-SMBMapping -Examples
- Get-SMBMapping
- aid new-smbMapping
- help new-smbMapping -Examples
- New-SMBMapping - LocalPath S: -RemotePath \\DC01\Shares
- Get-SMBMapping
Test Network Connections:
- ping 4.2.2.1
- tracert 4.2.2.1
- Test-NetConnection 4.2.2.1
- Test-NetConnection 4.2.2.1 -TraceRoute
- Test-NetConnection -CommonTCPPort HTTP -ComputerName cnn.com
Gathering Registry Information alongside PowerShell:
Get-PSProvider
Get-Item
Get-ItemProperty
Get-ItemProperty
- aid Get-PSProvider
- Get-PSProvider
- Set-Location HKLM:
PS HKLM:\> dir
PS HKLM:\> cd software
PS HKLM:\> set-ItemProperty -Path .\WiredCoffee -Name PackageInstalled -Value 0
(you powerfulness demand Administrator permisions)
Run As Admin:
sl hklm:\software
PS HKLM:\> Set-ItemProperty -Path .\WiredCoffee -Name PackageInstalled -value 0
PS HKLM:\> Get-Item .\WiredCoffee
Working alongside Files as well as Printers:
Working alongside File as well as Printers inwards PowerShell:
- Get-ChildItem
- Copy-Item
- Move-Item
- Rename-Item
- Get-Printer
- Add-Printer
- Remove-Printer
You are looking for a file stored on a network drive, without knowing the name, but solely knowing the file type:
- aid Get-ChildItem
- aid Get-ChildItem -Examples
- Get-ChildItem
- Get-ChildItem -path M:\ -Recurse
- Get-ChildItem -path M:\ -Recurse -Include *.PNG
Now nosotros demand to re-create the establish file locally:
- gcm *copy*
- aid Copy-Item
- help Copy-Item -Examples
- copy-item m:\DesktopBackgrounds -Destination c:\Backgrounds -Recurse -Verbose
- Get-ChildItem c:\
- Get-ChildItem c:\BackGrounds -Recurse
Move the folder to some other folder inwards the C: drive:
- Move-Item c:\Backgrounds -Destination c:\MovedFolder -Verbose
- Get-childItem C:\
- Get-ChildItem C:\MovedFolder -Recurse
Rename the folder, if needed:
- Rename-Item C:\Moved Folder -NewName c:\RenamedFolder
- Get-ChildItem C:\
File Permissions:
- icacls.exe | more
Check permissions on a folder:
- icacls.exe M:\DesktopBackground
Working alongside printers:
- gcm *printer*
- get-Printer (it volition exhibit the local printers)
- get-Printer -ComputerName DC01
- get-Printer -ComputerName DC01 | formatlist
- help add-Printer
- add-Printer -ConnectionName \\dc01\MKTG-PR-101
- Get-Printer
- Remove-Printer -Name "\\dc01\MKTG PR 101"
Working alongside Active Directory Information inwards PowerShell:
- Get-ADUser
- Search-ADAccount
- Get-ADComputer
- Get-ADGroup
- Get-ADGroupMember
- Add-ADGroupMember
View the Information on a User Account:
- gcm *user*
- Help Get-ADUser
- Get-ADUser -Examples
- Get-ADUser -Identity jgarcia
- Get-ADUser -Identity jgarcia -Property
- Get-ADUser -Identity jgarcia -Property *|more
- Search-ADAccount -lockedout | select name
- Search-ADAccount -AccountDisabled | select name
- Get-ADComputer -Filter *
- Get-ADComputer -Identity Client02 -Properties * |more
View Group Memberships:
- Get-Command *group*
- Help Get-ADGroup -Examples
- Get-ADGroup |more
View the ones related to Marketing, alongside component of the championship "MKGT":
- get-ADGroup -filter * | where Name -like "*MKTG*"
- Get-ADGroup -filter {Name -like "*mktg*"} (you filter the closest to the command)
- Get-ADGroupMember -Identity "MKTG Users" |select Name
- Add-ADGroupMember (and y'all tin instantly piece of work interactively inwards AD!!!!)(you powerfulness demand to piece of work alongside this alongside Administrator permissions)
- get-ADUser -filter * -Properties * | get-member | more
- get-ADUser -Property Name,City,Department -filter {Department -eq "MKTG" -and City -eq "Seattle"} |FilterTable SamAccountName, City, Department -Autosize
- get-ADUser -Property Name,City,Department -filter {Department -eq "MKTG" -and City -eq "Seattle"} |FilterTable SamAccountName, City, Department -Autosize > Marketing.txt
Advice: Have a laid methodology for Troubleshooting!
Use commands such as:
- Get-Help
- Get-Command
- Get-Member
Day4:
Remoting alongside PowerShell:
PowerShell Remoting Basics
Enabling Remoting
Working alongside Variables
Remoting alongside PowerShell
Powershell relies on 1 unmarried service WinRM (Windows remote management). WinRM is responsible for maintaining sessions betwixt nodes. WinRM needs Listener to travel setup! Connections exercise WS-MAN (with HTTP/HTTPS). The Listener needs to travel ready on the Target computer!
Enabling Remoting:
- Enable Remoting (run enable-ps remoting on the target computer)
- Set Permissions (give the user access, using set-pssessions)
- Permissions to perform work (add users, or exercise local admins)
- Modify Windows Firewall ('set-windowsfirewall' rules commands)
Requirements for Remoting alongside PowerShell:
Enable-PSRemoting
Get-PSSessionConfiguration
Set-PSSessionConfiguration
Set-NetFirewallRule
Commands:
- y'all volition demand admin permissions, or remoting is non setup:
Get-Service -computername Client02
- When y'all run the ascendance below, read the message below. It volition betoken a firewall number or remote figurer issue:
Enter-PSSession -ComputerName Client02
Example:
Run every bit Admin the ascendance below, to configure PSRemoting:
Enable-PSRemoting
Add inwards the Local Groups, the users/groups that volition receive got access through PowerShell on the remote computer!
Set-PSSessionConfiguration -Name Microsoft.Powershell -ShowSecurityDescriptorUI (add the remote back upwards grouping that volition receive got access, alongside R/W permissions)
Back on the 1st computer, nosotros volition run into that nosotros non tin access the 2d computer, remotely through PowerShell.
Get-item WSMAN:\localhost\Client\TrustedHosts (to depository fiscal establishment check for trusted hosts for this 2d computer)
If at that topographic point aren't any, nosotros wishing to add together some trusted hosts:
Set-Item WSMAN:\localhost\Client\Trustedhosts -Value * (trusted for every system)( nosotros tin also exercise domain names or IP addresses):
Set-Item WSMAN:\localhost\Client\Trustedhosts -Value "WebServer01"
If nosotros re-run the offset command, nosotros volition notice that nosotros instantly receive got trusted hosts!
Let us also larn our firewall setup to piece of work alongside legacy commands:
Get-NetFirewallRule | where DisplayName -Like "*Windows Management Instrumentation*"|select Displayname,name,enabled
- this would allow us to practice inbound traffic for WMI
- the ascendance higher upwards would give us all the WMI rules.
Get-NetFirewallRule |where Displayname -Like "*Windows Management Instrumentation*" |Set-NetFirewallRule -Enabled True -Verbose
(The ascendance higher upwards volition enable all the Rules that showed every bit False above)
Now nosotros should travel able to remotely larn by our remote workstation!
Working alongside Variables:
This is for having to type less commands, as well as using containers for sure enough most used repetitive commands, to lessen our typing efforts.
Get-Variable
$ComputerName = "Client02"
Write-Output
Show to a greater extent than variable details:
Get-Variable |More
Examples:
sl C:\
sl $HOME
cls
Example (set a variable for Client02:
$ComputerName = "Client02"
-if y'all type $Computername, it volition output the mention of "Client02"
Write-Output "The mention of the remote figurer is $Computername" (to impress out the variable)
Write-Output 'The mention of the remote figurer is $Computername' (to impress out the actual text)
Options for Remoting alongside PowerShell:
- - Computername parameter (in commands for remote computers)
- *-PSSession cmdlets (create, come inwards PS sessions, on remote computers)
- Invoke-Command (designed for scripting, to run against a remote system. It's used for a script. It uses XML to transfer data)
- New-CimSession (good for PS 3.0 computers. Good every bit a workaround, for when some commands don't work, for legacy machines)
Example:
help get-service -detailed
$Computername = "client02"
Get-Service -ComputerName $computername | Select Name,Status
Make a remote connection/session:
gcm *-PSSession (gmc = getcommand)
Enter-PSSession -Computername $computername (it volition start a session alongside Client02)
On the remote figurer type:
Get-Service | Select Name,Status
Exit
Check on opened upwards PS sessions:
Get-PSSession
Remove PS Session:
Get-PSSession |Remove-PSSession
Get-PSSession
Invoke-Command:
Help Invoke-Command -Examples
Invoke-Command -ComputerName $computername -ScriptBlock {Get-Service|select Name, Status}
Invoke-Command -ComputerName $computername -ScriptBlock {Get-Service|select Name, Status} |Out-File C:\scripts\InvokeService.txt
Notepad C:\scripts\InvokeService.txt
Cim-Sessions (in the parantheses, nosotros tin run some other command, inwards some other ascendance session):
Get-DnsClientServerAddress -CimSession (New-CimSession -ComputerName $computername)
Day5:
Building alongside PowerShell
Running Scripts inwards PowerShell
Basics of a Parametized Script
Using the PowerShell ISE
Building a Remote Information Gathering Script
A script is only a bunch of commands from the CLI, alongside the .PS1 extension.
This is how nosotros build tools for automation! This is non programming! Learn .Net or C++ instead, but for repetitive tasks as well as automation, PowerShell is for you!
By default, PS does non allow the execution of scripts for safety reasons!
We volition travel using the Set-ExecutionPolicy to either alter the policy, as well as hence that nosotros tin run the script we downloaded or that some other someone gave us.
- nosotros piece of work from an elevated PS compaction as well as nosotros run:
Get-StoppedServices.ps1
(we larn an error, because nosotros are missing the .\ inwards front end of the PS1 script)
.\Get-StoppedServices.ps1
(we larn some other mistake message close scripts beingness disabled on the system)
Help Set-ExecutionPolicy -full
Set-ExecutionPolicy Unrestricted
(choose Yes)
Get-ExecutionPolicy
(we larn Unrestricted every bit a response)
.\Get-StoppedServices.ps1
(now the script runs)
Using PowerShell ISE
Viewing an Existing Script
Creating a New Script
Introduction to the Script Browser
Run your ISE every bit an Administrator:
get-service -ComputerName Client02
(run alongside F8 to larn the output)
(by using the ISE, it gives us proposition commands nosotros wishing to use) (great tool)
- let's charge upwards the Get-StoppedServices.ps1 to await at the script
Get-OSInfo.ps1
$ComputerName = Read-Host "Enter ComputerName"
Get-CimInstance - ClassName Win32_OperatingSystem `
-ComputerName $Computername |
Select-Object -Property CSName, LastBootUpTime
Script Basics:
- Variables
- Parameters
- Logic
- Member Enumeration
Working alongside Script Basics:
Setting Variables
Creating a Parameter
If construct
Foreach Construct
Member Enumeration
Get-ServiceStatus.ps1
#script displays the condition of services running on a specified machine
#Creates a mandatory parameter for ComputerName to travel input
Param (
[Parameter (Mandatory=$true)][string]$ComputerName
)
#creates a variable that contains the output of Get-Service since this has multiple objects, it's referred to every bit an array
$Service = Get-Service -ComputerName $ComputerName
#ForEach Construct volition run through each object (aka each service) inwards $Service
#it volition perform all actions contained inwards the script block for each object
Foreach ($a inwards $service) {
#creates variables containing condition as well as displayname properties
$ServiceStatus = $a.Status
$ServiceDisplayName = $a.DisplayName
#If Else makes conclusion based on $ServiceStatus value
if($ServiceStatus -eq "Running")
{
Write-Output "$ServiceDisplayName is $ServiceStatus"
}
else
{
Write-Output "$ServiceDisplayName is $ServiceStatus"
}
}
Let's run the script above:
Set-ExecutionPolicy Unrestricted
.\Get-ServiceStatus.ps1
Get-OSVersion.ps1
$OS= Get-CimInstance Win32_OperatingSystem | select Caption
$OSv2 = (Get-CimInstance Win32_OperatingSystem).Caption
$OSv3 = (Get-CimInstance Win32_OperatingSystem).WindowsDirectory
Building a Script
Use ISE to run the commands:
Run all commands every bit one-liners -> Add variables as well as parameters -> Add logic run for multiple instances - Keep it simple
Building a Remote Information Gathering Script
Determine Script Tasks
Building Commands
Adding commands to script
Creating variables as well as parameters
Running against remote systems
Get-HelpdeskSupport.ps1
Determine script tasks:
#Username
#computerName
#IP address as well as DNS Name
Reso
#DNS Server of Target
#OS description
#SystemMemory
#Last Reboot
#FreeSpace
#Last User logon engagement & time
#Retrieve Group Membership of AD user account
#Printer
#Write Output to Screen & Make available for pipeline commands
The actual script above:
#IP address as well as DNS Name
$DNSFQDN = Resolve-DnsName -Name $ComputerName | select Name,IPaddress
#DNS Server of Target
$DNSServer = (Get-DnsClientServerAddress `
-cimsession (New-CimSession -ComputerName $ComputerName) `
-InterfaceAlias "ethernet0" -AddressFamily IPv4).ServerAddresses
#OS description
$OS=(Get-CimInstance Win32_OperatingSystem -ComputerName $ComputerName).Caption
#SystemMemory
$memory = ((((Get-CimInstance Win32_PhysicalMemory -ComputerName $ComputerName).Capacity | stair out -Sum).Sum)/1gb)
#Last Reboot
$Reboot = (Get-CimInstance -Class Win32_OperatingSystem -ComputerName $ComputerName).LastBootUpTime
#DiskSpace/FreeSpace
$drive = Invoke-Command -ComputerName $ComputerName {Get-PSDrive | where Name -EQ "C"}
$Freespace = [Math]::Round(($drive.free)/1gb,2)
# for higher upwards - (Get-CimInstance -ComputerName client02 {Get-PSDrive | where Name -EQ "C"}).free
#Last User logon engagement & time
$LastLogonUser = (Get-ADUser -Identity $Username -Property *).LastLogonDate
if($LastLogonUser -eq $null){
$LastLogonUser = "User has non logged onto network since concern human relationship creation"
}
#Retrieve Group Membership of AD user account
$ADGroupMembership = (get-aduser -Identity $Username -property *).memberof
#User accounts on System
(Get-CimInstance Win32_UserAccount -CimSession $ComputerName).Caption
#Printer
$Printers = Get-Printer -ComputerName $Username | Select -Property Name,DriverName, Type |ft -AutoSize
#Write Output to Screen & Make available for pipeline commands
Write-Output "Username: $username " ; ""
Write-Output $UserAccounts;""
Write-Output "DNS Name & IP Address of Target:"
Write-Output $DNSFQDN;""
Write-Output "DNS Server of Target: $DNSServer";""
Write-Output "Last User Logon Attempts: $LastLogonUser ";""
Write-Output "Computername: $Computername ";""
Write-Output "Total System RAM: $memory GB ";""
Write-Output "Freespace on C: $Freespace GB";""
Write-Output "Printers Installed: "
Write-Output $Printers
Write-Output "Group Membership ( Displayed every bit Distinguished Name )"
Write-Output $ADGroupMembership
.\get-helpdesksupportdata.ps1 -ComputerName Client02 -Username jgarcia
.\get-helpdesksupportdata.ps1 -ComputerName Client02 -Username jgarcia | out-file jgarcia.txt
Day6:
Introducing Desired State Configuration
Next Steps
Part of Windows Management Framework iv as well as PowerShell 4
Allow administrators to force configurations to computers
Create DSC configuration via PowerShell script -> MOF files that contains configuration instructions -> that volition force the desired configuration to a figurer (PowerShell manages application of configurations)
Viewing a DSC configuration
Create a MOF file
gcm *-dsc*
help start-dscconfiguration
Look for SimpleConfigv2.ps1 from Jason Helmick for an representative of a config file.
Next Steps:
- start using the PowerShell ascendance prompt CLI
- Ask for help
- inquire yourself: Can I exercise PowerShell?
- ROI (return on investment) on the usage of PowerShell, as well as hence exercise your fourth dimension as well as PowerShell responsibly!
- await into using PowerShell v3/v4 Essentials for information technology Admins Part 1 - 4
- await into PowerShell Toolmaking Fundamentals
- as well as also Windows PowerShell Desired State configuration Fundamentals
THE END