Home > Software design >  Powershell syntax to use where condition with a foreach loop
Powershell syntax to use where condition with a foreach loop

Time:09-29

I'm new to powershell and have been practicing to get better so would greatly appreciate all your help.

I have a txt file with just a list of servers that I need to add an account to. However, I need to exclude the server names that does not contain "-" in the servername.

This is what I have right now which obviously doesn't work and I keep getting errors.

    $servers = Get-Content "$PSScriptRoot\SQLServers.txt"
    

     foreach ($server in $servers| Where $server -contains "*-*" ) 

CodePudding user response:

For a wildcard string comparison, you'll want the -like operator, and then refer to the current pipeline item being tested by Where-Object with $_:

foreach ($server in $servers |Where { $_ -like "*-*" }) {
   # work with each matching $server here
}

-like can also be used to filter a collection of strings directly, so in your case you could do:

foreach ($server in @($servers) -like "*-*") {
   # work with each matching $server here
}

CodePudding user response:

If your file have only one column you can use import csv and directly set the name of one and uniq colum, like this :

Import-Csv "$PSScriptRoot\SQLServers.txt" -Header server | where server -Like "*-*" | foreach{

#user serveur name here
$_.Server

}

Otherwise you can directly filter on $_ variable like this :

Get-Content "$PSScriptRoot\SQLServers.txt" | where {$_ -like "*-*"} | foreach{

#user serveur name here
$_

}
  • Related