This question already has answers here:
PowerShell outputting array items when interpolating within double quotes
(3 answers)
Closed 8 months ago.
$nameonly = #("") * 20
$i=1
do
{
$nameonly[$i] = "A$i"
$i++
}
until ($i -eq 10)
write-host "$nameonly[4]"
When i run the code i expect the output to be: A4 but instead i get:
A1 A2 A3 A4 A5 A6 A7 A8 A9 [4]
`
Try removing the quotation marks in your final command.
So it should be write-host $nameonly[4]
This will get you the indexed value in position 4 of the array.
You can also skip the write-host command.
Invoking the variable $nameonly[4] will output to the console.
If you use quotation marks then it will convert the whole array into a string and output the entire array content as a string object.
Related
I'm receiving an input as an array of strings
Input[0]:1
2
3
Input[1]:a
b
c
Input[2]:x
y
z
...
I am looking to use the split function on each of those elements through a loop so I can isolate them. I don't mind if it's done by creating a group of arrays (Array0[1,2,3]; Array1[a,b,c];...) or by creating a multidimensional array, whichever is best, but I'm struggling with how to create those in a loop.
EDIT: I can get it working as expected with this same setup with a single input that splits into an array (e.g. $InputArr = $InputArr.Split("`n")), but as soon as I try it with a 2D array, it doesn't split properly
Current Code:
Function Read-example {
[CmdletBinding()]
param (
[Parameter(Mandatory = $true)]
[string[]]
$InputArr
)
begin{
}
process {
$InputArr[0] = $InputArr[0].Split("`n")
Write-Host "Input 0 0: " $InputArr[0][0]
Write-Host `n "Input 0 1: " $InputArr[0][1]
Write-Host `n "Input 0 2: " $InputArr[0][2]
}
My Input is:
InputArr[0]: 1a
1b
1c
And the output is:
Input 0 0: 1
Input 0 1: a
Input 0 2:
The way you have formatted in the question, it looks like the strings in the array elements are separated by newline characters.
$arr = "1`r`n2`r`n3", "a`r`nb`r`nc", "x`r`ny`r`nz"
If that is the case, simply loop over the array $arr and split each element on that newline:
for ($i = 0; $i -lt $arr.count; $i++) {
$arr[$i] = $arr[$i] -split '\r?\n'
}
After this, the original array stores sub arrays:
$arr[0].GetType() --> String[]
$arr[0][0] --> 1
$arr[0][1] --> 2
$arr[0][2] --> 3
etc.
Is this what you mean?
This question already has answers here:
Creating a Jagged\Multidimensional array with a single array inside of it
(1 answer)
Return Multidimensional Array From Function
(3 answers)
Append an Array to an Array of Arrays in PowerShell
(2 answers)
Closed 4 years ago.
Issue
I am trying to reconstruct an array from the parts that constitute it but I am failing to obtain the same result. I instead end up with a single-dimension array with all the values from the respective arrays.
Question
How can I make sure that $brray is populated with the individual arrays and not only the values that they contain?
MWE
$array = #(("a1","a2"),("b1","b2"))
$a = #("a1","a2")
$b = #("b1","b2")
$brray = #()
$brray += $a
$brray += $b
function test(){
Param(
[string[]]
$array
)
return $array
}
test($array)
test($brray)
Output
$array
a1 a2
b1 b2
$brray
a1
a2
b1
b2
Want to fill two column array, and sort it on second column to display.
Can someone assist me ?
$scopelist = Get-DhcpServerv4Scope | sort name
write-host -foregroundcolor green "Aantal scopes : " $scopelist.count
$allscopes=#(85),#(2)
$teller=0
foreach ($scope in $scopelist)
{
#write-host $scope.name " : " (Get-DhcpServerv4Lease $scope.scopeid).count
$all += (Get-DhcpServerv4Lease $scope.scopeid).count
$allscopes += $scope.name,(Get-DhcpServerv4Lease $scope.scopeid).count
#$allscopes[$teller][0]=$scope.name
#$allscopes[$teller][1]=(Get-DhcpServerv4Lease $scope.scopeid).count
$teller++
}
write-host "Alle toestellen via dhcp : " $all
$allscopes
#$gesorteerd = $allscopes | sort-object #{Expression={$_[1]}; Ascending=$false}
#$gesorteerd
now is output something like this :
Tournai
19
Turnhout
40
Users Wired
149
Users Wireless
46
Verviers
41
Veurne
18
WAP
10
Waregem
42
Wavre
25
Wetteren
33
Wevelgem
46
Zaventem
23
Zelzate
69
Zottegem
18
Zwevegem
42
Your array sorting is fine. The problem is with array initialization and the line where you're adding members to the array. This:
$allscopes=#(85),#(2)
creates one-dimensional array with 2 array members, {85} and {2}. Then this line:
$allscopes += $scope.name,(Get-DhcpServerv4Lease $scope.scopeid).count
uses += operator, which subsequently adds $scope.name and count to the one-dimensional array (it's the default behaviour for this operator).
To fix your code try this:
# Empty array initialization
$allscopes = #()
...
# Notice the comma - means you're adding array as a member, not two members
$allscopes += ,($scope.name,(Get-DhcpServerv4Lease $scope.scopeid).count)
...
# Output every (x,y) member, joined with tab char
$allscopes | foreach {$_ -join "`t"}
This question already has answers here:
How to concatenate array of integers into comma separated string
(4 answers)
Closed 5 years ago.
I found this snippet for doing a string to array:
$c = "2,3,4,5,6,7,10..12".split(',') | % {iex $_}
How would I do the reverse to convert $c back to a string like "2,3,4,5,6,7,10,11,12"? I of course don't require to abbreviate it back to "2..7,10..12".
You are looking for -join:
$c -join ','
Looking to be able to parse an array based on a variable and take the next 2 characters
array=( 7501 7302 8403 9904 )
if var = 73, result desired is 02
if var = 75, result desired is 01
if var = 84, result desired is 03
if var = 99, result desired is 04
Sorry if this is an elementary question, but I've tried variations of cut and grep and cannot find the solution.
Any help is greatly appreciated.
You can use this search function using printf and awk:
srch() {
printf "%s\n" "${array[#]}" | awk -v s="$1" 'substr($1, 1, 2) == s{
print substr($1, 3)}' ;
}
Then use it as:
srch 75
01
srch 73
02
srch 84
03
srch 99
04
Since bash arrays are sparse, even in older versions of bash that don't have associative arrays (mapping arbitrary strings as keys), you could have a regular array that has keys only for numeric indexes that you wish to map. Consider the following code, which takes your input array and generates an output array of that form:
array=( 7501 7302 8403 9904 )
replacements=( ) # create an empty array to map source to dest
for arg in "${array[#]}"; do # for each entry in our array...
replacements[${arg:0:2}]=${arg:2} # map the first two characters to the remainder.
done
This will create an array that looks like (if you ran declare -p replacements after the above code to dump a description of the replacements variable):
# "declare -p replacements" will then print this description of the new array generated...
# ...by the code given above:
declare -a replacements='([73]="02" [75]="01" [84]="03" [99]="04")'
You can then trivially look up any entry in it as a constant-time operation that requires no external commands:
$ echo "${replacements[73]}"
02
...or iterate through the keys and associated values independently:
for key in "${!replacements[#]}"; do
value=${replacements[$key]}
echo "Key $key has value $value"
done
...which will emit:
Key 73 has value 02
Key 75 has value 01
Key 84 has value 03
Key 99 has value 04
Notes/References:
See the bash-hackers wiki on parameter expansion for understanding of the syntax used to slice the elements (${arg:0:2} and ${arg:2}).
See BashFAQ #5 or the BashGuide on arrays for more details on the syntax used above.