Updated: I am trying to take a user input values(string) into a 2d array. For testing purpose, I assigned a string to variable.
Goal: Later I want my program to look at each row for column 1 of my array and do something like install printer software if it says Printer and don't install software if noPrinter. I can do this for 1d array but I want anywhere from 1 to 10 rows. That is why 2d array thought would be complexity.
I want to learn to do this and not ask you to write all my code.
Thank you.
Here is my code.
#set user input to a string variable
$UserInputVar = "computer1,noPrinter,Computer2,Printer,Computer3,Printer"
#this is my 2d array; Declare. i want to be able to use anywhere from 1 to 10 rows and always 2 columns
$my2d=[object[]]::(,2)
$my2d.clear #for testing purpose
#assign values of sting to 2 dimensional array
#split the string at each comma(,)
$my2d = $UserInputVar.Split(",")
#show me the values in this array
"`n #my2d[0][0] "
$my2d[0][0] #expect value 'computer1'
$my2d[0][1] #expect value 'noPrinter'
$my2d[0][2]
$my2d[0][3]
"`n #my2d[1][0] "
$my2d[1][0] #expect value 'computer2'
$my2d[1][1] #expect value 'Printer'
$my2d[1][2]
$my2d[1][3]
"`n #my2d[2][0] "
$my2d[2][0] #expect value 'computer3'
$my2d[2][1] #expect value 'Printer'
$my2d[2][2]
$my2d[2][3]
"`n #array with no 2nd index"
$my2d[0]
$my2d[1]
$my2d[2]
I'm not sure if you want an object as output, but if so, this is a simple way to do it:
$z = 0
$UserInputVar = "This,is,my,strg,to,test".Split(',')
for($z=0; $z -lt $UserInputVar.Count; $z=$z+2)
{
[pscustomobject]#{
1 = $UserInputVar[$z]
2 = $UserInputVar[$z+1]
}
}
Output
1 2
- -
This is
my strg
to test
Edit
Looking again at the question, this may be what you're looking for:
$z = 0
$UserInputVar = "This,is,my,strg,to,test".Split(',')
$result = [System.Collections.Generic.List[object]]::new()
for($z=0; $z -lt $UserInputVar.Count; $z=$z+2)
{
$result.Add(#($UserInputVar[$z],$UserInputVar[$z+1]))
}
Some Testing
PS /> $result[0]
This
is
PS /> $result[0][0]
This
PS /> $result[0][1]
is
PS /> $result[0][2]
PS /> $result[1][0]
my
You may also use regex matching to return your groups of 2 elements. Then you can split each of those returned pairs into a single array (because of the unary operator ,). All the returned single arrays are then wrapped automatically into Object[] array.
$UserInputVar = "computer1,noPrinter,Computer2,Printer,Computer3,Printer"
$my2d = [regex]::Matches($UserInputVar,'[^,]+(,[^,]+|$)') |
Foreach-Object {,($_.Value -split ',')}
Related
I want to write two things in Powershell.
For example;
We have a one list:
$a=#('ab','bc','cd','dc')
I want to write:
1 >> ab
2 >> bc
3 >> cd
4 >> dc
I want this to be dynamic based on the length of the list.
Thanks for helping.
Use a for loop so you can keep track of the index:
for( $i = 0; $i -lt $a.Count; $i++ ){
"$($i + 1) >> $($a[$i])"
}
To explain how this works:
The for loop is defined with three sections, separated by a semi-colon ;.
The first section declares variables, in this case we define $i = 0. This will be our index reference.
The second section is the condition for the loop to continue. As long as $i is less than $a.Count, the loop will continue. We don't want to go past the length of the list or you will get undesired behavior.
The third section is what happens at the end of each iteration of the loop. In this case we want to increase our counter $i by 1 each time ($i++ is shorthand for "increment $i by 1")
There is more nuance to this notation than I've included but it has no bearing on how the loop works. You can read more here on Unary Operators.
For the loop body itself, I'll explain the string
Returning an object without assigning to a variable, such as this string, is effectively the same thing as using Write-Output.
In most cases, Write-Output is actually optional (and often is not what you want for displaying text on the screen). My answer here goes into more detail about the different Write- cmdlets, output streams, and redirection.
$() is the sub-expression operator, and is used to return expressions for use within a parent expression. In this case we return the result of $i + 1 which gets inserted into the final string.
It is unique in that it can be used directly within strings unlike the similar-but-distinct array sub-expression operator and grouping operator.
Without the subexpression operator, you would get something like 0 + 1 as it will insert the value of $i but will render the + 1 literally.
After the >> we use another sub-expression to insert the value of the $ith index of $a into the string.
While simple variable expansion would insert the .ToString() value of array $a into the final string, referencing the index of the array must be done within a sub-expression or the [] will get rendered literally.
Your solution using a foreach and doing $a.IndexOf($number) within the loop does work, but while $a.IndexOf($number) works to get the current index, .IndexOf(object) works by iterating over the array until it finds the matching object reference, then returns the index. For large arrays this will take longer and longer with each iteration. The for loop does not have this restriction.
Consider the following example with a much larger array:
# Array of numbers 1 through 65535
$a = 1..65535
# Use the for loop to output "Iteration INDEXVALUE"
# Runs in 106 ms on my system
Measure-Command { for( $i = 0; $i -lt $a.Count; $i++ ) { "Iteration $($a[$i])" } }
# Use a foreach loop to do the same but obtain the index with .IndexOf(object)
# Runs in 6720 ms on my system
Measure-Command { foreach( $i in $a ){ "Iteration $($a.IndexOf($i))" } }
Another thing to watch out for is that while you can change properties and execute methods on collection elements, you can't change the element values of a non-collection collection (any collection not in the System.Concurrent.Collections namespace) when its enumerator is in use. While invisible, foreach (and relatedly ForEach-Object) implicitly invoke the collection's .GetEnumerator() method for the loop. This won't throw an error like in other .NET languages, but IMO it should. It will appear to accept a new value for the collection but once you exit the loop the value remains unchanged.
This isn't to say the foreach loop should never be used or that you did anything "wrong", but I feel these nuances should be made known before you do find yourself in a situation where a better construct would be appropriate.
Okey,
I fixed that;
$a=#('ab','bc','cd','dc')
$a.Length
foreach ($number in $a) {
$numberofIIS = $a.IndexOf($number)
Write-Host ($numberofIIS,">>>",$number)
}
Bender's answer is great, but I personally avoid for loops if at all possible. They usually require some awkward indexing into arrays and that ugly setup... The whole thing just ends up looking like hieroglyphics.
With a foreach loop it's our job to keep track of the index (which is where this answer differs from yours) but I think in the end it is more readable then a for loop.
$a = #('ab', 'bc', 'cd', 'dc')
# Pipe the items of our array to ForEach-Object
# We use the -Begin block to initialize our index variable ($x)
$a | ForEach-Object -Begin { $x = 1 } -Process {
# Output the expression
"$x" + ' >> ' + $_
# Increment $x for next loop
$x++
}
# -----------------------------------------------------------
# You can also do this with a foreach statement
# We just have to intialize our index variable
# beforehand
$x = 1
foreach ($number in $a){
# Output the expression
"$x >> $number"
# Increment $x for next loop
$x++
}
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?
I have this variable
$sync_output = Join-Path $syncPATH $CUBE_input
I have this foreach loop:
$i=0
$Destination_Server = #()
foreach($row in $Table | where { $_.cube_name -match $CUBE })
{
$i++
$Destination_Server += $row.Item("query_server")
write-host " > Query Server $($i):" $Destination_Server[$Destination_Server.length -1]
$sync_output += "_$Destination_Server.txt"
Invoke-ASCmd –InputFile $XML_file -Server $Destination_Server[$Destination_Server.length -1] >$sync_output
}
it does what it needs to do, except for the sync_output, I am getting this created:
as you can see, the first file,
CUBE_Destination_Server1
is perfectly created.
however, the second file, should be named
CUBE_Destination_Server2
but instead its for some reason appending the Destination_Server2 after appending Destination_Server1 twice...
Why is that?
The += operator appends. So this line:
$sync_output += "_$Destination_Server.txt"
takes the existing value of $sync_output and then adds "_$Destination_Server.txt" onto the end.
One way to get your desired result is to assign (not append) $syncResult inside your loop, with a statement like this:
$sync_output = (Join-Path $syncPATH $CUBE_input) + "_$Destination_Server.txt"
Update: it looks like you have a similar problem with the $Destination_Server variable--you should use plain assignment (=) with it too, rather than appending (also called concatenation) (+=).
The string is appending, because that is what you told it to do.
Straight up, the += says to add the new content at the end, so in the case of
$sync_output = Join-Path $syncPATH $CUBE_input
...
$sync_output += "_$Destination_Server.txt"
It sets a string, and then appends things to the end of that string, and keeps appending to it each time that command is executed when the ForEach-Object loop cycles. This is compounded by your other use of +=, which is appending objects into an array, since you setup $Destination_Server = #() which sets that variable as an empty array. So when you append to your string you are appending an entire array to that string.
So to replicate your example:
$sync_output = 'CUBE'
$destination_server = #()
Then inside the loop on the first pass you add a string to the array:
$destination_server += 'Destination_Server1'
So that array has 1 item in it. You then add that array to $sync_output which expanding the variables basically reads like:
"CUBE" += "_Destination_Server1.txt"
So now $sync_output has a value of CUBE_Destination_Server1.txt. Next iteration of the loop! You add another string to the $Destination_Server array:
$destination_server += 'Destination_Server2'
Now that array has 2 strings in it, so when you append it to the $sync_output string variable you essentially are doing this:
"CUBE_Destination_Server1.txt" += "_Destination_Server1Destination_Server2.txt"
It does that because the array of strings simply concocts all of the strings in its array into one string. In order to really fix this you need to be consistent and reference the last string in the array. I recommend not re-using the same variable for this, and will use $sync_output_file.
$sync_output = Join-Path $syncPATH $CUBE_input
$i=0
$Destination_Server = #()
foreach($row in $Table | where { $_.cube_name -match $CUBE })
{
$i++
$Destination_Server += $row.Item("query_server")
write-host " > Query Server $($i):" $Destination_Server[$Destination_Server.length -1]
$sync_output_file = $sync_output + '_' + $Destination_Server[-1] + '.txt'
Invoke-ASCmd –InputFile $XML_file -Server $Destination_Server[$Destination_Server.length -1] >$sync_output_file
}
Edit: Here's why $Destination_Server[$Destination_Server.length - 1] works like $Destination_Server[-1]:
In PowerShell an each item in an array has an index. That index is zero based. You can reference an item in the array by its index number as such $Array[X] where X is the index number of the item you are interested in. So given this array:
$MyArray = 'cat','dog','fish','goat','banana'
If you reference $MyArray[0] it will return cat, since that is the first item in the array. With arrays in PowerShell the .length and .count properties are synonymous, so when you reference $MyArray.length you are simply getting the count of items in the array. When you count items you start at 1, but array indexes start at 0, which is why you have to do .length - 1 to get the index number of the last item in the array. In my example if we do $MyArray.Length it would return 5, because my array has 5 items in it. So $MyArray[$MyArray.Length - 1] is essentially $MyArray[5 - 1], or $MyArray[4], which is the last item in $MyArray.
In addition to referencing items by index you can also use negative numbers, which will start at the end of the array, and count backwards. This method is not zero based, so $MyArray[-1] references the last item in the array, just like $MyArray[-2] is the second to the last item in the array.
So the difference between $MyArray[$MyArray.length - 1] and $MyArray[-1] is that in the first you calculate the index number for the last item in the array, where the second references the last item in the array regardless of what its index number is.
You can also specify ranges this way, so $MyArray[0..2] would get you the first 3 items in the array, and $MyArray[-2..-1] would get you the last 2 items in the array. That doesn't really apply to your situation right now, but it's handy to know in general and might be helpful in the future for you.
I'm trying to figure out the best way to get unique combinations from a powershell array. For instance, my array might be
#(B,C,D,E)
I would be hoping for an output like this :
B
C
D
E
B,C
B,D
B,E
C,D
C,E
D,E
B,C,D
C,D,E
B,C,D,E
I do not want re-arranged combos. If combo C,D exists already then I do not want combo D,C. It's redundant for my purposes.
I looked into the functions here : Get all combinations of an array
But they aren't what I want. I've been working on figuring this out myself, but have spent quite a bit of time without success. I thought I'd ask the question here so that if someone else already know I'm not wasting my time.
Thanks!
This is an adaptation from a solution for a C# class I took that asked this same question. For any set find all subsets, including the empty set.
function Get-Subsets ($a){
#uncomment following to ensure only unique inputs are parsed
#e.g. 'B','C','D','E','E' would become 'B','C','D','E'
#$a = $a | Select-Object -Unique
#create an array to store output
$l = #()
#for any set of length n the maximum number of subsets is 2^n
for ($i = 0; $i -lt [Math]::Pow(2,$a.Length); $i++)
{
#temporary array to hold output
[string[]]$out = New-Object string[] $a.length
#iterate through each element
for ($j = 0; $j -lt $a.Length; $j++)
{
#start at the end of the array take elements, work your way towards the front
if (($i -band (1 -shl ($a.Length - $j - 1))) -ne 0)
{
#store the subset in a temp array
$out[$j] = $a[$j]
}
}
#stick subset into an array
$l += -join $out
}
#group the subsets by length, iterate through them and sort
$l | Group-Object -Property Length | %{$_.Group | sort}
}
Use like so:
PS C:>Get-Subsets #('b','c','d','e')
b
c
d
e
bc
bd
be
cd
ce
de
bcd
bce
bde
cde
bcde
Note that computational costs go up exponentially with the length of the input array.
Elements SecondstoComplete
15 46.3488228
14 13.4836299
13 3.6316713
12 1.2542701
11 0.4472637
10 0.1942997
9 0.0867832
My tired attempt at this. I did manage to get it to produce the expected results but how it does it is not as elegant. Uses a recursive functionality.
Function Get-Permutations{
Param(
$theInput
)
$theInput | ForEach-Object{
$element = $_
$sansElement = ($theInput | Where-Object{$_ -ne $element})
If($sansElement.Count -gt 1){
# Build a collection of permutations using the remaining elements that were not isolated in this pass.
# Use the single element since it is a valid permutation
$perms = ,$element
For($elementIndex = 0;$elementIndex -le ($sansElement.Count - 1);$elementIndex++){
$perms += ,#(,$element + $sansElement[0..$elementIndex] | sort-object)
}
# For loop does not send to output properly so that is the purpose of collecting the results of this pass in $perms
$perms
# If there are more than 2 elements in $sansElement then we need to be sure they are accounted for
If($sansElement -gt 2){Get-Permutations $sansElement}
}
}
}
Get-Permutations B,C,D,E | %{$_ -join ","} | Sort-Object -Unique
I hope I can explain myself clearly....So each pass of the function will take an array. Each individual element of that array will be isolated from the rest of the array which is represented by the variables $element and $sansElement.
Using those variables we build individual and progressively larger arrays composing of those elements. Let this example show using the array 1,2,3,4
1
1,2
1,2,3
1,2,3,4
The above is done for each "number"
2
2,1
2,1,3
2,1,3,4
and so forth. If the returned array contains more that two elements (1,2 would be the same as 2,1 in your example so we don't care about pairs beyond one match) we would take that array and run it through the same function.
The real issue is that the logic here (I know this might be hard to swallow) creates several duplicates. I suppose you could create a hashtable instead which I will explore but it does not remove the logic flaw.
Regardless of me beating myself up as long as you don't have thousands of elements the process would still produce results.
Get-Permutations would return and array of arrays. PowerShell would display that one element per line. You asked for comma delimited output which is where -join comes in. Sort-Object -Unique takes those sorted string an discards the duplicates.
Sample Output
B
B,C
B,C,D
B,C,D,E
B,C,E #< Missing from your example output.
B,D
B,D,E #< Missing from your example output.
B,E
C
C,D
C,D,E
C,E
D
E
How can I put $org into an array together with $count?
Like this example array:
$myArray = #{
1="SampleOrg";
2="AnotherSampleOrg"
}
Another example:
$myArray = #{
$count="$org";
$count="$org"
}
Example foreach:
$count=0;get-organization | foreach {$count++; $org = $_.Name.ToString();write-host $count -nonewline;write-host " $org"}
$answer = read-host "Select 1-$count"
The above will display:
1 SampleOrg
2 AnotherSampleOrg
Select 1-2:
What I would like to do afterwards is to put the array to use in a switch.
Example:
switch ($answer)
{
1 {$org=myArray[1]} #<-- or whatever that corresponds to "SampleOrg"
2 {$org=myArray[2]} #<-- or whatever that corresponds to "AnotherSampleOrg"
}
You have to initialize your hashtable somewhere before the loop:
$myArray = #{}
and add a
$myArray.Add($count, $org)
to your foreach-loop.
EDIT: For the discussion about hastable/array see the whole thread ;) I just kept the name of the variable from the original posting
Looks like you're confusing arrays and Hashtables. Arrays are ordered, and indexed by an numeric value. Hashtables are associative, and indexed by any value that has equality defined.
This is array syntax
$arr = #(1,2,3)
and this is Hashtable syntax
$ht = #{red=1;blue=2;}
For your question, the following will work
$orgs = #(get-organization | % { $_.Name })
this will create a 0 based array, mapping int -> OrgName, so
$orgs[$answer]
will get the correct name. Or if you're using 1 based indexing
$orgs[$answer-1]
Note, I removed the switch, as there's no reason for it.