Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the meaning of starting a PowerShell one liner with a + (plus) sign

Tags:

powershell

I've came across a PowerShell one liner script for which the very first character is a + (plus) sign and I was wondering what is the meaning of doing this.

Example that will give the Unicode code point for character 'A' :

+'A'['']
like image 301
Martin Lebel Avatar asked Jul 07 '15 14:07

Martin Lebel


2 Answers

A unary + works as an implicit cast to the type int32.

The parser will simply try to convert the value on the right-hand side to an integer.

Let's look at (and step through) your statement, much like the parser would:

+'A'['']

Let's try to "tokenize" that statement:

+ 'A' [ ''  ]
^  ^  ^  ^  ^
|  |  |  |  |
|  |  |  |  Array index close operator
|  |  |  Empty string
|  |  Array index open operator
|  Literal string of length 1 with value A
Unary + operator

In order to know whether we can apply the + operater, we'll need to evaluate the right-hand argument:

'A'[''] 

The only way we can index into a string (such as 'A'), is by treating it as a char[], and providing an integer value between the [ and ] operator. An empty string is not in itself an integer, but when implicitly converted to one, it becomes 0 (try [int]"" or '' -as [int] in powershell to see this in action). Now the statement looks more like this:

'A'[0]

This char at index 0 is obviously A, and so that is now our right-hand argument, the character uppercase A.

We now apply the unary + and voila, we get the corresponding ASCII value for the char A, which happens to be 65.

We could similarly have done:

+("A" -as [char])

Or, using Briantist's example:

"A" -as [char] -as [int]

If you ever wonder how the parser splits a certain statement into individual tokens, use the [PSParser]::Tokenize() method:

PS C:\> $errors = @()
PS C:\> $script = "+'A'['']"
PS C:\> $tokens = [System.Management.Automation.PSParser]::Tokenize($script,[ref]$errors)
PS C:\> $tokens | select Content, Type
Content     Type
-------     ----
+       Operator
A         String
[       Operator
          String
]       Operator
like image 97
Mathias R. Jessen Avatar answered Nov 14 '22 02:11

Mathias R. Jessen


It's used in code golfing to convert to a number. It's shorter than [int].

The significance of [''] is that the square brackets are being used to get a [char] from a string. The '' is an empty string being coerced into a 0.

The asker is referring to a solution to a specific problem, where one of the restrictions was that the digits 0 through 9 could not be used in the answer at all.

See the PowerShell One-Liner Contest 2015 and the explanation of this (rather brilliant) solution from the winner.

like image 43
briantist Avatar answered Nov 14 '22 00:11

briantist