What is Windows PowerShell? You'll understand it after reading this _powershell

Source: Internet
Author: User
Tags documentation

Introduction

Always envy the Linux command prompt (they are called shell, of course). Regular expressions, pipelines, and various magical commands combine to perform many complex tasks efficiently. Efficiency is really high. Flow of n years after the saliva, finally lucky to use the Win7, met the version of CMD: Windows PowerShell. Since then the dark cool, the original Windows also have such a sharp weapon ah ~
Look at the following Windows script, less than 15 lines of valid code. Under Win7, just right-click the script file and select Run with PowerShell to automatically find the 10 processes that make up the most memory, and then draw the memory they occupy into a three-dimensional pie chart, as shown in the following illustration.

Copy Code code as follows:

# Create new Excel instance
  $objExcel = New-object-comobject Exce L.application
  $objExcel. Visible = $True
  $objWorkbook = $objExcel. Workbooks.Add ()
  $objW Orksheet = $objWorkbook. Worksheets.item (1)

 # write information to the Excel file
$i = 0
$first (ps | sort ws-descending | select-first)
$first | foreach-process {$i + +; $objWorksheet. Cells.item ($i, 1) = $_.name; $objWorksheet. Cells.item ($i, 2) = $_.ws}
$otherMem = (ps | measure ws-s). Sum-($first | measure ws-s). Sum
$objWorksheet. Cells.item (11,1) = "others"; $objWorksheet. Cells.item (11,2) = $otherMem

# draw the pie Char T
$objCharts = $objWorksheet. ChartObjects ()
$objChart = $objCharts. ADD (0, 0, $)
$ ObjChart.Chart.SetSourceData ($objWorksheet. Range ("A1:b11"), 2)
$objChart. Chart.charttype =
$ ObjChart.Chart.ApplyDataLabels (5)

(1. This script invokes the COM library of Excel. 2. Of course, from the point of view of the command coupling, the output to the text format is more advantageous, but this example is mainly to illustrate the strong PowerShell and Microsoft's products superior reusability. 3. To manually start the PowerShell, you can type the PowerShell carriage return directly in the search box of the Start menu.
With a simple taste of PowerShell, here are a few ways to introduce the advantages of PowerShell versus previous versions of the command prompt and even the Linux shell.

Cmdlet + Regex + Pipeline + ...

In the past, cmd relative to the shell has many deficiencies, such as fewer commands, some of the command function is weak, the regular expression does not support and so on. But now PowerShell to catch up a lot. The 2.0 RTM version supports 414 commands (known as the Cmdlet), supports regular expressions, and powerful piping applications (in fact, the pipeline itself has the same functionality as it used to be, the key is to have a bunch of commands that can be piped, such as more, sort, foreach, etc.), The connection with the system is much tighter than before.

Give a few examples to illustrate:

Dir Registry::hkey_current_user can directly display the contents of the registry corresponding to the location, you can see that Dir has improved a lot of features.

PS | Sort Ws-descending | Select-first 10 can show the 10 processes that occupy the largest memory, and you can see the flexible application of the pipeline.

Dir-name |? {$_-match "(? <num>.). * (\k<num>) "} can display files with duplicate characters in the current directory. such as ABCDA.EFG, and ABCD.EFG will not show it. You can see that PowerShell's support for regular expressions is pretty strong. (exact, strict regular expressions are no longer possible, and need context-free grammars to support them.) )
Previously in order to demonstrate the power of the Linux shell, Stephenjy sent a screenshot of his own, before meeting PowerShell feel good magic, fortunately now can also be achieved. :-)

(In order to save the display space, the partial display result of PowerShell is deleted, but this prompt effect can be validated with the following script: function prompt {"($env: Username)-($env: ComputerName)-(' $?: $ ?) -(Jobs: $ (get-job | measure). Count)-($ (get-location)) ' N (! $ ((history) [-1]). ID + 1))-> "})

Large kill device-object oriented

The design idea of Linux determines that all inputs and outputs are as text-formatted as possible, so that cooperation between processes can be facilitated. This also requires that each program provide a certain strength of the text parsing ability. But the idea of Windows is different, and many of the input and output in PowerShell are not plain text (plain text), but rather an object (objects). So rather than PowerShell is an interactive environment, it is more of a powerful language than the runtime, and this language is even object-oriented.

For example, when you type get-process to view the current list of processes, the system returns a list of these:

Copy Code code as follows:

Handles NPM (k) PM (k) WS (k) VM (M) CPU (s) Id ProcessName
-------  ------    -----      ----- -----   ------     -- -----------
318 8 12948 3872 1728 applemobiled
5 13816 13328 6920 AUDIODG
1315 11732 10988 108 2544 ccmexec
... ...

Although it appears to be a general format text, it is actually an array, and each array element is an object of the process type. In the same vein as. NET, all classes in PowerShell inherit from object and support the GetType () function. So we can execute (get-process). GetType () to see its type:

Copy Code code as follows:

IsPublic isserial Name BaseType
-------- -------- ----                                     --------
True object[] System.Array

The type of each element in the array can be used (get-process) [0]. GetType () View:
Copy Code code as follows:

IsPublic isserial Name BaseType
-------- -------- ----                                     --------
True False Process System.componentm ...

The thought-oriented thinking is so obvious that class members, methods, and inheritance all appear. Personal feeling that this benefit is not expected to be able to write what large software PowerShell, but in two other ways: first, so that the built-in cmdlet and its data structure organization clear, intuitive, write code fast and error-prone. Second, the object-oriented built-in support also seamlessly joins the back. NET and COM interfaces provide the foundation.

Standing on the shoulders of giants--called seamlessly. net/com

The. NET framework contains an unusually powerful library, and many libraries are packaged with COM to ensure cross-language compatibility at the binary level. A big feature of PowerShell is that you can call these libraries directly. For example, the previous example creates an Excel object with $objexcel = New-object-comobject Excel.Application. A script on Wikipedia also demonstrates the power of this seamless invocation. The following 3-sentence script works by displaying the title of the most recent 8 posts in an RSS feed. Note that the network connection, content download, XML parsing and so on are all completed by the. Net Library, because standing on the shoulders of giants, PowerShell in the actual use of both sides, simple and efficient.

Copy Code code as follows:

$RSSURL = "Http://blogs.msdn.com/powershell/rss.aspx"
$blog = [XML] (New-object System.Net.WebClient). Downloadstring ($RSSURL)
$blog. Rss.channel.item | Select Title-first 8

Edit, run, Debug-IDE

The development of Windows programs, especially based on Microsoft technology, is a great way to have powerful Ides and professional documentation to support it. Whether it's Visual Studio under Windows or mono develop under Linux, even PowerShell languages have ide:windows PowerShell ISE, which integrates editing and debugging. With automatic completion, instant scripting interaction, debugging, and even remote debugging, the PowerShell script writes "Very nice and strong". Of course the documentation is also strong, and the MSDN section on PowerShell is still a professional expanse.

The disguise of egg ache-profile

With the PowerShell, rarely went to CMD. However, as an egg-ache outfit B male, the PowerShell disguised as a CMD is also quite a fun thing. It's not hard to find that PowerShell and CMD differ only in the five aspects of the icon, title, background color, prompt, and display text when it's just started. Icons and background colors can be easily modified in shortcut properties. and the title and prompt changes will be used to profile. Profile is a script that runs automatically every time the PowerShell is started. The path to this script is set in the $profile variable. Just set the $host. Ui. Rawui.windowtitle for C:\windows\system32\cmd.exe will be able to disguise the title as CMD. And the custom prompt is the current path, which is naturally very simple in PowerShell. As for the start of the display text, as long as the/nologo parameters to hide the original version of information, and then print a line of CMD in the text is good. The final effect is as follows: (see this link for profile)

Another: Process-level job scheduling – parallel support?

==========================================================
With the rapid development of multi-core processors, parallel computing has been emphasized repeatedly since the. NET Framework 4.0. From the newly-added parallel tool class in System.Threading to F #, a functional language that is well-suited to parallelism, Microsoft provides strong support for thread-level parallelism in due course. However, for process-level work scheduling, Windows seems quite primitive. For the simplest example, if we start 5 copy sessions to a mobile hard disk at the same time, Windows starts all copies at the same time. This allows the head to repeatedly make meaningless moves between different target locations, so that in the flash of the hard drive light, a lot of time is wasted. Also, when we start several computationally large processes at the same time, Windows tries to keep these processes "going hand in hand". However, in order to avoid a process is starved to death, the system has to frequently switch processes, so a lot of time has been wasted in the preservation of the site, process switching, restore the scene. In this way, process-level parallelism is not good enough.

Fortunately, PowerShell has been added to the task scheduling management function. With simple experiments, we can see that PowerShell's schedule to jobs is very different from Windows default, which typically maintains the same processes as the CPU core, while other processes take up only a fraction of the CPU time. Until the previous process has finished working, a new process is followed by a fast running state. ==========================================================
Later, after a more careful experiment, it was found that the original Windows built-in process scheduling scheme is a small number of high-speed operations (on my dual-core processor two processes Occupy 50%cpu), most of the low-speed follow-up (all other processes share the remaining 50%cpu). This powershell work scheduling does not improve the original status of the system. At the same time, due to the PowerShell scheduling system needs to occupy a small amount of memory, initialization also takes a while. It is even 50% slower than the default schedule in actual measurement. The results of this experiment are rather awkward. Do not know why PowerShell to join the job this thing, just for asynchronous call it?

Related Article

E-Commerce Solutions

Leverage the same tools powering the Alibaba Ecosystem

Learn more >

11.11 Big Sale for Cloud

Get Unbeatable Offers with up to 90% Off,Oct.24-Nov.13 (UTC+8)

Get It Now >

Alibaba Cloud Free Trial

Learn and experience the power of Alibaba Cloud with a free trial worth $300-1200 USD

Learn more >

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.