Script Bits

My collection of random bits of PowerShell scripts I find very useful. These could be full PowerShell scripts, PowerShell functions, PowerShell modules, or smaller bits.

Get Chocolatey Package Version

Created 2019-07-21

This is a simple PowerShell function I created that simply gets the version of the Chocolatey package URL parameter.

Get-ChocoPackageVersion

function Get-ChocoPackageVersion {
    # Gets the version of the Chocolatey package specified by the URL using the -ChocoPackageVersion parameter.
    # Defaults to GoogleChrome if you do not specify the ChocoPackageURL parameter.
    [cmdletbinding()]
    param(
        [Parameter(Position=0)]
        [String]$ChocoPackageURL = "https://chocolatey.org/packages/GoogleChrome"
    )
    $script:ChocoPackageVersion = ((Invoke-RestMethod -Uri $ChocoPackageURL).Split("`r`n") | Select-String "<title>").ToString() -split " " | Select-Object -Last 1
}

Get-ChocoPackageVersion -ChocoPackageURL "https://chocolatey.org/packages/notepadplusplus"
Write-Output "`nRetrieved package version: [$script:ChocoPackageVersion]"

Output

Retrieved package version: [7.7.1]

Pronounceable Random Password

Github:
https://github.com/tjgruber/New-Passwd

Creates a random password that is actually pronounceable, making it possible to remember, but more importantly in my case, much quicker to type.

I converted this handy Script Bit from a PHP equivalent a colleague of mine had created a number of years ago. There is a single “Length” switch that allows you to specify the number of syllables that are produced.

New-Passwd -Length 4 -Count 10

Script

function New-Passwd {
<#

.SYNOPSIS
A simple script that generates a random, but human-pronounceable password.

.DESCRIPTION
Version: 2.0
This script creates a random password based on human-pronounceable syllables.
You can adjust the number of syllables, and when working with it interactively,
includes the ability to generate multiple passwords. The generated password
will include a symbol character in a random location, and a 2-4 digit number suffix.

When integrating this function into a script, you'll likely want to use the -HideOutput
switch to prevent the password from being outputted to the console.

.EXAMPLE
New-Passwd

Default generates one password that is four (4) syllables long, 15-17 character length total.

Example output:
PS > Jabgot@darsay8472

.EXAMPLE
New-Passwd -Length 20 -Count 5

Generates 5 passwords that are each 20-syllables long.

Example output:
PS > Neoreonuasantotlenlodjusveitavfihpotretvifruajigvuolua;tiuket6348
PS > Coasuukocfekbestajbacnutbabheptaksegcui.sesnadsotjuncaesojpou7255
PS > Paeruamohsadheimukbanneakui;pujgodmejsuinegjaobitfoffejgafheu2701
PS > Hapdaobagtiecokbihlubkiurubroelephep-munlijdumgemcuspagmuvkub4728
PS > Dejtegbia{gonbimpilpiltavvardiiribdujsevvujfovripdornopjiodoj3586

.EXAMPLE
New-Passwd -HideOutput

Generates one default password that is four (4) syllables long, 15-17 character length total,
and does not show the output. It is useful to include this switch when calling from within
a script where you will be using the $script:Passwd variable elsewhere.
Default is to write output.

Example output:
PS > 

#>
    [cmdletbinding()]
    param(
        [Parameter(Position=0)]
        #Default length in syllables.
        [Int]$Length = 4,
        [Parameter(Position=1)]
        #Default number of passwords to create.
        [Int]$Count = 1,
        [Parameter(Position=2)]
        #Hides the output. useful when used within a script.
        [Switch]$HideOutput
    )
    Begin {
        #consonants except hard to speak ones
        [Char[]]$lowercaseConsonants = "bcdfghjklmnprstv"
        [Char[]]$uppercaseConsonants = "BCDFGHJKLMNPRSTV"
        #vowels
        [Char[]]$lowercaseVowels = "aeiou"
        #both
        $lowercaseConsantsVowels = $lowercaseConsonants+$lowercaseVowels
        #numbers
        [Char[]]$numbers = "0123456789"
        #special characters
        [Char[]]$specialCharacters = '!$.;#@{+&}?:+_="%>-*/^'+"'"

        $countNum = 0
    }
    Process {
        while ($countNum -le $Count-1) {
            $script:Passwd = ''
            #random location for special char between first syllable and length
            $specialCharSpot = Get-Random -Minimum 1 -Maximum $Length
            for ($i=0; $i -lt $Length; $i++) {
                if ($i -eq $specialCharSpot) {
                    #add a special char
                    $script:Passwd += ($specialCharacters | Get-Random -Count 1)
                }
                #Start with uppercase
                if ($i -eq 0) {
                    $script:Passwd += ($uppercaseConsonants | Get-Random -Count 1)
                } else {
                    $script:Passwd += ($lowercaseConsonants | Get-Random -Count 1)
                }
                $script:Passwd += ($lowercaseVowels | Get-Random -Count 1)
                $script:Passwd += ($lowercaseConsantsVowels | Get-Random -Count 1)
            }
            #add a number at the end
            $randNumNum = Get-Random -Minimum 2 -Maximum 5
            $script:Passwd += (($numbers | Get-Random -Count $randNumNum)-join '')
            if ($HideOutput) {
                # The $Passwd is not shown as output.
            } else {
                Write-Output "$script:Passwd"
            }
            $countNum++
        }
    }
}

Output

Bepnemluo>tia687
Tohhap-viaboi654
Rukhujduf{ril159
Nimfulbeg_run206
Pohrod(vigfuc270
Kiefao+rarsob179
Pon&pocfatder854
Par{faesekpas627
Fionav>ceaguh684
Cojvidcod!cad808

Set an Intune Win32 LoB App’s Category

Github:
https://github.com/tjgruber/Set-IntuneAppCategory

Adds or removes an Intune Win32 LoB app to or from an Intune app category based on a CategoryName match or exact CategoryId parameter.

I had a need for a function like this inside of an Azure DevOps release pipeline script. Here’s the result.

Set-IntuneAppCategory -CategoryName “App Category Name” -Add -AppId “662f02ca-eaba-4798-a20b-abab4214c0bd”

Script

<####################################################
# SET INTUNE APP CATEGORY
####################################################>
function Set-IntuneAppCategory {
<#
.SYNOPSIS
	Adds or removes an Intune Win32 LoB app to or from an Intune app category.
.DESCRIPTION
	Adds or removes an Intune Win32 LoB app to or from an Intune app category based on a CategoryName match or exact CategoryId parameter.
.PARAMETER CategoryName
	The name of the category to match.
.PARAMETER CategoryId
	The ID of the category. This needs to be exact.
.PARAMETER Add
	Adds specified app to specified category.
.PARAMETER Remove
    Removes specified app to specified category.
.PARAMETER AppId
	The ID of the app.
.EXAMPLE
	Set-IntuneAppCategory -CategoryName "Test group 0" -Add -AppId "662f02ca-eaba-4798-a20b-abab4214c0bd"
.EXAMPLE
	Set-IntuneAppCategory -CategoryName "Test group 0" -Remove -AppId "662f02ca-eaba-4798-a20b-abab4214c0bd"
.NOTES
	This is designed as an internal script function rather than a stand-alone function, but will work if you input the correct parameters.
.LINK
	https://TimothyGruber.com
#>
    [cmdletbinding()]
    param(
        [Parameter(Mandatory,ParameterSetName='CategoryName')]
        [string]$CategoryName,
        [Parameter(Mandatory,ParameterSetName='CategoryId')]
        [string]$CategoryId,
        [Parameter()]
        [switch]$Add,
        [Parameter()]
        [switch]$Remove,
        [Parameter(Mandatory)]
        [string]$AppId
    )
    if ($CategoryName) {
        $intuneAppGetCategoryNameIdUri = 'https://graph.microsoft.com/beta/deviceAppManagement/mobileAppCategories'
        $intuneAppGetCategoryNameIdRequest = @{
            ContentType = "application/json";
            Method = "Get";
            Uri = $intuneAppGetCategoryNameIdURI;
            ErrorAction = "SilentlyContinue";
            ErrorVariable = "intuneAppGetCategoryNameIdERR"
        }
        Invoke-GraphAPIAuthTokenCheck
        $setintuneAppGetCategoryNameIdDATA = (Invoke-RestMethod -Headers $global:graphAPIReqHeader @intuneAppGetCategoryNameIdRequest)
        if ($intuneAppGetCategoryNameIdERR) {
            Write-Output "...ERROR - There was a problem retrieving setintuneAppGetCategoryNameIdDATA - [$intuneAppGetCategoryNameIdERR]"
        }
        $matchedCategoryNameId = $setintuneAppGetCategoryNameIdDATA.value | Where-Object {$_.displayName -match $CategoryName}
        if (-not($matchedCategoryNameId)) {
            Write-Output "...ERROR - Could not match input of [$CategoryName] to an Intune Mobile App Category."
        }
        $intuneAppGetCategoryIdUri = "https://graph.microsoft.com/beta/deviceAppManagement/mobileAppCategories/$($matchedCategoryNameId.id)"
        $CategoryId = $matchedCategoryNameId.id
    }
    if ($Add) {
        $requestMethod = "Post"
        $intuneAppAddCategoryUri = "https://graph.microsoft.com/beta/deviceAppManagement/mobileApps/$appId/categories/`$ref"
        $intuneAppAddCategoryBody = @{
            '@odata.id' = $intuneAppGetCategoryIdUri
        }
        $intuneAppSetCategoryRequest = @{
            ContentType = "application/json";
            Body = ($intuneAppAddCategoryBody | ConvertTo-Json);
            Method = $requestMethod;
            Uri = $intuneAppAddCategoryUri;
            ErrorAction = "SilentlyContinue";
            ErrorVariable = "intuneAppCategoryERR"
        }
    }
    if ($Remove) {
        $requestMethod = "Delete"
        $intuneAppRemoveCategoryUri = "https://graph.microsoft.com/beta/deviceAppManagement/mobileApps/$appId/categories/$categoryId/`$ref"
        $intuneAppSetCategoryRequest = @{
            ContentType = "application/json";
            Method = $requestMethod;
            Uri = $intuneAppRemoveCategoryUri;
            ErrorAction = "SilentlyContinue";
            ErrorVariable = "intuneAppCategoryERR"
        }
    }
    Invoke-GraphAPIAuthTokenCheck
    $setintuneAppSetCategoryIdDATA = (Invoke-RestMethod -Headers $global:graphAPIReqHeader @intuneAppSetCategoryRequest)
    if ($intuneAppCategoryERR) {
        Write-Output "...ERROR - There was a problem retrieving setintuneAppSetCategoryIdDATA - [$intuneAppCategoryERR]"
    }
}

Leave a Reply

Your email address will not be published. Required fields are marked *