Simple PowerShell Logging Function

I use this simple PowerShell logging function in multiple smaller scripts of mine to write a hourly logfile with a generic name in a specific path.

As an input it takes the two parameters “message” and “severity”. The later is optional and set to “INFO” by default. It further needs the (global) variable $logPath which should be defined and filled with the full path to where the logfile should be stored on the filesystem.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
# Define the log output directory
$logPath = "C:\temp\log"
 
# Simple Logging Function
function Write-Log(){
    [CmdletBinding()]
    Param(
        [Parameter(Mandatory = $true)]
        [String]
        $message = "INFO",
 
        [Parameter(Mandatory = $false)]
        [ValidateSet("INFO","WARN","ERROR","DEBUG")]
        [String]
        $severity = "INFO"
    )
 
    # Define Output Color
    $color = "white"
    if($severity -eq "WARN"){
        $color = "yellow"
    }
    elseif($severity -eq "ERROR"){
        $color = "red"
    }
    elseif($severity -eq "DEBUG"){
        $color = "cyan"
    }
 
    # Create Log Directory if not exists
    if(!(Test-Path $global:logPath)){
        New-Item -ItemType Directory -Path $global:logPath
        Write-Log "Log Directory '$($global:logPath)' created"
    }
 
    # Prepare Log Line
    $logLine = "$(Get-Date -format "dd.MM.yyyy HH:mm:ss") `t $($severity) `t $($message)"
 
    # Write Logfile
    $scriptName = ((($MyInvocation.ScriptName -split ("\\"))[($MyInvocation.ScriptName -split ("\\")).Length -1]) -replace ".ps1", "").ToLower()
    $logFileName = "log_$($scriptName)_$(Get-Date -format "yyyy-MM-dd-HH").log"
    $logLine | Out-File -FilePath "$($global:logPath)\$logFileName" -Append -Encoding utf8
 
    # Print Logline
    Write-Host $logLine -ForegroundColor $color
}
 
#Test it
Write-Log "My Message" 
Write-Log "My Warning Message" "WARN"
Write-Log "My Error Message" "ERROR"
Write-Log "My Debug Message" "DEBUG"

How to create a Scheduled Task using PowerShell

Working with group Managed Service Accounts gMSA (not a topic of this post) and Scheduled Tasks, you’ll figure pretty soon that creating a Scheduled Task using the MMC Snap-in does not get you too far. As a solution: just create your Scheduled Task using Powershell.

I’m therefore using the code below. Just adjust it to your needs as required.

1
2
3
4
5
6
7
8
$taskName = "My Scheduled Task"
$taskDesc = "My fanc description"
$actionArgs = '-file "C:\Path\to\my\Script.ps1"'
$taskAction = New-ScheduledTaskAction -Execute "powershell.exe" -Argument $actionArgs 
$taskTrigger = New-ScheduledTaskTrigger -Daily -At 8:30pm
$taskSettings = New-ScheduledTaskSettingsSet -ExecutionTimeLimit (New-TimeSpan -Minutes 60) -RestartCount 2 -RestartInterval (New-TimeSpan -Minutes 15) -RunOnlyIfNetworkAvailable -Compatibility "Win8"
$taskPrincipal = New-ScheduledTaskPrincipal -UserID "CUSTOMERS\svcgMSA_Task$" -LogonType Password -RunLevel Highest
Register-ScheduledTask -TaskName $taskName -Description $taskDesc -Action $taskAction -Trigger $taskTrigger -Settings $taskSettings -Principal $taskPrincipal

Converting an IPv4 IP Address into a HEX String

The following function converts a given IPv4 IP address into an eight char hex string. Two hex chars in a row presenting eight bits of the IP address.

The idea behind it was to write a nice PowerShell function and to make the IP addresses easily sortable in a database.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
function ipv4ToHexString($ipv4){
 
    # Validation
    $valid = $true
    $ipv4.split(".") | foreach { if([int]$_ -ge 0 -and [int]$_ -le 255) { } else { $valid = $false } }
 
    if($valid -eq $true){
 
        # Conversion
        $hexString = ""
        $hexList = @("0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "a", "b", "c", "d", "e", "f")
        $ipv4.split(".") | foreach {
            $mod = [int]$_ % 16
            $first = $hexList[(([int]$_ - $mod) / 16)]
            $second = $hexList[$mod]
            $hexString += $first+$second
        } 
        return $hexString
    }
    else{
        return $false
    }
}

Active Directory: Export all group Managed Service Accounts (gMSA)

This one-liner exports all group managed Service Accounts (gMSA) from an Active Directory Domain into a .csv file.

As follows, you will find the command as I used it to export certain information about those gMSA in my Domain. You might have to adjust it to your specific needs.

1
2
3
4
5
6
7
8
9
Get-ADServiceAccount -Filter * -Properties * | `
    Select -Property Name, `
        @{name="Owner"; expression={(Get-Acl "AD:\$($_.DistinguishedName)").Owner}}, `
        Enabled, LockedOut, Description,
        @{name="LastLogonDate"; expression={ $_.LastLogonDate.toString("dd.MM.yyyy") }}, `
        @{name="PasswordLastSet"; expression={ $_.PasswordLastSet.toString("dd.MM.yyyy") }}, `
        DistinguishedName | `
        Export-Csv -Path ".\GroupManagedServiceAccounts_$((Get-ADDomain).Name).csv" `
         -NoTypeInformation -Encoding UTF8