Are there any other uses for parentheses in powershell?

As new to the Powershell world, I once got stuck in complex syntax. This is why I am trying to figure out all the possible uses of parentheses inside a language.

Do you know something else? Can you add here?

Here's mine (left the main use of kinky ones in the pipeline and round in method calls):

# empty array $myarray = @() # empty hash $myhash = @{} # empty script block $myscript = {} # variables with special characters ${very strange variable @ stack !! overflow ??}="just an example" # Single statement expressions (ls -filter $home\bin\*.ps1).length # Multi-statement expressions inside strings "Processes: $($p = "a*"; get-process $p )" # Multi statement array expression @( ls c:\; ls d:\) 
+7
source share
6 answers

Call expression for expression in expression:

 ($x=3) + 5 # yields 8 
+5
source

When using generics, you need to wrap the type in [..] :

 New-Object Collections.Generic.LinkedList[string] 

For some people this may seem confusing because it is like indexing in arrays.

+4
source

Param () operator (in function, script or scriptblock)

Around the condition in the expression If (or Elseif)

Around the expression in the switch statement.

Edit: Forgot the condition in the while statement.

Edit2: Also, $ () for subexpressions (e.g. in strings).

+2
source

Regular expressions are perhaps Powershell's first-class construct.

If we put together a complete list, we can include the role that square brackets and parentheses play in regular expressions.

Example:

 $obj.connectionString = $obj.connectionString -replace '(Data Source)=[^;]+', '$1=serverB\SQL2008_R2' 

Because of XML support, you can go so far as to include the square brackets used in XPath. (This is a really long bow, though :-)

 select-xml $config -xpath "./configuration/connectionStrings/add[@name='LocalSqlServer']" 
+1
source

Itโ€™s even written, but not clearly enough in the first short list after โ€œExpressions with multiple statements inside the lines that I will add

 # Var property inside a string $a = get-process a* write-host "Number of process : $a.length" # Get a list of process and then ".length Number of process : System.Diagnostics.Process (accelerometerST) System.Diagnostics.Process (AEADISRV) System.Diagnostics.Process (agr64svc).length write-host "Number of process : $($a.length)" # To get correct number of process Number of process : 3 
0
source

Brackets are the most powerful.

Suppose you want to collect all the output, including errors, of a script block and redirect it to a variable or other functions to handle this ... With a parenthesis, this is a simple task:

 $customScript = { "This i as test"; This will be procedure error! } (. $customScript 2>&1 ) | %{"CAPTURING SCRIPT OUTPUT: "+$_} 
0
source

All Articles