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


i've came across powershell 1 liner script first character + (plus) sign , wondering meaning of doing this.

example give unicode code point character 'a' :

+'a'[''] 

a unary + works implicit cast type int32.

the parser try convert value on right-hand side integer.

let's @ (and step through) statement, parser would:

+'a'[''] 

let's try "tokenize" statement:

+ 'a' [ ''  ] ^  ^  ^  ^  ^ |  |  |  |  | |  |  |  |  array index close operator |  |  |  empty string |  |  array index open operator |  literal string of length 1 value unary + operator 

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

'a'['']  

the way can index string (such 'a'), treating char[], , providing integer value between [ , ] operator. empty string not in integer, when implicitly converted one, becomes 0 (try [int]"" or '' -as [int] in powershell see in action). statement looks more this:

'a'[0] 

this char @ index 0 a, , our right-hand argument, character uppercase a.

we apply unary + , voila, corresponding ascii value char a, happens 65.

we have done:

+("a" -as [char]) 

or, using briantist's example:

"a" -as [char] -as [int] 

if ever wonder how parser splits statement individual tokens, use [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         string [       operator           string ]       operator 

Comments

Popular posts from this blog

How to provide Authorization & Authentication using Asp.net, C#? -

toolbar - How to add link to user registration inside toobar in admin joomla 3 custom component -

How to use Authorization & Authentication in Asp.net, C#? -