Created Learn PowerShell

This commit is contained in:
Jianyun Tao 2016-07-12 13:21:15 -07:00
parent ca1780255f
commit ecb21e9544
5 changed files with 544 additions and 0 deletions

View file

@ -0,0 +1,102 @@
Learning PowerShell
====
Whether you're new to programming or an experienced developer, we'll help you get started with PowerShell.
In this document we'll cover the following: installing PowerShell, samples walkthrough, PowerShell editor, debugger, testing tools and a map book for experienced bash users to get started with PowerShell faster. The exercises in this document are intended to give you a solid foundation in how to use PowerShell and get PowerShell to do work for you. You won't be a PowerShell guru at the end of reading this material but you will be well on your way with the right set of knowledge to start using PowerShell. If you have 30 minutes now, lets try it.
Installing PowerShell
----
First you need to setup your computer working environment if you have not done so. Choose the platform below and follow the instructions. At the end of this exercise, you should be able to launch the PowerShell session.
- [PowerShell on Linux][powershell-on-linux]
- [PowerShell on OS X][powershell-on-os-x]
- PowerShell on Windows
For this tutorial, you do not need to install PowerShell if you are running on Windows. You can launch PowerShell command console by pressing Windows Key and typing PowerShell, and clicking on 'Windows PowerShell'.
[powershell-on-linux]: https://github.com/PowerShell/PowerShell/blob/master/docs/building/linux.md
[powershell-on-os-x]: https://github.com/PowerShell/PowerShell/blob/master/docs/building/osx.md
TODO: Raghu for setup-dev-environment.md
Getting Started with PowerShell
----
PowerShell command has a Verb-None structure with a set of parameters. It's easy to learn and use PowerShell. For example, "Get-Process" will display all the running processes on your system. Let's walk through with a few examples by clicking on the [PowerShell Beginner's Guide](powershell-beginners-guide.md).
Now you have learned the basics of PowerShell. Please continue reading: Editor, Debugger, and Testing Tool if you want to do some development work in PowerShell.
PowerShell Editor
----
In this section, you will create a PowerShell script using PowerShell editor. You can certainly use your favorite editor to write scripts. As an example, we use Visual Studio Code (VS Code) which works for Windows, Linux, or OS X. Click on the following link to start create your first PowerShell script, let's say helloworld.ps1.
- [Using Visual Studio Code (VS Code)][use-vscode-editor]
On Windows, you can also use [PowerShell Integrated Scripting Environment (ISE)][use-ise-editor] to edit PowerShell scripts.
[use-vscode-editor]:./using-vscode.md#editing-with-vs-code
[use-ise-editor]:./using-ise.md#editing-with-ise
PowerShell Debugger
----
Assuming you have written a PowerShell script which may contains a software bug, you would like to fix the issue via debugging. As an example, we use VS Code. Click on the link below to start debugging:
- [Using Visual Studio Code (VS Code)][use-vscode-debugger]
On Windows, you can also use [ISE][use-ise-debugger] to debug PowerShell scripts.
[use-vscode-debugger]:./using-vscode.md#debugging-with-vs-code
[use-ise-debugger]:./using-ise.md#debugging-with-ise
PowerShell Testing
----
We recommend using Pester testing tool which is initiated by the PowerShell Community for writing test cases. To use the tool please read [ Pester Guides](https://github.com/pester/Pester) and [Writing Pester Tests Guidelines](https://github.com/PowerShell/PowerShell/blob/master/docs/testing-guidelines/WritingPesterTests.md).
Map Book for Experienced Bash users
----
TODO: Don & JP to fill in
| Bash | PowerShell | Description |
|:---------------|:--------------|:----------------|
| ls |ls |List files and folders
| cd |cd |Change directory
| mkdir |mkdir |Create a new folder
| Clear, Ctrl+L, Reset | cls | Clear screen
| | | |
| | | ||
More Reading
----
- Microsoft Virtual Academy: [GetStarted with PowerShell][getstarted-with-powershell]
- [Windows PowerShell in Action][in-action] by Bruce Payette
- [Why Learn PowerShell][why-learn-powershell] by Script Guy
- [Introduction to PowerShell][powershell-intro] from Pluralsight
- PowerShell Web Docs: [Basic cookbooks][basic-cookbooks]
- [PowerShell eBooks][ebooks-from-powershell.com] from PowerShell.com
- [PowerShell Training and tutorials][lynda-training] from Lynda.com
- [Learn PowerShell][channel9-learn-powershell] from channel9
- [Learn PowerShell Video Library][powershell.com-learn-powershell] from PowerShell.com
- [PowerShell Quick Reference][quick-reference] by PowerShellMagazine.com
- [PowerShell 5 How-To Videos][script-guy-how-to] by Script Guy
[getstarted-with-powershell]: https://channel9.msdn.com/Series/GetStartedPowerShell3
[in-action]: https://www.amazon.com/Windows-PowerShell-Action-Second-Payette/dp/1935182137
[why-learn-powershell]: https://blogs.technet.microsoft.com/heyscriptingguy/2014/10/18/weekend-scripter-why-learn-powershell/
[powershell-intro]: https://www.pluralsight.com/courses/powershell-intro
[basic-cookbooks]: https://msdn.microsoft.com/en-us/powershell/scripting/getting-started/basic-cookbooks
[ebooks-from-powershell.com]: http://powershell.com/cs/blogs/ebookv2/default.aspx
[lynda-training]: https://www.lynda.com/PowerShell-training-tutorials/5779-0.html
[channel9-learn-powershell]: https://channel9.msdn.com/Search?term=powershell#ch9Search
[powershell.com-learn-powershell]: http://powershell.com/cs/media/14/default.aspx
[quick-reference]: http://www.powershellmagazine.com/2014/04/24/windows-powershell-4-0-and-other-quick-reference-guides/
[script-guy-how-to]:https://blogs.technet.microsoft.com/tommypatterson/2015/09/04/ed-wilsons-powershell5-videos-now-on-channel9-2/

View file

@ -0,0 +1,273 @@
PowerShell Beginners Guide
====
If you are new to PowerShell, this document will walk you through a few examples to give you some basic ideas of PowerShell. We recommend that you open a PowerShell console/session and type along with the instructions in this document to get most out of this exercise.
Launch PowerShell Console/Session
---
Follow the [Installing PowerShell](./learning-powershell.md "Installing PowerShell") instruction you can install the PowerShell and launch the PowerShell session.
Getting Familiar with PowerShell Commands
---
As mentioned above PowerShell commands is designed to have Verb-Noun structure, for instance Get-Process, Set-Location, Clear-Host, etc. Lets exercise some of the basic PowerShell commands also known as **cmdlets**.
**1. Get-Process**: displays the processes running on your system.
By default, you will get data back similar to the following:
``` PowerShell
PS C:\>Get-Process
Handles NPM(K) PM(K) WS(K) VM(M) CPU(s) Id ProcessName
------- ------ ----- ----- ----- ------ -- -----------
147 11 2108 9316 ...82 0.02 12 notepad
174 12 4276 1460 ...53 3.56 309 cmd
121 9 1580 3096 ...85 3.94 8620 svchost
2168 374 448940 321504 820 867.39 1209 iexplore
```
Only interested in the instance of notepad that are running on your computer? Try this:
```PowerShell
PS C:\> Get-Process -Name notepad
Handles NPM(K) PM(K) WS(K) VM(M) CPU(s) Id ProcessName
------- ------ ----- ----- ----- ------ -- -----------
147 11 2108 9316 ...82 0.02 12 notepad
```
Want to get back more than one process? Then just specify process names, separating with commas. For example,
```PowerShell
PS C:\> Get-Process -Name notepad, iexplore
Handles NPM(K) PM(K) WS(K) VM(M) CPU(s) Id ProcessName
------- ------ ----- ----- ----- ------ -- -----------
1753 247 418220 194960 991 385.97 1748 iexplore
144 11 2152 9320 ...82 0.08 30004 notepad
```
**2. Clear-Host**: Clears the display in the command window
```PowerShell
PS C:\> Get-Process
PS C:\> Clear-Host
```
Type too much just for clearing the screen? Here is how the alias can help.
**3. Get-Alias**: Improves the user experience by using the Cmdlet aliases
To find the available aliases, you can type below cmdlet:
```PowerShell
PS C:\> Get-Alias
CommandType Name
----------- ----
Alias cat -> Get-Content
Alias cd -> Set-Location
Alias cls -> Clear-Host
Alias cp -> Copy-Item
Alias clv -> Clear-Variable
Alias gmo -> Get-Module
Alias man -> help
Alias rm -> Remove-Item
Alias ls -> Get-ChildItem
Alias type -> Get-Content
As you can see "cls" is an alias of Clear-Host. Now try it:
PS C:\> Get-Process
PS C:\> cls
```
**4. cd - Set-Location**: change your current working directory
```PowerShell
PS C:\> Set-Location C:\test
PS C:\test>
```
**5. ls or dir - Get-ChildItem**: list all items in the specified location
```PowerShell
Get all files under the current directory:
PS C:\test> Get-ChildItem
Get all files under the current directory as well as its subdirectories:
PS C:\test> dir -Recurse
List all files with file extension "txt".
PS C:\test> ls Path *.txt -Recurse -Force
```
**6. New-Item**: Create a file
```PowerShell
An empty file is created if you type the following:
PS C:\test> New-Item -Path c:\test\test.txt
Directory: C:\test
Mode LastWriteTime Length Name
---- ------------- ------ ----
-a---- 7/7/2016 7:17 PM 0 test.txt
```
You can use the **-value** parameter to add some data to your file. For example, the following command adds the phrase "Hello World" as a file content to the test.txt. Because the test.txt file exists already, we use **-force** parameter to replace the existing content.
```PowerShell
PS C:\test> New-Item -Path c:\test\test.txt -Value "Hello World!" -force
Directory: C:\test
Mode LastWriteTime Length Name
---- ------------- ------ ----
-a---- 7/7/2016 7:19 PM 12 test.txt
```
There are other ways to add some data to a file, for example, you can use Set-Content to set the file contents:
```PowerShell
PS C:\test>Set-Content -Path c:\test\test.txt -Value "Hello World too!"
```
Or simply use ">>" as below:
```
# create an empty file
"" > empty.txt
# set "hello world!!!" as content of text.txt file
"hello world!!!" > test.txt
```
The pound sign (#) above is used for comments in PowerShell.
**7. type, cat - Get-Content**: get the content of an item
```PowerShell
PS C:\>Get-Content -Path "C:\Test\test.txt"
PS C:\>type -Path "C:\Test\test.txt"
Hello World!
```
**8. rm, del - Remove-Item**: delete a file or folder
This cmdlet will delete the file c:\test\test.txt:
```PowerShell
PS C:\test> Remove-Item c:\test\test.txt
```
**9. Exit**: - to exit the PowerShell session, type "exit"
```PowerShell
PS C:\test> exit
```
Need Help?
----
The most important command in PowerShell is possibly the Get-Help, which allows you to quickly learn PowerShell without having to surfing around the Internet. The Get-Help cmdlet also shows you how PowerShell commands work with examples.
PS C:\>**Get-Help**
You can use this cmdlet to get help with any PowerShell commands.
PS C:\>**Get-Help -Name Get-Process**
It shows the syntax and other technical information of the Get-Process cmdlet.
PS C:\>**Get-Help -Name Get-Process -Examples**
It displays the examples how to use the Get-Process cmdlet.
If you use **-full** parameter, i.e., "Get-Help -Name Get-Process -Full", it will display more technical information.
Discover All Commands Available on Your System
----
You want to discover what PowerShell cmdlets available on your system. Simple, just run "Get-Command" as below.
PS C:\> **Get-Command**
If you want to know whether a particular cmdlet exists on your system, you can do something like below:
PS C:\> **Get-Command Get-Process**
If you want to know the syntax of Get-Process cmdlet, type
PS C:\> **Get-Command Get-Process -Syntax**
If you want to know how to sue the get-process, type
PS C:\> **Get-Help Get-Process -example**
PowerShell Pipeline '|'
----
Sometimes when you run Get-ChildItem or "dir", you want to get a list of files in a descending order. To archive that, type:
```PowerShell
PS C:\> dir | sort -Descending
```
Say you want to get the largest file in a directory
```PowerShell
PS C:\> dir | sort -Property length -Descending | Select-Object -First 1
Directory: C:\
Mode LastWriteTime Length Name
---- ------------- ------ ----
-a---- 5/16/2016 1:15 PM 32972 test.log
```
How to Create and Run PowerShell scripts
----
- You can use ISE, VS Code, or any favorite editor to create a PowerShell script and save the script with a .ps1 file extension (helloworld.ps1 in the example)
- To run the script, cd to your current folder and type .\helloworld.ps1
See [Running PowerShell Scripts Is as Easy as 1-2-3] [run-ps] for more details.
[run-ps]:http://windowsitpro.com/powershell/running-powershell-scripts-easy-1-2-3
More Reading
----
Books & eBooks & Blogs & Tutorials
- [Windows PowerShell in Action][in-action] by Bruce Payette
- [Windows PowerShell Cookbook][cookbook] by Lee Holmes
- [eBooks from PowerShell.org](https://powershell.org/ebooks/)
- [eBooks List][ebook-list] by Martin Schvartzman
- [eBooks from PowerShell.com][ebooks-powershell.com]
- [Tutorial from MVP][tutorial]
- Script Guy blog: [The best way to Learn PowerShell][to-learn]
- [Understanding PowerShell Module][ps-module]
- [How and When to Create PowerShell Module][create-ps-module] by Adam Bertram
- Video: [Get Started with PowerShell Remoting][remoting] from Channel9
- Video: [PowerShell Remoting in Depth][in-depth] from Channel9
- [PowerShell Basics: Remote Management][remote-mgmt] from ITPro
- [Running Remote Commands][remote-commands] from PowerShell Web Docs
- [Samples for PowerShell Scripts][examples]
- [Samples for Writing a PowerShell Script Module][examples-ps-module]
- [Writing a PowerShell module in C#][writing-ps-module]
- [Examples of Cmdlets Code][sample-code]
[in-action]: https://www.amazon.com/Windows-PowerShell-Action-Second-Payette/dp/1935182137
[cookbook]: http://shop.oreilly.com/product/9780596801519.do
[ebook-list]: https://blogs.technet.microsoft.com/pstips/2014/05/26/free-powershell-ebooks/
[ebooks-powershell.com]: http://powershell.com/cs/blogs/ebookv2/default.aspx
[tutorial]: http://www.computerperformance.co.uk/powershell/index.htm
[to-learn]:https://blogs.technet.microsoft.com/heyscriptingguy/2015/01/04/weekend-scripter-the-best-ways-to-learn-powershell/
[ps-module]:https://msdn.microsoft.com/en-us/library/dd878324%28v=vs.85%29.aspx
[create-ps-module]:http://www.tomsitpro.com/articles/powershell-modules,2-846.html
[remoting]:https://channel9.msdn.com/Series/GetStartedPowerShell3/06
[in-depth]: https://channel9.msdn.com/events/MMS/2012/SV-B406
[remote-mgmt]:http://windowsitpro.com/powershell/powershell-basics-remote-management
[remote-commands]:https://msdn.microsoft.com/en-us/powershell/scripting/core-powershell/running-remote-commands
[examples]:http://examples.oreilly.com/9780596528492/
[examples-ps-module]:https://msdn.microsoft.com/en-us/library/dd878340%28v=vs.85%29.aspx
[writing-ps-module]:http://www.powershellmagazine.com/2014/03/18/writing-a-powershell-module-in-c-part-1-the-basics/
[sample-code]:https://msdn.microsoft.com/en-us/library/ff602031%28v=vs.85%29.aspx

View file

@ -0,0 +1,74 @@
Using PowerShell Integrated Scripting Environment (ISE)
====
The PowerShell ISE works on Windows. If you are not using Windows, please see [Using VS Code](./using-vscode.md).
Editing with ISE
---
- Launch PowerShell ISE
* Press Windows Key -> type PowerShell ISE, click on PowerShell ISE to launch the ISE
- Create a new PowerShell Script
* Click on File -> New
* Add a few lines of PowerShell scripts in your newly created file, for example,
```PowerShell
# Convert Fahrenheit to Celsius
function ConvertFahrenheitToCelsius([double] $fahrenheit)
{
$celcius = $fahrenheit - 32
$celcius = $celcius / 1.8
$celcius
}
$fahrenheit = Read-Host 'Input a temperature in Fahrenheit'
$result =[int](ConvertFahrenheitToCelsius($fahrenheit))
Write-Host "$result Celsius"
```
* **Note**: You can find more examples [here](http://examples.oreilly.com/9780596528492/).
- Save the script file
* Click on File-> Save As -> type "helloworld.ps1"
- Close the helloworld.ps1
* File-> Close
- Reopen the helloworld.ps1
* File-> Open, then choose helloworld.ps1.
- For more details, go to [How to Write and Run Scripts in the Windows PowerShell ISE](https://msdn.microsoft.com/en-us/powershell/scripting/core-powershell/ise/how-to-write-and-run-scripts-in-the-windows-powershell-ise).
Debugging with ISE
----
To execute the entire script file, you can press **F5**; to execute several lines of your scripts, simply select them and press **F8**. However sometimes you would like to stop the execution on a particular line in order to exam some variables to check if the program runs as expected. In that case, you may follow the steps below. Let's take the helloworld.ps1 as an example and assume line 17 is the place where you want to stop.
- Set a break point: Move mouse over on the line 17, and press **F9**. You will see the line 17 is highlighted which means a breakpoint gets set.
- Press **F5** to run the script
- Enter 80 (or any number in Fahrenheit) from the command line prompt
- Notice that the ISE output pane becomes “[DBG]: PS C:\Test>>” prompt. This means the program is in the debugging mode. It stops at Line 17:
```PowerShell
PS C:\test> C:\test\helloword.ps1
Input a temperature in Fahrenheit: 80
Hit Line breakpoint on 'C:\test\helloword.ps1:17'
''[DBG]: PS C:\test>>'
```
- From the output pane, you can type $celcius and $fahrenheit to exam these variables to see if they are correct.
```PowerShell
[DBG]: PS C:\Test>> $celcius
26.6666666666667
[DBG]: PS C:\Tset>> $fahrenheit
80
```
- Press **F5** to let the program continue running
```PowerShell
[DBG]: PS C:\test>>
27 Celsius
PS C:\test>
```
See [How to Debug in ISE][debug] for more information.
[debug]:https://msdn.microsoft.com/en-us/powershell/scripting/core-powershell/ise/how-to-debug-scripts-in-windows-powershell-ise#bkmk_2

View file

@ -0,0 +1,95 @@
Using Visual Studio Code (VS Code)
====
If you are working on Linux and OS X, you cannot use ISE because it is not supported on these platforms. In this case you can choose your favorite editor to write PowerShell scripts. Here we choose VS Code as a PowerShell editor as an example.
You can use VS Code on Windows with PowerShell V5 by using Windows 10 or by installing [Windows Management Framework 5.0 RTM](https://www.microsoft.com/en-us/download/details.aspx?id=50395) for down-level Windows OSs.
Before starting it, please make sure PowerShell exists on your system. Follow the [Installing PowerShell](./learning-powershell.md "Installing PowerShell") instruction you can install the PowerShell and launch the PowerShell session.
Editing with VS Code
----
[**1. Installing VS Code**](https://code.visualstudio.com/Docs/setup/setup-overview)
* **Linux**: follow the Installation instructions in the [Running VS Code on Linux](https://code.visualstudio.com/docs/setup/linux) to setup VS Code application
* **OS X**: follow the Installation instructions in the [Running VS Code on OS X](https://code.visualstudio.com/docs/setup/osx) to setup VS Code application
* **Windows**: download and install VS Code for your OS from [Visual Studio Code website](https://code.visualstudio.com/docs/setup/windows).
**2. Installing PowerShell Extension**
- Launch the Visual Studio Code app by:
* **Windows**: typing **code** in your PowerShell session
* **Linux**: typing **code .** in your terminal
* **OS X**: typing **code** in your terminal
- Press **F1** (or **Ctrl+Shift+P**) which opens up the “Command Palette” inside the VS Code app.
- In the command palette, type **ext install** and hit Enter. It will show all VS Code extensions available on your system.
- Choose PowerShell and click on Install, you will see something like below
![VSCode](vscode.png)
- After the install, you will see the **Install** button turns to **Enable**.
- Click on Enable and OK
- Now you are ready for editing.
Debugging with VS Code
----
- Open a file folder (**File->Open Folder**) where contains the PowerShell modules or scripts you have written already and want to debug. In this example, we saved helloworld.ps1 under c:\test\debug. Thus we select the "debug" folder and open it in VS Code.
- Creating the Debug Configuration (launch.json)
Because some information regarding your scripts is needed for debugger to start executing your script, we need to set up the debug config First. This is one time only to debug PowerShell scripts under your current folder.
* Click on the **Debug** icon (or **Ctrl+Shift+D**)
* Click on the **Settings** icon that looks like a gear. The VS Code will prompt you to **Select Environment**. Choose **PowerShell**. Then the VS code will auto create a debug configuration settings file in the same folder. It looks like the following:
```json
{
"version": "0.2.0",
"configurations": [
{
"name": "PowerShell",
"type": "PowerShell",
"request": "launch",
"program": "${file}",
"args": [],
"cwd": "${file}"
},
{
"name": "PowerShell x86",
"type": "PowerShell x86",
"request": "launch",
"program": "${file}",
"args": [],
"cwd": "${file}"
}
]
}
```
- Once the debug configuration is established, now go to your helloworld.ps1 and set a breakpoint by pressing **F9**.
- Press **F5** to let the run.
There are a few blogs that may be helpful to get you started using PowerShell extension for VS Code
- Visual Studio Code: [PowerShell Extension][ps-extension]
- [Write and debug PowerShell scripts in Visual Studio Code][debug]
- [Debugging VS Code Guidance][vscode-guide]
- [Debugging PowerShell in VS Code][ps-vscode]
[ps-extension]:https://blogs.msdn.microsoft.com/cdndevs/2015/12/11/visual-studio-code-powershell-extension/
[debug]:https://blogs.msdn.microsoft.com/powershell/2015/11/16/announcing-powershell-language-support-for-visual-studio-code-and-more/
[vscode-guide]:https://johnpapa.net/debugging-with-visual-studio-code/
[ps-vscode]:https://github.com/PowerShell/vscode-powershell-ops/tree/master/vscode-powershell/examples
PowerShell Extension for VS Code
----
PowerShell extension source code can be found [GitHub](https://github.com/PowerShell/vscode-powershell-ops)

Binary file not shown.

After

Width:  |  Height:  |  Size: 182 KiB