Be lazy - automate your windows tasks with powershell

From time to time we need to do some windows tasks - like backup files , change files , invoke windows commands,connect to process , track system event, maniplulate files, administartion tasks , connect to the web, invoke rest service, query database...... for these we can use windows powershell

Windows PowerShell is Microsoft's task automation framework, consisting of a command-line shell and associated scripting language built on top of .NET Framework. PowerShell provides full access to COM and WMI, enabling administrators to perform administrative tasks on both local and remote Windows systems.

Installation:
If you have windows 7 , so you already have powershell version2.
If you want to upgrade to powershell version 3 than make sure service pack1 and .Net4 are installed on your computer and than follow by this link for upgrade.
You can star powershell from the start menu or by just type powershell in cmd window (exit at the end will return to shell window).


This is not a powershell tutorial. You will find plenty of them in the web.The target of this post is to give a general overview of powershell capabilities through some practical examples.

Cmdlets
Cmdlets are specialized commands in the PowerShell environment that implement specific functions. These are the native commands in the PowerShell stack. Most of the windows tools like mssql,office
Most of the windows tools implements their own cmdlet and give you the ability to connect with them by using cmdlet. You can define and implement cmdlet by yourself by using any .Net language.
Since its all about .Net classes and object is very simple to define and interact with any .Net API. You can even create your own "little language".
If you need to do some administration operation on any tool or program check first if it the tool has powershell snapin for management their environment.

Cmdlets follow a - naming pattern, such as Get-ChildItem,but its a good practice to add alias , so you can use 'gci, dir, ls' as an alias for Get-ChildItem.

Pipeline
PowerShell, like Unix/Linux based shells, implements a pipeline. This pipeline enables the output of one cmdlet to be piped as input to another cmdlet. For example, the output of the Get-Process cmdlet can be piped to the Sort-Object cmdlet (e.g. to sort the objects by handle count) and then to the Where-Object to filter any process that has, say, less than 1 MB of paged memory, then finally to the Select-Object cmdlet to select just the first 10 (i.e. the 10 processes based on handle count).

Editors
There are a lot of free and commercial powershell editors tools that will help you to write and debug powershell script.windows powershell ISE that shipped with windows enable all the abvove and is a great place to start write your first powershell scripts.

Lets be practical
get-member
get-memeber will help you to listing the properties and the methods of object or command.
New-Object Net.Webclient | Get-Member | Out-GridView
Get-Content
Get-Content reads the contents of a file. The –Wait parameter waits for contents to be
appended to the file. The –Tail parameter indicates how many lines from the end of
the file are read.
Get-Content .\test.xml -Wait -Tail 1
Start-Process
The following will print a world file

Start-Process -FilePath "C:\Documents\Test.Docx" -Verb Print
The following will start notepad as an adminstartor
Start-Process notepad.exe -Verb RunAs

Format
${c:data.xml} | Format-Xml -AttributesOnNewLine > data.xml
This will format the data.xml file (the file should be in the current directory). The AttributesOnNewLine parameter will tell the formatter do write attributes in a new line.
Invoke-Item
The Invoke-Item cmdlet provides a way to run an executable file or to open a file (or set of files) from within Windows PowerShell. The following will open all txt files under scripts with your default text editor.
Invoke-Item c:\scripts\*.txt

ConvertTo-Html
Display the result as html. The following will produce a html report of the running process.
Get-Process | ConvertTo-Html name,path,fileversion -title "Process Information" -body "
 Information about the processes running on the computer." | Set-Content c:\scripts\test.htm

Send-Mail
The following will send an email with content , target and vendor as defined in the param map.
Send-MailMessage @param

Invoke-Command
You can invoke commands or run a complete powershell script on a group of remote computers.

Invoke-Command -ComputerName COMPUTER -ScriptBlock { COMMAND } -credential USERNAME

Working with XML
Select-Xml -Xml $x -XPath '//article[contains(body/text(),"ten")]'
'jeho email je karel@novak.cz' -match ' \w+@[a-zA-Z_]+\.(?[a-zA-Z]{2,3})'
get-Process |ogv
This will output a list ,so you can filter, sort, and copy the contents to your clipboard.

You have plenty of cmdlet that will help you to display output in an easy and beautiful way.(xml, html...)

String format
In some cases you need to generate program input based on a pattern this is the place that String.Foramt can help you.
[string]::Format("{0:C}", 1234567890)
$1,234,567,890.00

Stop-Process
You can stop process by name or any other process attribute. The advantage is that you can stop multiple process at the same time and you don't need to look for the process in the task-manager
Stop-Process -processname notepad

You can Stop all SQL services at once
Get-Service *SQL* | Stop-Service -Force

Start-Service
We can start and stop services.The following will open a grid with list of all stopped services. We can chose multiple services for start.
Get-Service | Where Status -eq Stopped |Out-GridView -PassThru |Start-Service
Monitor System Performance
You can do it by monitoring counters and use - Get-Counter
Get-counter -Counter "\Processor(_Total)\% Processor Time" -SampleInterval 2 -MaxSamples 100
Will help you figure out about available command and command parameters.Running the following without specify a specific command will show open a GUI with all available commands.
Show-Command
Get-History
one of the feature that i love in Unix shelll is the history command. You can run history and get a list of all last executed commands (up to some limit that can be configure).
powershell has similar feature.
You can run get-history or h (alias) and you will get commands history.Next to each command you have the command history id , so you can invoke this command by the history-id like this :
Invoke-History   (alias - ihy)
You can do the following in order to complete the command:
#history-id 

Uninstall list of programs
In some cases we want to unistall group of programs, where we group them by name or by vendor or date ... Powershell allow us to do this.

$app = Get-WmiObject -Class Win32_Product | Where-Object {  $_.Name -match "Microsoft sql" }

$app | % { $_.Uninstall() }

Additional resources
Under codeplex  you will find hundreds of powershel extension like powershell for selenium that port some of the webdriver capabilities to powershell...

Powershell magazine  contain hundreds of tips and tricks for powershell.

Windows powershell for developers - I read several books and this one is a must for developers. If you want more advanced example you can take a look at powershell in action

אין תגובות:

הוסף רשומת תגובה