1

I tried to pass the variables to understand the real meaning of the @ and $ in the powershell as :

PS C:\Windows\system32> Write-Host $str
string
PS C:\Windows\system32> Write-Host @str
s t r i n g

and when we create an hash table like

PS C:\Windows\system32> $hash = @{key1 = 'value1'; key2 = 'value2'}
PS C:\Windows\system32> $hash

Name                           Value
----                           -----
key1                           value1
key2                           value2


PS C:\Windows\system32> @hash
At line:1 char:1
+ @hash
+ ~~~~~
The splatting operator '@' cannot be used to reference variables in an expression. '@hash' can be used only as an argument to a command. To reference variables in an expression use '$hash'.
    + CategoryInfo          : ParserError: (:) [], ParentContainsErrorRecordException
    + FullyQualifiedErrorId : SplattingNotPermitted

PS C:\Windows\system32> Write-Host $host
System.Management.Automation.Internal.Host.InternalHost
PS C:\Windows\system32> Write-Host $hash
System.Collections.DictionaryEntry System.Collections.DictionaryEntry
PS C:\Windows\system32> Write-Host @hash
-key1: value1 -key2: value2

Finally, I'm here to know about the difference between the use of @ and $ sign in front of the variables

Sanjay V
  • 11
  • 1
  • Fun . This has to do with [splatting](https://learn.microsoft.com/powershell/module/microsoft.powershell.core/about/about_splatting) where the variable should contain an array (e.g. `$Str = ,'String'`) or an hashtable but as in your case concerns a single string it unrolled in a character array: `Function Test { $Args.Count }; Test @Str`. I am not sure whether this qualifies as a bug... – iRon Jan 25 '22 at 09:17
  • 1
    See: [`#8042` Splatting is messed up by Powershell's implicit coercion of arrays to non-arraysAnyway](https://github.com/PowerShell/PowerShell/issues/8042). Anyways, to workaround this use the [Array subexpression operator `@( )`](https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_operators?view=powershell-7.2#array-subexpression-operator--) to force an array for splatting: `$Str = @('String'); Write-Host @Str` – iRon Jan 25 '22 at 09:41

0 Answers0