Need Help with If/Else Logic in PowerShell Script

0
36
Asked By CuriousCactus42 On

I'm having some trouble with my PowerShell script's if/elseif/else logic and could use some guidance. I'm working with a list of text files and using `select-string` to search for specific text. My goal is to check if SSH is allowed on my clusters. If it is allowed, I want to throw a warning. Also, anything other than "All IP Addresses(*) (deny)" should be displayed as "Not Compliant". Here's the relevant part of my code, though it's not the entire script. The variable "clusters" is an array containing the names of the clusters I'm checking.

```powershell
$implementations = @(Get-Content -Path 'C:pathImplementationclusters.txt')

foreach ($cluster in $clusters.name) {
if ($implementations -contains $cluster) {
Write-Host "$cluster is with Implementations team"
}
elseif (Select-String -path $transcript*.txt -Pattern 'All IP Addresses(*) (deny)' -simplematch) {
Write-Host "$cluster is compliant!"
}
elseif (Select-String -path $transcript*.txt -Pattern '(*allow)' -simplematch) {
Write-Host "$cluster is not compliant!" -ForegroundColor White -BackgroundColor Red
}
else {
Write-Host "$cluster is not compliant"
}
}
```

The issue arises when I allow SSH on a test cluster; the script still labels it as compliant. In my text file, the entry reads "All IP Addresses(*) (allow)". I suspect my problem could be due to the order of my checks or maybe what I'm using for the pattern. Any insights would be appreciated!

2 Answers

Answered By CodeWhisperer89 On

You really need to examine what's in `$implementations`. Also, is `$clusters` populated from a command like `get-cluster`? Right now, it looks like `$cluster` is simply a name and not the entire cluster object. You might also want to manually check the contents of your `$transcript*.txt`. Have you thought about whether to use a `switch` statement instead of `if/else`? Without more detail, debugging is probably your best bet. You could also try manually setting a value for `$cluster` and test your conditions that way.

CuriousCactus42 -

I can share those details tomorrow, thanks for the tips!

Answered By DebuggingDynamo On

I've found that stepping through your script line by line can really help identify where it might be going wrong. It’s often easier to see if your assumptions hold true that way. I'd suggest trying that first!

Related Questions

LEAVE A REPLY

Please enter your comment!
Please enter your name here

This site uses Akismet to reduce spam. Learn how your comment data is processed.