Author Posts

April 26, 2016 at 10:01 am

So I have these two variables with that contain following values:
variable1
data1
data2
data3
data4
data5
data6
data7
data8
data9
data10
data11
data12
data13
data14
data15

variable2
data10
data2
data33
data45
data5
data62
data7
data876
data9

I need to create a third variable with values from variable1 that don't match values from variable2.
TIA!

April 26, 2016 at 10:49 am

As always in PowerShell there are hundreds of ways to reach your goal. One simple approach would be to use the Compare-Object cmdlet to compare your two sets of data. By default, the Compare-Object cmdlet returns values that are different in each set of data. Take a look at the following:

[Array]$var1 += 'data1',
'data2',
'data3',
'data4',
'data5',
'data6',
'data7',
'data8',
'data9',
'data10',
'data11',
'data12',
'data13',
'data14',
'data15'

[Array]$var2 += 'variable2',
'data10',
'data2',
'data33',
'data45',
'data5',
'data62',
'data7',
'data876',
'data9'

$var3 = (Compare-Object $var1 -DifferenceObject $var2 | Where-Object {$Psitem.Sideindicator -eq '< ='}).InputObject

Here you take your first set of data (var1) and your second set (var2) and compare them together. We then pass this to Where-Object to specify which set of data we are interested in. In this case we take the <= side (non difference side). If we left the Where-Object filterscript off we would get back ALL results that are different from each other on both sides. After our Where-Object we select the InputObject property of our object to simply return the Names. All of this data is now stored into var3. Give it a try and see how you go. EDIT: for some reason <= gets formatted to include a space in the middle 🙁 You will need to remove the space.

April 26, 2016 at 10:52 am

$array1 = " 
data1
data2" -split "`n"

$array2 = " 
data10
data2" -split "`n"

foreach ($item in $array1){
    If ($array2 -notcontains $item){
    $array3 += @($item)}}
$array3

April 26, 2016 at 10:53 am

Another way would be something along these lines:

$variable1 = @(
    'data1',
    'data2',
    'data3',
    'data4',
    'data5',
    'data6',
    'data7',
    'data8',
    'data9',
    'data10',
    'data11',
    'data12',
    'data13',
    'data14',
    'data15'
)

$variable2 = @(
    'data10',
    'data2',
    'data33',
    'data45',
    'data5',
    'data62',
    'data7',
    'data876',
    'data9'
)

$variable3 = $variable1 | Where-Object { $_ -notin $variable2 }