Different command lines-Windows powershell Introduction

Source: Internet
Author: User
Tags true true
Introduction

I have always envied Linux Command Prompt (of course, they are called shell ). The combination of regular expressions, pipelines, and various magical commands can efficiently complete many complex tasks. High efficiency. After more than N years of experience, I finally had the honor to use win7 and encountered an upgraded version of CMD:Windows powershell. From then on, it was incredibly cool. It turned out to be a great tool for Windows ~
Take a look at the following Windows Script, less than 15 lines are validCode. In win7, you only need to right-click the script file and select Run with powershell. The 10 processes that occupy the most memory will be automatically found, and the memory they occupy will be drawn into a three-dimensional pie chart, as shown in.

1 #Create new Excel instance
2  $ Objexcel =New-Object- Comobject excel. Application
3  $ Objexcel. Visible= $ True
4  $ Objworkbook = $ Objexcel . Workbooks. Add ()
5  $ Objworksheet = $ Objworkbook. Worksheets. Item (1 )
6
7  #Write information to the Excel file
8 $ I = 0
9 $ First10 =(PS|Sort WS-Descending|Select-First10 )
10 $ First10 | Foreach - Process { $ I ++ ; $ Objworksheet . Cells. Item ( $ I , 1 ) = $ _ . Name; $ Objworksheet . Cells. Item ( $ I , 2 ) = $ _ . Ws}
11 $ Othermem =(PS|Measure WS-S). Sum-($ First10 |Measure WS- S). Sum
12 $ Objworksheet . Cells. Item ( 11 , 1 ) = " Others " ; $ Objworksheet . Cells. Item ( 11 , 2 ) = $ Othermem
13
14 #Draw the pie chart
15 $ objcharts = $ objworksheet . chartobjects ()
16 $ objchart = $ objcharts . add ( 0 , 0 , 500 , 300 )
17 $ Objchart. Chart. setsourcedata ($ Objworksheet. Range ("A1: B11"),2 )
18 $ Objchart. Chart. charttype= 70
19 $ Objchart. Chart. applydatalabels (5)

(1. This script calls the Excel com library. 2. Of course, from the perspective of command coupling, the output to text format is more advantageous. However, this example mainly describes the power of powershell and the excellent reusability of Microsoft products.3.To manually start powershell, enter powershell and press enter in the search box of the Start Menu.)
After learning about the power of powershell, the following describes the advantages of powershell over command prompt and even Linux Shell in previous versions.

cmdlet + RegEx + pipeline +...

in the past, CMD had many shortcomings over shell, such as fewer commands and weaker command functions, regular expressions are not supported. But now powershell is catching up with a lot. 2.0 RTM the version supports 414 built-in commands (called cmdlet ) and Regular Expressions , powerful pipeline application (in fact, the pipeline has similar functions as before. The key is to come up with a bunch of commands that can use pipelines, such as more, sort, foreach and so on), and the relationship with the system is much closer than before.
for example,
dir Registry: HKEY_CURRENT_USER can directly display the content of the corresponding Registry location, we can see that the Dir function has improved a lot.
PS | sort WS-descending | select-first 10 shows the 10 processes that occupy the maximum memory. You can see the flexible application of pipelines.
Dir-name |? {$ _-Match "(? .). * (\ K ) "} displays files with duplicate characters in the file name in the current directory. For example, abcda. EFG, but ABCD. EFG is not displayed. It can be seen that powershell supports regular expressions quite effectively. (Strictly speaking, the Regular Expression cannot achieve this effect, and the context-independent syntax is required .)
to demonstrate the strength of Linux Shell, Stephen JY I sent my own phone and thought it was amazing before I met powershell, fortunately, it can be implemented now. :-)

(To save the display space, some of the display results of powershell are deleted, but the prompt effect can be verified using the following Script: function prompt {"($ ENV: username)-($ ENV: computername)-('$? : $ ?) -(Jobs: $ (get-job | measure). Count)-($ (get-location) 'n (! $ (History) [-1]). ID + 1)-> "})

Killer-object-oriented

The design philosophy of Linux determines that all input and output are in the text format as much as possible, which facilitates cooperation between processes. This also requires variousProgramProvides powerful text parsing capabilities. However, unlike windows, many input and output in powershell are not plain text (plain text), but objects (objects ). Therefore, powershell is not so much an interactive environment as a powerful language runtime, which is even object-oriented.
For example, when you type get-process to view the list of current processes, the system returns a list like this:

Handles NPM (k) PM (k) WS (k) VM (m) CPU (s) ID processname
-----------------------------------------------
318 8 12948 3872 84 1728 applemobiled
115 5 13816 13328 38 6920 audiodg
1315 21 11732 10988 108 2544 ccmexec
......

Although it looks like a common formatted text, it is actually an array, and each array element is a process-type object. Same as. net, all classes in powershell inherit from objects and support the GetType () function. So we can execute (get-process). GetType () to see its type:

Ispublic isserial name basetype
----------------------------
True true object [] system. Array

The type of each element in the array can be viewed using (get-process) [0]. GetType:

ispublic isserial name basetype
-------- ---- --------
True False process system. componentm...

The ideology-oriented thinking is very obvious. Class Members, methods, and inheritance all appear. I personally feel that this benefit is not to expect that powershell can be used to write large software, but is embodied in two other aspects: First, it makes the built-in cmdlet and its data structure clear and intuitive, code writing speedFast and error-prone. Second, the built-in support for Object-Oriented is also behindSeamless connection to. NET and COM InterfacesProvides the foundation.

Standing on the shoulders of giants-seamless calling of. Net/COM

. NET Framework contains an exceptionally powerful library. To ensure cross-language compatibility at the binary level, Microsoft uses com to encapsulate many libraries. A major feature of powershell is that these libraries can be called directly. For example, in the preceding example, $ objexcel = new-object-comobject excel. application is used to create an Excel object. A script on Wikipedia demonstrates the strength of this seamless call. The script in the following three sentences is used to display the last eight RSS feeds.Article. Note that network connection, content download, XML parsing, and other work are all completed by the. NET library. It is because powershell is on the shoulders of giants that it is always simple and efficient in actual use.

 

$ Rssurl = "Http://blogs.msdn.com/powershell/rss.aspx"  
$ Blog =[XML] (New-Object System. net. WebClient). downloadstring ($ Rssurl )
$ Blog. RSS. Channel. Item|Select title-First8
Edit, run, debug-ide

Windows program development, especially the development based on Microsoft technology, is very nice to have powerful IDE and professional documentation support. Whether it is Visual Studio in Windows or mono develop in Linux, or even a language like powershell, there is an IDE integrating editing and debugging: Windows powershell Ise. With Automatic completion, instant script interaction, debugging, and even remote debugging, powershell scripts can be written as "awesome and powerful ". Of course, the document is also generally powerful,Powershell in msdnStill professional.

Egg camouflage-Profile

With powershell, I seldom go to cmd. However, it is a pleasure to disguise powershell as cmd as a cool B-man. It is not difficult to find that powershell and CMD are only different in five aspects: icon, title, background color, prompt, and displayed text at startup. The icon and background color can be easily modified in the shortcut attributes. Profile is required to modify the title and prompt. Profile is a script that runs automatically every time powershell is started. The script path is set in the $ profile variable. You only need to set $ host. UI. rawui. windowtitle to c: \ windows \ system32 \ cmd.exe to disguise the title as cmd. The custom prompt is naturally very simple in powershell as the current path. As for the display text at startup, you only need to hide the original version information through the/nologo parameter, and then print the text in a line of CMD. Final effect (for more information about the profile, seeThis link)

 

In addition, process-level job scheduling-parallel support?

=================================================== ================================< br> with the rapid development of multi-core processors, from.. NET Framework 4.0 and parallel computing has been repeatedly emphasized. From the parallel tool class added in system. threading to F #, this is a very suitable functional language for parallelization. Microsoft provides strong support for line-Level Parallelism in a timely manner. However, for process-level job scheduling, Windows seems to be quite primitive. For example, if we start five copy sessions on a mobile hard disk at the same time, Windows will start all copy operations at the same time. In this way, the head will repeatedly move (seek) between different target locations, so in the flash of hard drive lights, a lot of time is wasted. Similarly, when we start several processes with a large computing volume, Windows will try to make these processes "go hand in hand ". However, in order to prevent a process from getting starved to death, the system had to switch the process frequently, so a lot of time was wasted on the storage site, process switching, and site recovery. In this way, process-level parallelism is not good enough.

Fortunately, the task scheduling management function is added to powershell. Through a simple experiment, we can find that the scheduling of jobs by powershell is very different from that of Windows by default. It generally maintains high-speed running of processes with the same number of CPU cores, other processes only occupy a small amount of CPU time. After the previous process is finished, a new process enters the high-speed running state. ========================================================== ============================
After more careful experiments, I found that the built-in process scheduling solution for Windows is a small part of high-speed operation (two processes on my dual-core processor Occupy 50% CPU ), most low-speed follow-up (all other processes share the remaining 50% CPU ). In this way, powershell does not improve the current situation of the system. At the same time, the powershell scheduling system requires a large amount of memory, and initialization also takes time. It is even 50% slower than the default Scheduling in actual measurement. The results of this experiment are relatively satisfactory. I don't know why the job is added to powershell. Is it just for asynchronous calls?


[Update] Another post also about powershell can be found in my blog:Http://grapeot.me/post/2011/09/22/Computing-Powershell-as-a-glue-language.aspx

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.