Struggling with If/Else Logic in PowerShell?

0
0
Asked By CleverMouse27 On

I'm having some trouble with my if/elseif/else statements in PowerShell. I have a directory filled with text files, and I'm using the 'select-string' cmdlet to search through these files for specific text. I'm trying to check if SSH is allowed on my clusters, and if it is, I want to issue a warning. Specifically, if anything other than 'All IP Addresses(*) (deny)' is found, I need to display 'Not Compliant'. Below is a snippet of the code I think is relevant:

```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 I'm facing is that when I allow SSH on a test cluster, the script still marks the cluster as compliant. The output in the text file reads 'All IP Addresses(*) (allow)'. I'm wondering if my logic is flawed either in the order of checks or in the specific patterns I'm searching for.

2 Answers

Answered By TechieTim24 On

Make sure you check what's actually in `$implementations`. You could step through your code in debug mode too. Also, clarify if `$clusters` is just the names or if it's linked to the actual cluster objects—you might want to adjust your check to get properties of the objects, not just names. And take a look inside your `$transcript*.txt` files, they might hold the key. Lastly, have you considered switching to a `switch` statement instead of if/elseif? That might simplify things!

CleverMouse27 -

I can post that info tomorrow, thanks!

Answered By ScriptGuru99 On

It sounds like you might want to debug your script a bit. Go through it line by line and see if your assumptions about the results hold up. That should help you spot any issues!

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.