Last active
May 26, 2022 18:51
-
-
Save JohnL4/ca04279dbc58b71e21f78e85e612f3e4 to your computer and use it in GitHub Desktop.
PowerShell syntax for complex literals (array, hash), custom objects and calculated properties
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Hash table syntax is @{ name = value; name = value; ... } -- Curly braces and semicolons | |
$map = @{ key1 = "value1"; key2 = 3.14 } | |
echo $map.key1 # "value1" | |
echo $map["key2"] # 3.14 | |
# Coerce it to a new object | |
[PSCustomObject] $map | |
# Btw, you can SELECT a "calculated property" (or synthetic property, if that's how your brain works): | |
ls | sel -fir 3 | sel Name,LastWriteTime,@{Name="NooProperty";Expr={ $_.LastWriteTime.AddDays(-90) }} | |
# Array (list) syntax is @( value, value, ...) -- Parens, commas. | |
# Type declaration is "[type[]]", where "type" is the type of your array elements. | |
$list = @( 3.14, "value2" ) | |
echo $list[0] # 3.14 | |
echo $list[1] # "value2" | |
# If you want to BUILD a list: | |
# (From https://stackoverflow.com/a/33156229/370611) | |
$outItems = New-Object Collections.Generic.List[Object] # Or, say, Int64 or Int32 or String or whatever | |
$outItems.Add(1) | |
$outItems.Add("hi") | |
$outItems.ToArray() | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment