views:

2057

answers:

6

I've seen the @ symbol used in PowerShell to initialise arrays. What exactly does the @ symbol denote and where can I read more about it?

+2  A: 

The Splatting Operator

To create an array, we create a variable and assign the array. Arrays are noted by the "@" symbol. Let's take the discussion above and use an array to connect to multiple remote computers:

$strComputers = @("Server1", "Server2", "Server3")

They are used for arrays and hashes.

PowerShell Tutorial 7: Accumulate, Recall, and Modify Data

Array Literals In PowerShell

Cadoo
+11  A: 

PowerShell will actually treat any comma-separated list as an array:

"server1","server2"

So the @ is optional in those cases. However, for associative arrays, the @ is required:

@{"Key"="Value";"Key2"="Value2"}

Officially, @ is the "array operator." You can read more about it in the documentation that installed along with PowerShell, or in a book like "Windows PowerShell: TFM," which I co-authored :).

Don Jones
Make sure to check out Jeffrey Snover's answer below... @ is more than just an array identifier.
spoon16
+6  A: 

You can also wrap the output of a cmdlet (or pipeline) in @() to ensure that what you get back is an array rather than a single item.

For instance, dir usually returns a list, but depending on the options, it might return a single object. If you are planning on iterating through the results with a foreach-object, you need to make sure you get a list back. Here's a contrived example:

$results = @( dir c:\autoexec.bat)

One more thing... an empty array (like to initialize a variable) is deonted @().

Mike Shepard
[array]$a syntax is somewhat clearer, visually, but good tip.
Don Jones
A: 

What about this usage of the @ symbol:

Import-Csv $file.Name | Select-Object -Property Col1, Col2, @{Name="NewCol";Expression={$newColVal}}, Column3

In this instance it's used to add a column to the imported CSV, but can someone explain why/how?

@{} is the syntax for creating a Hashtable. In this case, Select-Object can accept a string representing the name of the property, or a Hashtable that also specifies some other options (such as code to run to define the value of the property).
JasonMArcher
+12  A: 

In PowerShell V2, @ is also the SPLAT operator.

PS> # First use it to create a hashtable of parameters:
PS> $params = @{path = "c:\temp"; Recurse= $true}
PS> # Then use it to SPLAT the parameters - which is to say to expand a hash table 
PS> # into a set of command line parameters.
PS> dir @params
PS> # That was the equivalent of:
PS> dir -Path c:\temp -Recurse:$true

Experiment! Enjoy! Engage!

Jeffrey Snover [MSFT] Windows Management Partner Architect

Jeffrey Snover - MSFT
Ok. I might forgive the noncompliance with ECMA-48 colors for this, because wow that's pretty cool.
Mark Tomlin