Let's say I have hash like this:
$NATO = #{
"A" = "Alpha";
"B" = "Bravo";
"C" = "Charlie";
# ...
"Y" = "Yankee";
"Z" = "Zulu";
}
I could get all values of hash using $NATO.keys key collection:
$NATO[$NATO.keys] # gives me all values
But if I want to pass subset of keys, to get subset of values, I can't do that:
$NATO["BUNYK".ToCharArray()] # gives me nothing, but I want
# Bravo, Uniform, November, Yankee, Kilo
Do you know how this could be done?
You could also pipe the string array into a ForEach-Object loop:
[string[]]'BUNYK'.ToCharArray() | % { $NATO[$_] }
The hash table stores the keys as objects, not necessarily simple strings. The keys in your example are strings, but you're trying to access them as [char] objects. The easiest way to handle your example is to cast the [char[]] array to a [string[]] array:
$NATO[([string[]] "BUNYK".ToCharArray())]
Related
I am trying to sort an hashtable in Powershell with the following structure :
https://i.stack.imgur.com/bjSX6.png
Each value of the hashtable is an array containing multiple elements.
I would like to sort the hashtable based on the value of second element of each array, is it possible ?
Create an ordered dictionary, then enumerate all the key-value pairs in the existing hashtable, sort them by the desired value and then add them to your new ordered dictionary:
# Create ordered dictionary
$ordered = [ordered]#{}
# Sort KVPs by value at index 1 (that's the second element) of the array
$hashtable.GetEnumerator() |Sort-Object { $_.Value[1] } |ForEach-Object {
# Copy the KVP to the ordered dictionary in... order
$ordered[$_.Key] = $_.Value
}
$ordered now contains the same entries as $hashtable, but sorted according to your criteria
Thought I have read enough examples here and elsewhere. Still I fail creating arrays in Power Shell.
With that code I hoped to create slices of pair values from an array.
$values = #('hello','world','bonjour','moon','ola','mars')
function slice_array {
param (
[String[]]$Items
)
[int16] $size = 2
$pair = [string[]]::new($size) # size is 2
$returns = [System.Collections.ArrayList]#()
[int16] $_i = 0
foreach($item in $Items){
$pair[$_i] = $Item
$_i++;
if($_i -gt $size - 1){
$_i = 0
[void]$returns.Add($pair)
}
}
return $returns
}
slice_array($values)
the output is
ola
mars
ola
mars
ola
mars
I would hope for
'hello','world'
'bonjour','moon'
'ola','mars'
Is possible to slice that array to an array of arrays with length 2 ?
Any explenation why it doesn't work as expected ?
How should the code be changed ?
Thanks for any hint to properly understand Arrays in PowerShell !
Here's a PowerShell-idiomatic solution (the fix required for your code is in the bottom section):
The function is named Get-Slices to adhere to PowerShell's verb-noun naming convention (see the docs for more information).
Note: Often, the singular form of the noun is used, e.g. Get-Item rather than Get-Items, given that you situationally may get one or multiple output values; however, since the express purpose here is to slice a single object into multiple parts, I've chosen the plural.
The slice size (count of elements per slice) is passed as a parameter.
The function uses .., the range operator, to extract a single slice from an array.
It uses PowerShell's implicit output behavior (no need for return, no need to build up a list of return values explicitly; see this answer for more information).
It shows how to output an array as a whole from a function, which requires wrapping it in an auxiliary single-element array using the unary form of ,, the array constructor operator. Without this auxiliary array, the array's elements would be output individually to the pipeline (which is also used for function / script output; see this answer for more information.
# Note: For brevity, argument validation, pipeline support, error handling, ...
# have been omitted.
function Get-Slices {
param (
[String[]] $Items
,
[int] $Size # The slice size (element count)
)
$sliceCount = [Math]::Ceiling($Items.Count / $Size)
if ($sliceCount -le 1) {
# array is empty or as large as or smaller than a slice? ->
# wrap it *twice* to ensure that the output is *always* an
# *array of arrays*, in this case containing just *one* element
# containing the original array.
,, $Items
}
else {
foreach ($offset in 0..($sliceCount-1)) {
, $Items[($offset * $Size)..(($offset+1) * $Size - 1)] # output this slice
}
}
}
To slice an array into pairs and collect the output in an array of arrays (jagged array):
$arrayOfPairs =
Get-Slices -Items 'hello','world','bonjour','moon','ola','mars' -Size 2
Note:
Shell-like syntax is required when you call functions (commands in general) in PowerShell: arguments are whitespace-separated and not enclosed in (...) (see this answer for more information)
Since a function's declared parameters are positional by default, naming the arguments as I've done above (-Item ..., -Size ...) isn't strictly necessary, but helps readability.
Two sample calls:
"`n-- Get pairs (slice count 2):"
Get-Slices -Items 'hello','world','bonjour','moon','ola','mars' -Size 2 |
ForEach-Object { $_ -join ', ' }
"`n-- Get slices of 3:"
Get-Slices -Items 'hello','world','bonjour','moon','ola','mars' -Size 3 |
ForEach-Object { $_ -join ', ' }
The above yields:
-- Get pairs (slice count 2):
hello, world
bonjour, moon
ola, mars
-- Get slices of 3:
hello, world, bonjour
moon, ola, mars
As for what you tried:
The only problem with your code was that you kept reusing the very same auxiliary array for collecting a pair of elements, so that subsequent iterations replaced the elements of the previous ones, so that, in the end, your array list contained multiple references to the same pair array, reflecting the last pair only.
This behavior occurs, because arrays are instance of reference types rather than value types - see this answer for background information.
The simplest solution is to add a (shallow) clone of your $pair array to your list, which ensures that each list entry is a distinct array:
[void]$returns.Add($pair.Clone())
Why you got 3 equal pairs instead of different pairs:
.Net (powershell based on it) is object-oriented language and it has consept of reference types and value types. Almost all types are reference types.
What happens in your code:
You create $pair = [string[]] object. $pair variable actually stores memory address of (reference to) [string[]] object, because arrays are reference types
You fill $pair array with values
You add (!) $pair to $returns. Remember that $pair is reference to memory block. And when you add it to $returns, it adds memory address of [string[]] you wrote values to.
You repeat step2: You fill $pair array with different values, but address of this array in memory keeps the same. Doing this you actually replace values from step2 with new values in the same $pair object.
= // = step3
= // = step4
= // = step3
As a result: in $returns there are three same memory addresses: [[reference to $pair], [reference to $pair], [reference to $pair]]. And $pair values were overwritten by code with last pair values.
On output it works like this:
Powershell looks at $results which is array.
Powershell looks to $results[0] which reference to $pair
Powershell outputs reference to $pair[0]
Powershell outputs reference to $pair[1]
Powershell looks to $results[1] which reference to $pair
Powershell outputs reference to $pair[0]
Powershell outputs reference to $pair[1]
Powershell looks to $results[1] which reference to $pair
Powershell outputs reference to $pair[0]
Powershell outputs reference to $pair[1]
So you see, you triple output the object from the same memory address. You overwritten it 3 times in slice_array and now it stores only last pair values.
To fix it in your code, you should create a new $pair in memory: add $pair = [string[]]::new($size) just after $returns.Add($pair)
I am trying to create a function to loop through json file and based upon specific condition met want to add the value of the json keys to array but not able to accomplish the same.
Following is the json:
$a1 = [ {
"name": "sachin",
"surname": "",
},
{
"name": "Rajesh",
"surname": "Mehta"
}
]
and the function that i have created is below:
function addingkeyval
{
param ($key,
[Array]$tobeaddedarr)
$a1 | Select-Object -Property name,surname | ForEach-Object {
if($_.$key-eq "")
{
}
else
{
$tobeaddedarr +=$_.$key+","
}
}
}
when i cal this function with the statement:
$surnamearr = #()
addingkeyval -key surname -tobeaddedarr $surnamearr
i want the output in the array $surnamearr as below
("Mehta")
somehow i am not able to add the value in the array can anyone help me in achieving the same
$surnamearr = ([string[]] (ConvertFrom-Json $a1).surname) -ne ''
ConvertFrom-Json $a1 converts the JSON array to an array of PowerShell custom objects (type [pscustomobject]).
(...).surname extracts the values of all .surname properties of the objects in the resulting array, using member-access enumeration.
Cast [string[]] ensures that the result is treated as an array (it wouldn't be, if the array in $a1 happened to contain just one element) and explicitly casts to strings, so that filtering nonempty values via -ne '' also works for input objects that happen to have no .surname property.
-ne '' filters out all empty-string elements from the resulting array (with an array as the LHS, comparison operators such as -ne act as array filters rather than returning a Boolean value).
The result is that $surnamearr is an array containing all non-empty .surname property values.
As for what you tried:
$tobeaddedarr +=$_.$key+","
This statement implicitly creates a new array, distinct from the array reference the caller passed via the $tobeaddedarr parameter variable - therefore, the caller never sees the change.
You generally cannot pass an array to be appended to in-place, because arrays are immutable with respect to their number of elements.
While you could pass an mutable array-like structure (such as [System.Collections.Generic.List[object]] instance, which you can append to with its .Add() method), it is much simpler to build a new array inside the function and output it.
Therefore, you could write your function as:
function get-keyval
{
param ($key)
# Implicitly output the elements of the array output by using this command.
([string[]] (ConvertFrom-Json $key).surname) -ne ''
}
$surnamearr = get-keyval surname
Note:
Outputting an array or a collection in PowerShell by default enumerates it: it sends its elements one by one to the output stream (pipeline).
While it is possible to output an array as a whole, via the unary form of ,, the array-construction operator (
, (([string[]] (ConvertFrom-Json $a1).surname) -ne '')), which improves performance, the problem is that the caller may not expect this behavior, especially not in a pipeline.
If you capture the output in a variable, such as $surnamearr here, PowerShell automatically collects the individual output objects in an [object[]] array for you; note, however, that a single output object is returned as-is, i.e. not wrapped in an array.
You can wrap #(...) around the function call to ensure that you always get an array
Alternatively, type-constrain the receiving variable: [array] $surnamearr = ..., which also creates an [object[]] array, or something like [string[]] $surnamearr = ..., which creates a strongly typed string array.
$hash = #{}
$hash.x1 = 1
$hash.x2 = 2
Can I display the hash table's values like this?
$hash.[x1,x2]
$hash.[x1,x2] (with dot and bare words) will not work, but you can use the index operator directly on a hashtable with an array of the key names (as strings). Like this:
$hash['x1','x2']
or like this:
$keys = 'x1', 'x2'
$hash[$keys]
I have an array where each element is a hashtable. Each hashtable has the same keys. Here it is:
#(
#{"MarketShortCode"="abc";"MarketName"="Market1" },
#{"MarketShortCode"="def";"MarketName"="Market2" },
#{"MarketShortCode"="ghi";"MarketName"="Market3" },
#{"MarketShortCode"="jkl";"MarketName"="Market4" }
)
I want a nice elegant way to extract an array containing just the value of the MarketShortCode key. So I want this:
#("abc","def","ghi","jkl")
This is the best I've come up with:
$arr = #()
$hash | %{$arr += $_.MarketShortCode}
$arr
But I don't like that cos its three lines of code. Feels like something I should be able to do in one line of code. Is there a way?
Just do this:
$hash | %{$_.MarketShortCode}
That is, return the value from the block instead of adding it to an array and then dereferencing the array.
If you're using PowerShell 3+, there's even shorter way:
$hash.MarketShortCode
PowerShell automatically applies dot . to each item in an array when it's used this way, but it wasn't supported until v3.