(20) Special operators in PowerShell

Source: Internet
Author: User
Tags arithmetic operators bitwise operators logical operators parent directory

In Powershell, in addition to the usual arithmetic operators, assignment operators, comparison operators, bitwise operators, logical operators, split and merge operators of strings, escape characters, and special operators, these special operators can often solve special problems such as executing a Run command, Change the data type of the value, and so on.


    1. & (call operator)

Use the & (call operator) to run a command, script, or script block. Because the call operator is not parsed, it cannot interpret the command arguments. This call operator is used to indicate that the value following it is a command (not a string). Use this operator to run a command stored in a variable and represented by a string. For example:

ps c:\>  $command  =  "Get-service" ps c:\>  $commandGet-serviceps c:\>  &  $commandStatus    Name                displayname------   ----                -----------Stopped  adobeflashplaye ...  Adobe Flash Player Update ServiceStopped  Alerter             AlerterStopped  ALG                 Application Layer Gateway  servicestopped  appmgmt             Application managementstopped  aspnet_state       asp.net   Status Service RUNNING  ATI&NBSp hotkey poller  ati hotkey pollerrunning  audiosrv            windows audio ...

As can be seen from the above example, the Get-service command is assigned to the variable $command, so when the input $command output is the string value "Get-service", if you want to execute the command, you need to add the call operator before the variable.

This command is useful in practical applications, such as the ability to assign a cmd command to a variable and then execute the CMD command using the call operator .

2. . (attribute reference operator, or point operator)

You can use the attribute operator to access the properties and methods of an object, like a high-level language, by using the dot operator. For example:

PS c:\> $myStr = "This is my string" PS c:\> $myStr. Length17ps c:\> $myStr. Substring (1,4)

The dot operator, plus the auto-completion feature of Powershell, can greatly improve the accuracy of the input commands, such as the ability to output $myStr. len<tab key >, the command will be automatically complete. Before we introduce the split and merge operators of strings, there are a large portion of the operations that can be implemented by means of strings, such as the substring () of a string that intercepts a specified substring.


In addition to the reference attribute, the point operator has a more important application.

Use point "." To get the source operator

This means that by running a script that makes the items in the script part of the calling scope, the popular point is that other scripts can be called in the current script, and the methods and variables in the other scripts are valid at the current scope . This is useful in the modular use of scripting, where you can put frequently used methods in a script, and load the script each time you use it to use the methods in that script. For example:

. C:\.sample.ps1

If you include the statement in your script, you can use all the methods and variables in SAMPLE.PS1 at the current scope.


In addition, the point operator has the most common use.

The dot (.) is also used as the parent directory symbol

This should be the property of everyone. In Powershell, double-clicking the script will not be performed by default (unlike a script like bat, double-click to run directly), mainly for security reasons. The format for executing scripts in Powershell is as follows:

PS c:\>. \sample.ps1

3.:: (static member operator)

    . To find the static properties and methods of an object, you can pass the output of the command through the pipe (|) Enter the command to the Get-member cmdlet. For example:

ps c:\> [datetime]::now2017 January 15 Sunday  19:11:40ps c:\> [datetime]::now |  Get-Member   TypeName: System.DateTimeName                  MemberType      Definition----                  ----------     ----------add                   Method          system.datetime add (System.timespan value) adddays               Method          System.datetime adddays (Double value) addhours              method          system.datetime addhours (Double value) addmilliseconds      method          system.datetime addmilliseconds (Double value) addminutes            method         system.datetime  addminutes (Double value)

4 ... (range operator)

The range operator represents a sequence integer in an integer array given the upper and lower bounds, noting that the operator is valid only for integers. This operation allows you to quickly create an array of integers of the specified range. For example:

PS c:\> 1..41234PS c:\> 4..14321PS c:\> $max = 5PS c:\> foreach ($a in 1: $max) ' >> {>> Write -host $a >>}>>12345

As you can see from the example above, using the range operator makes the syntax more concise and intuitive.

5.-F (Format operator)

Formats a string using the Format method of a String object. Enter the format string to the left of the operator and enter the object to be formatted on the right side of the operator. For example:

PS d:\> "{0} {1} {2:n}"-F 1, "Hello", [math]::p i1 Hello 3.14

{0} {1} {2} before-F in the above statement is a placeholder, after-F is the value to replace the placeholder, and for the third value, format it to output only two decimal places.

Format operators are commonly used to format time, date, and output results (preserving several decimals, and so on).

6. $ () sub-expression operator

Returns the result of one or more statements. A scalar is returned for a single result. For multiple results, an array is returned. For example:

PS c:\> $x = 2PS c:\> $ ($x * 5) 10PS c:\> $ (get-process PowerShell) Handles NPM (k) PM (k) WS (k) VM (M) C      PU (s) Id ProcessName-----------------------------------------------432 6 29248 20352 139 3.27 3320 PowerShell

7. @ () array sub-expression operator

Returns the result of one or more statements through an array. If there is only one item, the array has only one member. For example:

PS c:\> @ (get-wmiobject Win32_LogicalDisk) deviceid:c:drivetype:3providername:freespace:27906625536siz         E:44811317248volumename:D Eviceid:d:drivetype:3providername:freespace:7755649024size : 42950717440VolumeName: Software

8., (comma operator)

When used as a two-tuple operator, commas are used to create arrays. When used as a unary operator, commas are used to create an array that contains only one member. The comma is placed before the member. For example, compare the execution results of the command:

PS c:\> $myArray = 1,2,3ps c:\> $singleArray =, 1PS c:\> $singleInt = 1

The first command and the second command are created as an array of integers, and the second command creates an array with only one element. The third command creates a variable of type number.

Summarize

Special operators in Powershell can implement some of the features that other operations cannot implement. In particular, call operators and point operations, as well as static member operators, can implement other functions that are not in the reach of other operations, mastering these special operators, you can implement many artifice in Powershell.

This article from "Flower Blossom Fall" blog, declined reprint!

(20) Special operators in PowerShell

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.