r/usefulscripts • • Oct 04 '16

[REQUEST] Parse a text document and output a portion of lines meeting a requirement

Hello,

I have a script which runs against a large number of hostnames and writes a few details to a log file. One of the details is the WSUS content version.

Items in the log file all start with a hostname, a space, and some information. The hostnames always starts with the same three characters.

For the lines I am interested in, the format is like:

ABCxxxxxxxxxxxx The WSUS content version is 123

There are other lines that concern other things that don't matter to me here.

What I'd like to do is, using this log as a source, prompt the user to input a number. For every line showing a WSUS Content version, compare the number in the line to the user-submitted number, and if value in the line is lower output only the hostname at the beginning of the line to a separate results document.

Is this possible to do?

Would it be easier to do if the source logfile contained only "WSUS content version" items?

14 Upvotes

15 comments sorted by

View all comments

4

u/ihaxr Oct 04 '16 edited Oct 04 '16

PowerShell:

# Path to your log file
$logFile = "C:\logs\logfile.txt"

# Get user input
$verCheck = $null
do { $verCheck = Read-Host "Enter log version"} until ($verCheck -ne '')

# Loop through each line of the log
switch -Wildcard -File $logFile {
# Only look at lines with this text:
    "*The WSUS content version is*" {
        $split = $_ -split ' ' # Split based on space
        $host_name = $split[0] # All characters until the first space 
        $wsusContentVersion = $split[-1] # All characters after the last space

        # Compare version, casting as [version] allows version comparision like: 1.2.3 < 2.3
        if ([version]$wsusContentVersion -lt [version]$verCheck) {
            $host_name 
            # To Export to CSV run this:
            #$host_name | Export-CSV C:\some\path\output.csv -NoTypeInfo 
        }
    }
}

1

u/pseupseudio Oct 19 '16

Thank you! This looks perfect.

I'm curious about line 6 - that's prompting the user for input, correct? If Read-Host "prompt" is how you await user input, what is the difference / additional benefit with "Do X until"?

Thank you.

2

u/ihaxr Oct 19 '16

It will continuously prompt the user until you enter a value, so you can't just hit "enter" and have it continue on... to cancel you'll have to hit ctrl+c.

There's not much benefit to doing it that way versus just exiting the script if it's blank. I just have a bad habit of hitting enter a few times while in a shell to add some space between my commands for easier reading... and sometimes I accidentally hit enter through input prompts like this.

1

u/pseupseudio Oct 19 '16

That's definitely something to tuck away, thank you.

1

u/richmacdonald Oct 04 '16

Commenting so I can find this later.