I am trying to exclude a list of database names got from a csv file in a foreach loop. Instead of excluding me the names of dbs powershell multiplies me the number of entries:
PS:
$b1 = Import-CSV -Path C:\tst.csv
foreach ($ServerName in $Servers){
Foreach($Database in $SQLServer.Databases)
{
foreach($a in $b1){
$server = $a.Name
$db = $a.SQL
if ($ServerName.Name -ne $server -and $Database.Name -ne $db){
$Database.Name
}
}
}
}
CSV List:
Name,SQL
server1,db1
server1,db2
server2,db1
output:
db0
db0
db0
db1
db1
db2
db2
etc
Servers: s1 s2 s3
Can anyone give an advise on this?
Thank you!
CodePudding user response:
This condition in your inner loop:
$ServerName.Name -ne $server -and $Database.Name -ne $db
Is doing a line-by-line comparison which is likely to be $true
more than once, we don't have enough information on this, but your issue is likely to be solved if you use containment operators for this (you can use -notin
or -notcontains
, it's up to you). As aside, your second inner loop is iterating over $SQLServer
which is also not defined and unclear what it is.
$csv = Import-CSV -Path C:\tst.csv
foreach($ServerName in $Servers) {
foreach($Database in $SQLServer.Databases) {
if($ServerName.Name -notin $csv.Name -and $Database.Name -notin $csv.SQL) {
$Database.Name
}
}
}
CodePudding user response:
add the results in an array and call it with unique paramter
to creat the array
$array = @()
in the loop add this
$array = $Database.Name
then after loop
$array | select -Unique