You are asking about software metering. MS provides purpose built solutions for that, so why script it? Don’t write code, if you don’t have to. Don’t’ reinvent the wheel unless you have to, and you really know it will be a better wheel, or it’s just a learning process.
Software metering in System Center Configuration Manager
Configuration Manager Software Metering
There are even pre-built SCCM scripts for this use case.
SCCM - Collection for Software metering
This PowerShell script allow you to create some collection for your software metering rules:The idea came after reading the post from Nicolas Pilon here:https://www.systemcenterdudes.com/sccm-automatically-uninstall-application/As I have seen some peolple having some difficulties
Download : CreatecollRules.ps1