Powershell Primer

49
Quick PowerShell Primer ARE YOU A WINDOWS ADMIN? YOU PROBABLY SHOULD LEARN THIS STUFF…

description

This was a presentation I gave to our Rockford SpiceCorps meeting on October 10th, 2013. I'm still learning it, but wanted to share with other Spiceheads so they don't have to feel intimidated by Powershell.

Transcript of Powershell Primer

Page 1: Powershell Primer

Quick PowerShell PrimerARE YOU A WINDOWS ADMIN? YOU PROBABLY SHOULD LEARN THIS STUFF…

Page 2: Powershell Primer

Things you should know •Can be considered a command-line replacement

•Has a fairly easy to follow structure when executing commands (called ‘cmdlets’)

•Cmdlets use attributes, similar to exe command-line arguments

•You can pipe the output of one cmdlet into another

•Similar to batch, you can use the line-by-line commands in Powershell to create a script (.PS1 file)

•An integrated scripting environment (ISE) is provided with Powershell

Page 3: Powershell Primer

Starting with Powershell Comes pre-installed with Windows 7 + and Windows Server 2008 +

Click start > type ‘powershell’ > right-click ‘run as administrator’

Powershell 4.0 is the latest iteration – be sure to check the notes about interoperability with MS management tools (Exchange, VMM, etc.) on your desktop.

Page 4: Powershell Primer

Powershell structure: verb-nounFor the most part, use verb-noun format

◦ GET-SOMETHING◦ SET-SOMETHING◦ Get-service◦ Start-Service◦ Get-Process◦ Delete-Item◦ Etc.

Page 5: Powershell Primer

Starting with Powershell

Good first command:

Get-Host

Page 6: Powershell Primer

Powershell structure: objectsObjects are the “things” that Powershell works with: files, registry keys, computer names, strings, users, etc.

Get-Service

This would retrieve a list of services, now grouped together as individual objects – not just names of services, but all their properties like ‘status,’ ‘name,’ ‘startuptype,’ etc.).

Page 7: Powershell Primer

Powershell structure: attributesPowershell uses attributes to define the cmdlet.

Get-service –name “wuauserv”

Get-eventlog –logname system –newest 3

attribute

attribute attribute

Page 8: Powershell Primer

Powershell structure: pipelinePowershell can pass objects (not just strings) to another cmdlet, allowing you to create some powerful sequences of commands.

Get-service –name “bits” | restart-service

Get-process –name “notepad” | stop-process

Get-eventlog –logname system | out-file c:\temp\system.log

Page 9: Powershell Primer

Some starter cmdletsCertainly, there a TON more cmdlets available to you through Powershell, but here are a few to get you introduced:

◦ Get-Command◦ Get-Help◦ Get-Content◦ Get-ChildItem◦ Get-EventLog◦ Get-Service / Stop-Service / Restart-Service / Start-Service

Getting data

Page 10: Powershell Primer

Get-CommandSEARCH FOR THE COMMAND YOU NEED

Getting data

Page 11: Powershell Primer

Get-Command: the basicsProbably THE MOST useful cmdlet of all, Get-Command can find the command you are looking for:

Note the use of wildcards.

Getting data

Get-Command *service* Finds all cmdlets with the word ‘service’ in it.

Get-Command get-* Finds all cmdlets starting with the word ‘get-’

Get-Command –noun *service*

Finds all cmdlets with ‘service’ in the noun string.

Page 12: Powershell Primer

Get-HelpPRETTY SELF-EXPLANATORY, NO?

Getting data

Page 13: Powershell Primer

Get-Help: the basicsThis cmdlet is useful to determine what another cmdlet does:

Get-Help get-command

The command will output a help article about the command you referenced.

Getting data

Page 14: Powershell Primer

Get-Help: Three ways to get itViewing it inline with the command window:

Get-Help get-service –detailed

Viewing the help online:

Get-Help get-service –online

Viewing help outside of the Powershell command window (Powershell 3.0+):

Get-Help get-service –showwindow

Getting data

Make sure to run ‘update-help’

occasionally to get the

latest help

documentation from Microsoft

Page 15: Powershell Primer

Get-ContentUSE INPUT FROM ANOTHER SOURCE

Page 16: Powershell Primer

Get-ContentThis cmdlet can take a file and process its contents and do something with it.

Where would you use this?◦ Have it grab the content of a logfile and email it to your team◦ Process each line (list of computers or users, etc.) from a text file and run a

command against each line◦ Use it to find strings in log files◦ Etc.

Page 17: Powershell Primer

Get-ContentGet-content c:\computers.txt | foreach-object {ping $_}

This will ping each computer found in the text file (note the foreach-object cmdlet). Try using another command in place of ping.

The curly brackets denotes a block of code (i.e. ping) that runs against each object found in the pipeline.

$_ represents the object found in the previous pipeline passed to the next pipeline (i.e. a computername).

Page 18: Powershell Primer

Get-Content

Get-content c:\windows\windowsupdate.log | select-string –pattern “error”

This will list all lines within windowsupdate.log which contains the word “error.” ‘Select-String’ is another cmdlet we piped our logfile contents to.

Page 19: Powershell Primer

Get-ChildItemINDEX A LIST OF OBJECTS FROM INSIDE A CONTAINER

Getting data

Page 20: Powershell Primer

Get-ChildItemBasically, this is like ‘Dir’ in DOS/Windows CLI. However, it can access much more than just file/folder objects but other items from various containers, like:

◦ Aliases◦ Environment◦ FileSystem◦ Function◦ Registry◦ Variable◦ Certificates

In Powershell, these are called ‘drives’ (sometimes referred to as PSDrives)

You can work directly in network shares with Powershell. No more mapping of drive letters when working with remotely connected folders!

Page 21: Powershell Primer

Get-ChildItemWe’re just going to talk about files and folders, though…

Get-ChildItem c:\windows –file

The –file attribute tells to only return files from the c:\windows folder.

Get-ChildItem has an alias named “dir” and “ls” – use get-alias –definition get-childitem to find out more.

Page 22: Powershell Primer

Get-ChildItemThe –filter attribute tells get-childitem to only return .log files from the c:\windows folder.

Get-ChildItem c:\windows –file –filter *.log

You can use the –recurse attribute to drill through all the subfolders.

-recurse

Page 23: Powershell Primer

Get-ChildItemGet-ChildItem c:\windows\system32 –file –filter *.log | where-object creationtime –gt 08-08-2012

We’ve piped our results from get-childitem to ‘where-object’ (we’ll talk about that in a minute). This will show us files from get-childitem where the creation time is greater than 08-08-2012.

Note you could place a function here to subtract a number of days from today’s date, then pipe that into a ‘remove-item’ cmdlet to delete them.

Page 24: Powershell Primer

Get-EventLogGET OBJECTS FROM A SPECIFIED EVENT LOG

Getting data

Page 25: Powershell Primer

Get-EventLogRunning Get-EventLog with the ‘List’ attribute will show you all event logs on the system, like ‘System,’ ‘Security,’ ‘Application,’ etc.

Get-EventLog –List

Specifying a log name using the –Logname attribute will show you all the events from that log.

Get-EventLog –Logname system

Page 26: Powershell Primer

Get-EventLogThis will return the latest 3 entries in your system event log using the –newest attribute.

Get-EventLog –Logname System –newest 3

Using the –message attribute, Powershell will look at the contents of the event message and index the latest 3 entries in your system log with the word ‘shutdown’ contained in the message text

Get-EventLog –Logname System –newest 3 –message *shutdown*

Page 27: Powershell Primer

Get-EventLogUsing the –EntryType attribute, PS will retrieve the last 10 errors from the system event log.

Get-EventLog –newest 10 –entrytype error | format-list

Note that we piped this to the ‘format-list’ cmdlet. This converts outputted objects into easily legible text. Replace this with ‘out-file c:\filename.txt’ to save the results for use later.

Page 28: Powershell Primer

Get-ServiceLIST SERVICES AND THEIR PROPERTIES ON A COMPUTER

Getting data

Page 29: Powershell Primer

Get-ServiceFrom earlier examples, you may have noticed we looked at working with services…but as a refresher, simply running ‘get-service’ will output a list of installed service status, name, and display names.

Get-service

Page 30: Powershell Primer

Get-ServiceGet-service can also be run against a remote system using the –computername attribute.

Get-service –computername titan

You can determine if a command can be run remotely by reviewing the help contents (get-help) for that particular cmdlet. By default, you don’t typically need to enable anything on the remote computer for this to function.

Page 31: Powershell Primer

Get-ServicePiping Get-Service to Restart-Service

Get-service –computername titan –name “bits” | restart-service

By using the –name attribute, we are telling Powershell to only retrieve services named “bits” and then pipe it to restart-service.

Some methods are available to some objects that makes it possible to manipulate them without piping them to another cmdlet – use get-member to discover them. i.e. (get-service –name “spiceworks”).stop()

Page 32: Powershell Primer

Get-ServiceWant to start stopped services only? You could write something like this using ‘where-object:’

Get-service | where-object status –eq stopped | start-service

You can use wildcards too.

Get-service –displayname *exchange* | where-object status –eq stopped | start-service

Page 33: Powershell Primer

Some starter cmdlets (useful cmdlets to send output to)

◦ Get-Member◦ Select◦ Where-Object◦ ForEach-Object◦ Out-File◦ Format-List

Outputting data

Page 34: Powershell Primer

Get-MemberLISTING THE PROPERTIES AND METHODS OF A COMMAND OR OBJECT

Getting data

Page 35: Powershell Primer

Get-Member: the basicsOnly used when piped from another cmdlet, Get-Member tells you more about the kind of information about the objects the originating cmdlet can work with:

Get-Service | get-member

Once you get your results from get-member, you can use this knowledge to use ‘select’ or ‘where-object’ cmdlets (so you can filter or select data about objects in the prior pipeline).

Outputting data

Page 36: Powershell Primer

Select-objectSELECT SPECIFIC PROPERTIES OF AN OBJECT

Getting data

Page 37: Powershell Primer

Select-objectOnly used when an object is piped to it, this cmdlet will show you only the information about the object that you specify

Get-process | select-object name, ID

This will show us only the name and ID (PID) of all processes that are currently running, even though there are a lot more properties to each process that we could do something with.

We know that we can use ‘name’ and ‘ID’ with Get-process because we found out about them using ‘Get-Process | Get-Member.’

Outputting data

Page 38: Powershell Primer

Where-ObjectFILTERS RETURNED DATA FROM OBJECTS IN THE PRIOR PIPELINE

Getting data

Page 39: Powershell Primer

Where-ObjectOnly used when an object is piped to it, this cmdlet will only perform an action against an object with certain criteria

Get-process | where-object name –eq “notepad”

We know that we can use ‘name,’ since it was retrieved using ‘Get-Process | Get-Member.’

Outputting data

Page 40: Powershell Primer

ForEach-ObjectLOOP THROUGH A COLLECTION OF OBJECTS

Getting data

Page 41: Powershell Primer

ForEach-ObjectOnly used when an object is piped to it, this cmdlet will perform an action against each object passed to it (use curly brackets!)

Get-content c:\computers.txt | foreach-object {write-host $_}

Write-Host will output the object string to screen (if possible)

Outputting data

Page 42: Powershell Primer

Out-FileSAVING DATA DIRECTLY TO FILE

Getting data

Page 43: Powershell Primer

Out-FileOnly used when an object is piped to it, this cmdlet will take objects, convert the results to string and place it into a text file.

Get-Service | Out-File c:\services.txt

Note there are other methods to output data to different file types (CSV, HTML, XML, etc. use ‘get-command’ to find them)

Outputting data

Page 44: Powershell Primer

Format-ListDISPLAY INFORMATION ABOUT OBJECTS IN A LIST

Getting data

Page 45: Powershell Primer

Format-ListOnly used when an object is piped to it, this cmdlet will take objects, convert the results into string and format the output into a list. Great for reporting.

Get-Service | format-list

Alternative cmdlets are ‘format-wide’ and ‘format-table.’

Note that once formatted into string output, the object is no longer being treated as an object and cannot be piped into another cmdlet expecting anything other than strings.

Outputting data

Page 46: Powershell Primer

Summary

This presentation shows only a tiny fraction of what Powershell can do.

Some things to remember:

◦ Pipe objects from one cmdlet to another using the verb-noun format.

◦ Not sure what commands are available to you? Use get-command.

◦ Not sure what you can do with the command? Use get-help cmdlet-name.

◦ Not sure what the cmdlet will work with? Pipe the cmdlet into get-member.

◦ You can perform various actions against computer and user objects, too.

◦ Put your commands together and make a script (.PS1 file)

Some things to remember…

Page 47: Powershell Primer

Other useful cmdlets

• Send-MailMessage• Restart-Computer• Rename-Computer• ConvertTo-Html• Get-wmiObject• Out-Printer• Connect-PSSession• Out-Gridview

More power!

Page 48: Powershell Primer

Tools and Resources

Some great links for Powershell (tools, resources)

Download Powershell 3.0 - http://bit.ly/DownloadPS30

Powershell 3.0 documentation - http://bit.ly/PS30-coremodule

Powershell ISE (comes with Powershell)

PowerGUI (Quest Software, freeware) - http://bit.ly/PowerGUIDownload

Quest ActiveRoles CmdLets - http://bit.ly/QuestADCmdlets (needed for PowerGUI)

Rob Van Der Woude’s WMI Code Generator - http://bit.ly/WMIGenerator

Tools for working with PowerShell

Page 49: Powershell Primer

Thanks!ROB DUNN

TWITTER: @MAXIMILLIANX

[email protected]