0

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 "*-*" ) 
0

2 Answers 2

2

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
}
Sign up to request clarification or add additional context in comments.

4 Comments

Thank you so much for your help. Tried the second option and it worked like a charm!
@afzzaps, if this is the best answer to your question, please select the check mark icon to the left of the answer. That lets others know that this is the best answer. That is how SO works.
@Mathias, one last item I stumbled upon and if you could help too. After filtering out the $server in $servers -like -; I need to find out which of these servers doesn't start with TPP. How can I add that additional filter along with the - filter ?
@afzzaps You can either chain multiple calls to Where-Object: ... |Where { $_ -like "*-*"} |Where {$_ -notlike "TPP*"}, or combine multiple comparisons into a single clause with the -and operator: ... |Where { $_ -like "*-*" -and $_ -notlike "TPP*" }. You could also chain multiple filter comparisons (although it might not be super readable/obvious): @(@($servers) -like "*-*") -notlike "TPP*"
0

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
$_

}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.