PowerShell noob question here. I have groups of servers that are listed in separate lists. Each server has an error log that I scan for certain errors. However, each group of servers has its own unique set of errors that I scan using a specific search string for that server group. What I’m basically doing is creating a condition based on the server list name and mapping the appropriate search string for that server group.
Something like this:
$SERVER_LST_1 = "$pwd\servers\servers_1.lst"
$SERVER_LST_2 = "$pwd\servers\servers_2.lst"
$SERVER_LST_3 = "$pwd\servers\servers_3.lst"
$SEARCH_STR_1 = "Error text for server group 1"
$SEARCH_STR_2 = "Error text for server group 2"
$SEARCH_STR_3 = "Error text for server group 3"
$Servers1 = Get-Content $SERVER_LST_1
ForEach ($Server1 in $Servers1)
{
$StartupErrorLog1 = Get-ChildItem -Path \\$Server1\$LOG_PATH -Include StartupError.log -Recurse | Select-String -notmatch $SEARCH_STR_1
}
$Servers2 = Get-Content $SERVER_LST_2
ForEach ($Server2 in $Servers2)
{
$StartupErrorLog2 = Get-ChildItem -Path \\$Server2\$LOG_PATH -Include StartupError.log -Recurse | Select-String -notmatch $SEARCH_STR_2
}
$Servers3 = Get-Content $SERVER_LST_3
ForEach ($Server3 in $Servers3)
{
$StartupErrorLog3 = Get-ChildItem -Path \\$Server3\$LOG_PATH -Include StartupError.log -Recurse | Select-String -notmatch $SEARCH_STR_3
}
I would like to make the code more efficient by not using so many conditions. Is there a cleaner approach to map the search strings to their appropriate server group by using less code? Hope that makes sense.
You can refactor it into something like below:
Basically, using an HashTable to associate the search text and the server group. Also, I have given only the refactoring solution, but the Get-ChildItem and Select-String may not be doing what you want to.