Comparison of PowerShell and Unix Shell: eight instances

Source: Internet
Author: User

This document compares PowerShell and Unix Shell, usually Linux Bourne Shell, including sh, ksh, and bash ). There is a big difference between the two. The biggest difference is that PowerShell uses objects as basic operation units, while Unix Shell uses strings as basic units. Likewise, they have a large number of built-in commands, it also allows user scaling.

1 instance: Terminate the process

To terminate all processes starting with "p" in a Unix operating system, run the following command in the command line:

$ ps -e | grep " p" | awk '{ print $1 }' | xargs kill

Use the ps command to obtain the list of current processes and output the obtained text to the grep command. This command searches for processes whose names start with "p. Send the output to the awk command, and select the 1st column here as the process ID) and output it to the xargs command. The xargs command will execute the kill command for each process, terminate all processes starting with "p. Despite the implementation of the function, the entire command is not reliable. Because the execution results of ps commands vary in different operating systems and even in different versions of the same operating system ). If the-e option is not supported for the ps column containing the process ID during execution, it is not necessarily the 1st column. In this case, the command line execution may fail.

Similarly, to execute the same command in PowerShell, you only need to perform the following operations:

PS C:\> get-process p* | stop-process

The command here finds all processes starting with "p" and terminates them. The Get-Process cmdlet carries parameters that need to match the Process name. The result object is directly passed to the Stop-Process cmdlet to end the corresponding object Process.

2. Example: end the filtering process.

To find and kill processes that occupy more than 10 MB of memory, run the following command on the Unix command line:

$ ps -el | awk '{ if ( $6 > (1024*10)) { print $3 } }' |grep -v PID | xargs kill

The execution of this command depends on the user's knowledge that the ps-el command will return the memory occupied by the process in column 6th in KB) and contains the PID attribute in column 3rd, at the same time, you need to remove the 1st lines output by the ps command.

Next, check the corresponding script in PowerShell:

PS C:\> get-process | where { $_.WS -gt 10MB } | stop-process

We can see the advantages of Object-based commands compared with text-based commands, that is, you do not have to worry about the size of memory occupied by processes or the columns containing the process ID. The memory usage can be referenced by the process name. The Where cmdlet can check the input object and obtain the object attributes.

3. Example: Calculate the directory size.

In this example, the file size in a directory is calculated, the file is traversed, The Length attribute is obtained, and the variable is superimposed into a variable. Finally, the variable is printed. The Processing Method in Unix systems is as follows:

$ tot=0; for file in $( ls )> do> set -- $( ls -log $file )> echo $3> (( tot = $tot + $3 ))> done; echo $tot

In the preceding example, the set command is used to create variables for each space-separated element. This is a Unix Command that is usually used before the awk command appears. If the awk command is used, a considerable amount of code will be reduced, as shown below:

$ ls –l | awk ‘{ tot += $5; print tot; }’ | tail -1

This reduces the complexity of the command, but you need to know that the Length attribute is in the 5th column, and the awk versions may be different. The loop in PowerShell is also very simple. Although it also needs to be traversed one by one, it is very convenient to obtain the Length attribute. Because the length is the property of the file object, you do not need to care about its column. Similar scripts are as follows:

PS C:\> get-childitem | measure-object -Property length -SumCount    : 53Average  :Sum      : 489648208Maximum  :Minimum  :Property : length

The Measure-Object cmdlet is used to determine the attribute to be operated based on the input-Property. Based on the input options, for example,-Sum,-Maximum,-Minimum, and-Average perform Sum, Maximum, Minimum, and Average for the previously specified object attributes. To match the preceding Unix script, you only need to specify the Length attribute and the-Sum option.

4. instance: Dynamic Operation Value

Many objects provided by the system are usually dynamic, not static. That is, you do not need to obtain the data of an object later, because the data is constantly updated based on changes in system conditions. And modifying these objects will take effect immediately in the system. Such objects are called "real-time objects ".

For example, to obtain the CPU processing time occupation, the ps commands in the traditional Unix Shell run repeatedly to continuously obtain the running status of the process. For objects that can access Real-Time Processes, you only need to obtain the processing object once. Once an object is updated by the system, you only need to read the same attributes continuously. In the following example, the memory occupied by the application is obtained at an interval of 10 seconds. First, check the processing method of the Unix Shell script:

$ while [ true ]domsize1=$(ps -el|grep application|grep -v grep|awk '{ print $6}')sleep 10msize2=$(ps -el|grep application|grep -v grep|awk '{print $6}')expr $msize2 - $msize1msize1=$msize2done

You can use PowerShell as follows:

PS C:\>> $app = get-process applicationNamePS C:\>> while ( $true ) {>> $msize1 = $app.VM>> start-sleep 10>> $app.VM - $msize1>> }

Obviously, PowerShell scripts are easier to read.

5. instance: monitors the service life of a process.

If you determine whether a specific process continues to run under Unix, You need to collect the process list and compare it with another list. For example:

$ processToWatch=$( ps -e | grep application | awk '{ print $1 }'$ while [ true ]> do> sleep 10> processToCheck=$(ps -e |grep application |awk '{print $1}' )
> if [ -z "$processToCheck" -or \
> "$processToWatch" != "$processToCheck" ]
> then
> echo "Process application is not running"
> return
> fi
> done

In PowerShell, you only need to perform the following operations:

PS C:\> $processToWatch = get-process applicationNamePS C:\> $processToWatch.WaitForExit()

PowerShell only needs to get the object and wait for the object to exit.

6. Example: Determine whether the software has a pre-release beta version.

Pre-release beta versions are often unstable and may have various defects. This leads to system security risks, so it is necessary to distinguish such software. This type of information is not stored in Unix executable files, so it is not necessary to discuss the situation in Unix Shell. For Windows, a specific tool is required to check whether a prerelease test version exists in the currently running process. For example:

PS C:\> Get-Process | where  {>> $_.mainmodule.FileVersioninfo.isPreRelease}>> Handles  NPM(K)    PM(K)      WS(K) VM(M)   CPU(s)     Id ProcessName-------  ------    -----      ----- -----   ------     -- -----------    627      17    29236       5120   177     7.66    560 Powerword

This instance uses the stacked attributes to check the attributes obtained from the MainModule of the process object. The FileVersionInfo attribute is a reference of MainModle, and its attribute IsPreRelease is used to determine whether the software is a prerelease version. If this attribute is true, the objects output by the Get-Process cmdlet will be output to the console.

7. Example: Convert string case

In Unix Shell, the following method is usually used to convert the case of a specific string:

$ echo "this is a string" | tr [:lower:] [:upper:]

Or use:

$ echo "this is a string" | tr '[a-z]' '[A.Z]'

PowerShell is easier, such:

PS (1) > "this is a string".ToUpper()

This directly uses the ToUpper () method of the string object to convert uppercase letters in the string to lowercase letters. To convert uppercase letters to lowercase letters, use the ToLower () method.

8. Example: insert characters into a string

For example, you need to insert the string "ABC" into the first letter of the string "string" to obtain a string similar to "sABCtring. Use the sed command in Unix Shell:

$ echo "string" | sed "s|\(.\)\(.*)|\1ABC\2|"

In PowerShell, use the regular expression:

PS (1) > "string" -replace '(.)(.*)','$1ABC$2'sABCtring

In PowerShell, the simpler method is to use the Insert () method to directly Insert a String object, for example:

PS (2) > "string".Insert(1,"ABC")sABCtring

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.