I’m new to power shell, I have 2 lists like
$list1=[‘1’,’2’,’5’,’6’,’4’];
$list2=[‘9’,’10’,’8’,’6’,’5’];
$expectedoutputlist=[‘9’,’10’,’8’,’5’,’6’];
Based on the order of list1 I need to update the order of list2 where it have common items in both the lists if not remain same.
I need solution in getting desired output in power shell , please help me
CodePudding user response:
Use the Array.IndexOf() method.
This works in your case because for items in $list2 that cannot be found in $list1, IndexOf() returns -1
, so these will be sorted on top.
The way you define your 'lists' is wrong/quite unusual.. The square brackets should not be there.
Below $list1 and $list2 are defined as arrays.
$list1 = '1','2','5','6','4'
$list2 = '9','10','8','6','5'
$sorted = $list2 | Sort-Object { $list1.IndexOf($_) }
Result:
$sorted -join ',' # --> 9,10,8,5,6
or if you rather see the values quoted:
($sorted | ForEach-Object { "'{0}'" -f $_ }) -join ',' # --> '9','10','8','5','6'
CodePudding user response:
The following script could help:
$list1 = '1','2','5','6','4'
$list2 = '9','10','8','6','5'
$list1Reduced = $list1.Where({ $_ -in $list2 })
$ii1 = 0
for ( $ii2 = 0; $ii2 -lt $list2.Count; $ii2 ) {
if ( $list2[$ii2] -in $list1Reduced ) {
$list2[$ii2] = $list1Reduced[$ii1]
$ii1
if ( $ii1 -ge $list1Reduced.Count ) { $ii1 = 0 } # or $ii1--
}
}
$list2 -join ','
Output: .\SO\69359305.ps1
9,10,8,5,6