Group-based licensing requires Azure AD Premium subscription though, so it's not ideal solution.
Windows PowerShell is a task automation and configuration management framework from Microsoft, consisting of a command-line shell and associated scripting language built on the .NET Framework. PowerShell provides full access to the Component Object Model (COM) and Windows Management Instrumentation (WMI), enabling administrators to perform administrative tasks on both local and remote Windows systems as well as WS-Management and Common Information Model (CIM) enabling management of remote Linux systems and network devices.
TRUSTED BY
I started with the PowerShell using the MSOL cmdlets to manage this and am now using the Azure Graph API via PowerShell to do this, but it is all part of a much larger identity management solution so I can't really put it up here. That said, Microsoft have recently introduced licensing templates for O365. Check out:
https://blogs.technet.microsoft.com/enterprisemobility/2017/02/22/announcing-the-public-preview-of-azure-ad-group-based-license-management-for-office-365-and-more/
I think this will natively in O365 achieve what you are looking to do. I certainly wish this was around at the start, but our solutions are now well entrenched to change.