Knowledge Base

Preserving for the future: Shell scripts, AoC, and more

Powershell notes

sum attribute of objects in array

( $foo.disksizerequired | Measure-Object -Sum ).Sum /1024/1024
1206181

Save down user photo from Active Directory

https://devblogs.microsoft.com/scripting/weekend-scripter-exporting-and-importing-photos-in-active-directory/
$path = "E:\test\output1.jpg"
$user = get-aduser "bgstack15" -properties thumbnailphoto
[System.Io.File]::WriteAllBytes($path,$user.thumbnailphoto)

Display string of asterisks for a password. Obscure a password for display.

$output=""; For ($c=0; $c -lt $pass.length; $c++){$output+="*"}; Write-Host $output

Function uses -Verbose flag (from powershell - How to properly use the -verbose and -debug parameters in a custom cmdlet - Stack Overflow

function DoStuff {
    [CmdletBinding()]
    param()

    process {
        if ($PSBoundParameters['Verbose']) {
            # Do verbose stuff
        }

        New-Item Test -Type Directory -Verbose:($PSBoundParameters['Verbose'] -eq $true)
    }
}
DoStuff -Verbose

Also, this example from How to write a PowerShell function to use Confirm, Verbose and WhatIf | SQL DBA with A Beard

function Set-FileContent {
    [cmdletbinding(SupportsShouldProcess)]
    Param(
        [Parameter(Mandatory = $true)]
        [ValidateNotNullOrEmpty()]
        [string]$Content,
        [Parameter(Mandatory = $true)]
        [ValidateScript( {Test-Path $_ })]
        [string]$File
    )
    if ($PSCmdlet.ShouldProcess("$File" , "Adding $Content to ")) {
        Set-Content -Path $File -Value $Content
    }
}

Timestamps

# Slightly more readable: 2020-01-15T17:07:59Z
(Get-Date).ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ssZ")
#Also just fine
(Get-Date -Format FileDateTimeUniversal)

Creating a DateTime object with a specific UTC DateTime in PowerShell - Stack Overflow

Import CSV to dictionary

With column headings of ID and Data:

Import-Csv $filePath | % { $HashTable[$_.ID] = $_.Data }

Powershell CSV with headers to hashtable - Stack Overflow

Set locale for one command
function Set-Culture([System.Globalization.CultureInfo] $culture) { [System.Threading.Thread]::CurrentThread.CurrentUICulture = $culture ; [System.Threading.Thread]::CurrentThread.CurrentCulture = $culture } ; Set-Culture en-US ; [system.threading.thread]::currentthread.CurrentCulture

The last command there displays the desired (en-US) locale. You can run a command there. Reference: Change the current culture of a Powershell session, v3.0+ specific - Stack Overflow

Run script
added 2024-01-18

Open a new powershell window.

C:\Windows\system32\WindowsPowerShell\v1.0\powershell.exe -ExecutionPolicy Unrestricted

And then dot-source your function library.

Find remote display resolution
added 2024-02-22

In newer versions of Windows Server, you cannot just right-click the desktop and view the properties, to learn the effective screen resolution. The dialog says, "The display settings can't be changed from a remote session." But I just wanted to see it!

Recommended that you run this in a subshell (just powershell.exe) because once you load the assembly it will always think that is the resolution even after it changes.

Add-Type -AssemblyName System.Windows.Forms
$a = [System.Windows.Forms.Screen]::AllScreens.WorkingArea.Size ; "$($a.Width)x$($a.Height)"

References:

Comments