Skip to content

Instantly share code, notes, and snippets.

@indented-automation
Created September 5, 2023 12:02
Show Gist options
  • Save indented-automation/381be11511114d5cd7ae171726038cad to your computer and use it in GitHub Desktop.
Save indented-automation/381be11511114d5cd7ae171726038cad to your computer and use it in GitHub Desktop.
Background Activity Moderator
Add-Type -TypeDefinition @'
using System.Runtime.InteropServices;
using System.Text;
public class Native
{
[DllImport("kernel32.dll", SetLastError = true)]
public static extern uint QueryDosDevice(
string lpDeviceName,
StringBuilder lpTargetPath,
int ucchMax
);
}
'@
$drives = @{}
Get-CimInstance Win32_Volume -Filter 'DriveType=3' | ForEach-Object {
$devicePath = [System.Text.StringBuilder]::new()
$null = [Native]::QueryDosDevice($_.DriveLetter, $devicePath, 65536)
if ($devicePath.ToString()) {
$drives[$devicePath.ToString()] = $_.DriveLetter
}
}
Get-ItemProperty HKLM:\system\CurrentControlSet\services\bam\state\UserSettings\* | ForEach-Object {
try {
$user = ([System.Security.Principal.SecurityIdentifier]$_.PSChildName).Translate(
[System.Security.Principal.NTAccount]
)
} catch {
$user = $_.PSChildName
}
$_.PSObject.Properties | Where-Object Name -match '\\Device|_.+' | ForEach-Object {
$bytes = $_.Value[0..7]
$int64 = [BitConverter]::ToInt64($bytes, 0)
$lastUseTime = [DateTime]::FromFileTimeUtc($int64)
$path = $_.Name
if ($path -match '^(\\Device\\[^\\]+)\\(.+)') {
$path = Join-Path $drives[$matches[1]] -ChildPath $matches[2]
}
[PSCustomObject]@{
User = $user
LastUseTime = $lastUseTime.ToLocalTime()
LastUseTimeUtc = $lastUseTime
Path = $path
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment