DEV Community

jsguru
jsguru

Posted on

6 6

Programmatically determine OS is up to date or outdated on windows or mac osx .

Recently I have developed Software for Windows and Mac osx.
Here I needed to determine my os is up to date or outdated programmatically.

For windows version, programming language is C# and for mac osx version, swift is used.

I could implement the function in C# because there are C# code snippet related my purpose over internet.

But unfortunately, no luck for Mac osx and swift.
There are too much articles to get Mac osx or iOS version.
They was not my concerns.

Below is C# implementation for windows version.

bool CheckIsOSUpdated()
{
    IUpdateSession updateSession = new UpdateSession();
    IUpdateSearcher searcher;
    searcher = updateSession.CreateUpdateSearcher();
    ISearchResult updates = searcher.Search("IsInstalled=0 and Type='Software' and IsHidden=0");
    //ISearchResult updates = searcher.Search("IsInstalled=0");
    if (updates.Updates.Count == 0)
        return true;
    else
        return false;
}

Then the implementation in swift for Mac osx version is

import SwiftShell

func getIsOSXUpdate() -> Bool {
    // softwareupdate --list|tee
    // let command = runAsync("softwareupdate", "--list").stdout.runAsync("tee")
    let command = runAsync("softwareupdate", "--list")
    do {
        try command.finish()
    } catch {
        NSLog("could not collect available updates.")
        return false
    }

    _ = command.stdout.read()
    let error = command.stderror.read()

    if error.contains("No new software available") {
        return true
    }

    return false
}

You may wonder why stderror is used rather than stdout.
When you run softwareupdate --list on terminal, you will see the result like below if your Mac os is up to date.

JSGURUs-Mac:~ jsguru$ softwareupdate --list
Software Update Tool

Finding available software
No new software available.
JSGURUs-Mac:~ jsguru$ 

Strangely, stdout returns "Software Update Tool\n\nFinding available software\n" and stderror returns "No new software available.\n".
That's why stderror is used.

I hope these code snippets help you.

Postmark Image

Speedy emails, satisfied customers

Are delayed transactional emails costing you user satisfaction? Postmark delivers your emails almost instantly, keeping your customers happy and connected.

Sign up

Top comments (2)

Collapse
 
buinauskas profile image
Evaldas Buinauskas
return updates.Updates.Count == 0;

Shorter 🙂

Collapse
 
jsgurugit profile image
jsguru

Yes, you are right.

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay