Checking Profile Scripts (Part 2)

by Oct 1, 2020

In the previous script we came up with a one-liner that checks which profile scripts actually exist. This solution works per host only, though, because each host uses its own host-specific profile paths.

Here is a more generic approach: it lists all profile paths for all PowerShell hosts present on your system. You could then check these files as part of a security or sanity check:

# calculate the parent paths that can contain profile scripts
$Paths = @{
    AllUser_WPS = $pshome
    CurrentUser_WPS = Join-Path -Path ([Environment]::GetFolderPath('MyDocuments')) -ChildPath "WindowsPowerShell"
    AllUser_PS = "$env:programfiles\PowerShell\*"
    CurrentUser_PS = Join-Path -Path ([Environment]::GetFolderPath('MyDocuments')) -ChildPath "PowerShell"

# check all paths for PowerShell scripts ending on "profile.ps1"
$Paths.Keys | ForEach-Object {
    $key = $_
    $path = Join-Path -Path $paths[$key] -ChildPath '*profile.ps1'
    Get-ChildItem -Path $Path |
      ForEach-Object {
        # create a custom object with all relevant details for any
        # found profile script

        # name of PowerShell host is the prefix of profile file name
        if ($_.Name -like '*_*')
            $hostname = $_.Name.Substring(0, $_.Name.Length-12)
            $hostname = 'any'
            # scope and PowerShell version is found in the 
            # name of the parent folder
            Scope = $key.Split('_')[0]
            PowerShell = $key.Split('_')[1]
            Host = $hostname
            Path = $_.FullName

The result reports the existing PowerShell profile scripts for all hosts and may look similar to this:

Scope       PowerShell Host                    Path                                                                           
-----       ---------- ----                    ----                                                                           
CurrentUser WPS        Microsoft.PowerShellISE C:\Users\tobia\OneDrive\Dokumente\WindowsPowerShell\Microsoft.PowerShellISE_...
CurrentUser WPS        any                     C:\Users\tobia\OneDrive\Dokumente\WindowsPowerShell\profile.ps1                
CurrentUser PS         Microsoft.VSCode        C:\Users\tobia\OneDrive\Dokumente\PowerShell\Microsoft.VSCode_profile.ps1   

Twitter This Tip! ReTweet this Tip!