One repo for Windows utils in Go, all you need.
- Pure, production-ready Go-style APIs β Zero CGO, no os/exec command-line wrappers, no
syscall. - One-line superpowers β like
RunAsAdmin(),RunTask(), andEmptyRecycleBin(). - Complete control β Master Services, File Systems, Network states, and more.
β‘ Actively developed. Contributions, feature requests, and PRs are more than welcome!
| Module | Feature | Description | Status |
|---|---|---|---|
| π₯οΈ System & Hardware | Accurate OS Version | Bypass compatibility shims to get true Windows version and build. | π’ Stable |
| Active Sessions | List logged-on users and retrieve the active console/desktop session user. | π’ Stable | |
| USB Device Monitoring | Background message-only window listener for USB device plug/unplug. | π’ Stable | |
| Last Shutdown Reason | Query Event Log for last shutdown/reboot/BSOD event parameters. | π’ Stable | |
| Display & Monitor Metrics | Query multi-monitor geometry, bounds, and DPI scaling factors. | π’ Stable | |
| System Uptime | Retrieve elapsed duration since the Windows system was booted. | π’ Stable | |
| Workstation Control | Instantly lock the current Windows desktop session. | π’ Stable | |
| Recycle Bin Control | Programmatically empty the Recycle Bin on all drives silently. | π’ Stable | |
| Memory Metrics | Query current physical and virtual memory utilization bytes. | π’ Stable | |
| Workstation Lock State | Detect if the workstation session is currently locked. | π‘ Roadmap | |
| CPU Metrics | Query average or core-level active CPU utilization percentage. | π‘ Roadmap | |
| GPU Info & Diagnostics | Detect active graphics card models, driver versions, and dedicated VRAM capacity. | π‘ Roadmap | |
| Battery & Power Status | Query real-time power source (AC/DC) and precise remaining battery percentage. | π‘ Roadmap | |
| BIOS & Motherboard Info | Retrieve physical motherboard serial number, manufacturer, and BIOS date/version. | π‘ Roadmap | |
| π Files & Shell | Shortcuts (.lnk) | Create (.lnk via COM) and parse (.lnk via custom binary parser) shortcuts natively. | π’ Stable |
| Known Folders | Retrieve true paths to Desktop, AppData, LocalAppData, etc. | π’ Stable | |
| File Lock Hunter | Identify which processes (PIDs) currently lock a specific file. | π’ Stable | |
| Disk & Partitions | Retrieve disk SN (hardware), partition GUID, and filesystem format (NTFS, etc). | π’ Stable | |
| Drive Type Query | Retrieve drive storage type (e.g., Fixed, CD-ROM, Removable, Network). | π’ Stable | |
| Disk Free Space | Query total, free, and caller-available bytes on any path/volume. | π’ Stable | |
| File Attributes | Programmatically check or toggle the "Hidden" file attribute. | π’ Stable | |
| File Owner Query | Retrieve security owner (Domain\User) details for any file/folder. | π‘ Roadmap | |
| Recycle Bin Space | Programmatically query aggregate file count and total size in the Recycle Bin. | π‘ Roadmap | |
| NTFS Alternate Streams | List, create, read, and delete hidden Alternate Data Streams (ADS) natively. | π‘ Roadmap | |
| USN Journal Change Monitor | Real-time change tracking of volume/directory file modifications and write events. | π‘ Roadmap | |
| π Network & Firewall | Advanced Networking | Retrieve adapter physical MAC addresses and Native Wi-Fi SSID/signal. | π’ Stable |
| Firewall Rules | Programmatically add, update, or delete Windows Firewall rules. | π’ Stable | |
| Port-to-PID Tracking | Find which local process (PID) owns a specific TCP/UDP port. | π’ Stable | |
| Internet Connectivity | Instant NLA-based network connectivity status check. | π’ Stable | |
| DNS Client Cache | Programmatically flush the system DNS client resolver cache. | π’ Stable | |
| Native Ping | Calculate latency via ICMP echo packets without spawning ping.exe. | π‘ Roadmap | |
| Active TCP/UDP Table | Enumerate all live network connections, local/remote endpoints, and states. | π‘ Roadmap | |
| System Proxy Settings | Query, toggle, or update system-wide dynamic Internet Explorer proxy endpoints. | π‘ Roadmap | |
| Network Routing Table | Retrieve and parse current static and dynamic routing configurations. | π‘ Roadmap | |
| π Process & Control | Process Parameters | Query any process's command line, working directory, and parent PID. | π’ Stable |
| Single Instance Lock | Global Mutex lock to ensure a single instance of an application runs. | π’ Stable | |
| Environment Sync | Modify system environment variables and broadcast to the OS instantly. | π’ Stable | |
| Job Objects | Bind child processes to a Job Object to ensure auto-kill on parent crash. | π’ Stable | |
| Process Running Check | Case-insensitive check of process activity by executable name. | π’ Stable | |
| Process Memory Metrics | Retrieve private working set, virtual size, and page fault counts for any PID. | π‘ Roadmap | |
| CPU Affinity Mask | Query or set processor core affinity masks to restrict process execution. | π‘ Roadmap | |
| Token Impersonation | Duplicate and impersonate high-privilege tokens to execute code as another user. | π‘ Roadmap | |
| π‘οΈ Security & Credentials | Digital Signature Verification | Validate executable/DLL signatures, extract leaf certs and details. | π’ Stable |
| UAC & Privilege Checks | Check if running as Admin (elevated token). | π’ Stable | |
| Privilege Elevation & Drop | Launch processes as Administrator or downgrade to standard user sessions. | π’ Stable | |
| Credential Manager | Read, write, and delete Windows Credential Manager generic credentials. | π’ Stable | |
| Access Control (ACL) | Modify DACL/ACE permissions on files/folders without boilerplate. | π’ Stable | |
| User SID | Retrieve the Security Identifier (SID) string of the current user. | π’ Stable | |
| Token Elevation Type | Retrieve token elevation context ("Default", "Full", "Limited"). | π’ Stable | |
| UAC Status | Query registry policy to check if User Account Control is enabled. | π’ Stable | |
| Adjust Privileges | Dynamically enable or disable specific LUID process privileges. | π‘ Roadmap | |
| Run as SYSTEM | Spawn a child process with local NT AUTHORITY\SYSTEM credentials. | π‘ Roadmap | |
| βοΈ Automation & Admin | Task Scheduler | Manage Windows Scheduled Tasks (Create, Read, Update, Delete, Run, Stop). | π’ Stable |
| Windows Services | Install, uninstall, start, stop, restart, and query Windows services. | π’ Stable | |
| Simplified Registry API | High-level API for registry key and value CRUD operations. | π’ Stable | |
| Event Log Management | Write to and query translated, formatted Windows Event Logs (via PowerShell/Evt). | π’ Stable | |
| Installed Applications | Scan Registry Uninstall nodes to list all installed software. | π’ Stable | |
| Active Window Tracking | Listen to active foreground window transitions and extract their titles natively. | π‘ Roadmap | |
| BitLocker Volume Status | Query encryption percentage, encryption status, and protection level of volumes. | π‘ Roadmap |
The library is logically split into four domain packages:
winutil/
βββ executable/ # Security, Credentials, Privileges, UAC, DACL/ACL
βββ file/ # Cryptography, Compression, Shortcuts, Known Folders, Disk Info, File Locks
βββ system/ # Task Scheduler, Services, Registry, Event Log, Processes, Monitor Metrics, USB, OS Info
βββ network/ # Physical MAC, Native Wi-Fi, COM Firewall Rule Management, Port Tracking
winutil is strictly committed to 100% pure native Win32/COM execution. It contains zero process spawns, zero
command-line shell assemblies (e.g., os/exec to cmd or powershell), and zero CGO dependencies. Instead of wrapping
command-line tools, winutil communicates directly with Windows Kernel, Security, and Desktop APIs.
Below is a complete quick-reference mapping of each Go function inside winutil to its equivalent standard Windows CLI
command, alongside a list of powerful Native-Only Capabilities that have no standard command-line equivalents.
| Go Function | Equivalent Windows CLI / PowerShell Command |
|---|---|
VerifySignature |
signtool verify /pa <filePath> or Get-AuthenticodeSignature |
GetLeafCertificate |
PowerShell (Get-AuthenticodeSignature <filePath>).SignerCertificate |
IsAdmin |
whoami /groups or checking net session |
RunAsAdmin |
powershell Start-Process <cmdPath> -Verb RunAs or runas |
RunAsUser |
None (Native-Only Explorer Token Duplication) |
WriteCredential |
cmdkey /generic:<target> /user:<user> /pass:<pass> |
ReadCredential |
cmdkey /list:<target> (cmdkey won't show passwords for safety) |
DeleteCredential |
cmdkey /delete:<target> |
GrantFileAccess |
icacls <filePath> /grant <identity>:(permission) |
RevokeFileAccess |
icacls <filePath> /remove <identity> |
GetCurrentUserSID |
whoami /user or (Get-WmiObject Win32_UserAccount -Filter "Name='$env:username'").SID |
GetTokenElevationType |
None (Native-Only TokenElevationType structure query) |
IsUACEnabled |
reg query HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System /v EnableLUA |
EnablePrivilege |
None (Native-Only AdjustTokenPrivileges API) [Roadmap] |
RunAsSystem |
None (Native-Only Service Token Duplication) [Roadmap] |
ImpersonateToken |
None (Native-Only ImpersonateLoggedOnUser API) [Roadmap] |
| Go Function | Equivalent Windows CLI / PowerShell Command |
|---|---|
CalculateMD5 |
certutil -hashfile <filePath> MD5 |
EncryptAES / DecryptAES |
None (No native CMD handles raw AES-CFB encryption) |
GetDiskSerialNumber |
wmic diskdrive get serialnumber or Get-PhysicalDisk |
GetPartitionGUID |
mountvol or diskpart |
GetFileSystemFormat |
fsutil fsinfo volumeinfo <drive> |
GetKnownFolderPath |
PowerShell [Environment]::GetFolderPath(...) |
GetFileLocks |
Sysinternals handle.exe -p <pid> <filePath> or openfiles |
CreateShortcut |
PowerShell (New-Object -COM WScript.Shell).CreateShortcut(...) |
ResolveShortcut |
PowerShell (New-Object -COM WScript.Shell).CreateShortcut(...).TargetPath |
ParseLnkFile |
None (Native-Only High-speed pure Go binary .lnk parser) |
Zip |
PowerShell Compress-Archive -Path <src> -DestinationPath <dest> |
Unzip |
PowerShell Expand-Archive -Path <src> -DestinationPath <dest> |
GetDriveType |
wmic diskdrive get mediatype or PowerShell Get-Volume |
GetDiskFreeSpace |
fsutil volume diskfree <path> or PowerShell Get-Volume |
IsFileHidden |
attrib <path> (checking for 'H' attribute) |
SetFileHidden |
attrib +h <path> or attrib -h <path> |
GetFileOwner |
PowerShell (Get-Acl <path>).Owner [Roadmap] |
GetRecycleBinSize |
PowerShell (Get-ChildItem -Path C:\$Recycle.Bin -Recurse -Force).Length` [Roadmap] |
GetNTFSAlternateStreams |
dir /r or PowerShell Get-Item -AlternateStream * [Roadmap] |
MonitorUSNJournal |
fsutil usn readjournal [Roadmap] |
| Go Function | Equivalent Windows CLI / PowerShell Command |
|---|---|
AddFirewallRule |
netsh advfirewall firewall add rule ... or New-NetFirewallRule |
DeleteFirewallRule |
netsh advfirewall firewall delete rule ... or Remove-NetFirewallRule |
GetPortOwner |
netstat -ano | findstr <port> |
GetMACAddress |
getmac /fo list or ipconfig /all or Get-NetAdapter |
GetWiFiInfo |
netsh wlan show interfaces |
IsInternetAvailable |
None (Native-Only high-speed NLA state check) |
FlushDNS |
ipconfig /flushdns or PowerShell Clear-DnsClientCache |
Ping |
ping or PowerShell Test-Connection [Roadmap] |
GetActiveTCPTable |
netstat -an [Roadmap] |
GetSystemProxy |
netsh winhttp show proxy [Roadmap] |
GetRoutingTable |
route print [Roadmap] |
| Go Function | Equivalent Windows CLI / PowerShell Command |
|---|---|
GetDisplayInfo |
PowerShell Get-CimInstance Win32_VideoController |
WriteEventLog |
eventcreate /ID <eventID> /L APPLICATION /SO <sourceName> ... |
ReadEventLog |
wevtutil qe <logName> ... or PowerShell Get-WinEvent |
getLogicalDrives |
fsutil fsinfo drives or PowerShell Get-PSDrive |
ExpandEnv |
echo %variable% or cmd.exe /c "echo ..." |
GetExecutablePathByPID |
wmic process where processid=<pid> get executablepath |
GetProcessCommandLine |
wmic process where processid=<pid> get commandline |
GetProcessWorkingDirectory |
None (Querying PEB CurrentDirectory of another process) |
GetProcessParentPID |
wmic process where processid=<pid> get parentprocessid |
SingleInstanceLock |
None (Native-Only Kernel Mutex Synchronization) |
SyncEnvironment |
PowerShell [Environment]::SetEnvironmentVariable(...) |
AssignProcessToJobObject |
None (Native-Only OS Job Object Sandboxing) |
SetRegistryString |
reg add "<key>" /v "<name>" /t REG_SZ /d "<val>" /f |
GetRegistryString |
reg query "<key>" /v "<name>" |
DeleteRegistryValue |
reg delete "<key>" /v "<name>" /f |
DeleteRegistryKey |
reg delete "<key>" /f |
GetTasks |
schtasks /query /fo list or PowerShell Get-ScheduledTask |
CreateTask |
schtasks /create /tn "<task>" /tr "<exe>" ... |
DeleteTask |
schtasks /delete /tn "<task>" /f |
RunTask |
schtasks /run /tn "<task>" |
StopTask |
schtasks /end /tn "<task>" |
InstallService |
sc.exe create <name> binPath= "<exePath>" |
RemoveService |
sc.exe delete <name> |
StartService |
sc.exe start <name> or net start <name> |
StopService |
sc.exe stop <name> or net stop <name> |
QueryService |
sc.exe query <name> |
GetActiveUser |
query user or qwinsta |
GetLoggedOnUsers |
qwinsta or query session |
GetLastShutdownReason |
wevtutil qe System /q:"*[System[(EventID=1074 or ...)]]" ... |
GetInstalledSoftware |
wmic product get name or querying Uninstall Registry paths |
GetStartupItemsFromRegKeys |
PowerShell query of Run keys |
GetBootItemsFromFolder |
dir "%USERPROFILE%\AppData\Roaming\...\Programs\Startup" |
ListenUSBDeviceEvents |
None (Native-Only dynamic Window message loop listening) |
GetAccurateOSVersion |
systeminfo | findstr /B /C:"OS Version" |
GetSystemUptime |
systeminfo (uptime field) or PowerShell LastBootUpTime |
LockWorkstation |
rundll32.exe user32.dll,LockWorkStation |
EmptyRecycleBin |
PowerShell Clear-RecycleBin -Force |
IsProcessRunning |
tasklist /fi "imagename eq <name>" or PowerShell Get-Process |
GetMemoryStatus |
systeminfo or PowerShell Get-CimInstance Win32_OperatingSystem |
GetCPUUsage |
wmic cpu get loadpercentage [Roadmap] |
IsWorkstationLocked |
None (Native-Only lock check API) [Roadmap] |
GetGPUInfo |
wmic path win32_VideoController get name [Roadmap] |
GetBatteryStatus |
powercfg /batteryreport or PowerShell Get-CimInstance Win32_Battery [Roadmap] |
GetBIOSInfo |
wmic bios get serialnumber or PowerShell Get-CimInstance Win32_Bios [Roadmap] |
GetProcessMemoryMetrics |
tasklist or PowerShell (Get-Process -Id <pid>).WorkingSet [Roadmap] |
SetProcessAffinity |
PowerShell (Get-Process -Id <pid>).ProcessorAffinity = <mask_value> [Roadmap] |
TrackActiveWindow |
None (Native-Only Event Hooks: SetWinEventHook) [Roadmap] |
GetBitLockerStatus |
manage-bde -status or PowerShell Get-BitLockerVolume [Roadmap] |
These features are implemented directly via low-level kernel abstractions or dynamic OS synchronization primitives, and cannot be directly mapped or simulated via standard single-line CLI commands:
ListenUSBDeviceEvents: Sets up a specialized message-only background window viaRegisterClassExWandCreateWindowExWto captureWM_DEVICECHANGEandDBT_DEVICEARRIVALWindows messages dynamically in real-time. No standard CLI can do asynchronous Windows message loop subscription.SingleInstanceLock: Leverages the Windows Kernel Mutex synchronization object viawindows.CreateMutex. It guarantees single-process orchestration across separate Windows sessions natively in memory.AssignProcessToJobObject: Leverages Windows Job Objects (CreateJobObjectW,AssignProcessToJobObject) to sandbox child processes and guarantee their immediate, clean termination when the parent process exits or crashes.RunAsUser: Re-duplicates the Shell (explorer.exe) token viaOpenProcessTokenandDuplicateTokenExto downgrade privilege from Administrator down to a standard active session user.
Ensure you have Go installed (version 1.22 or later).
git clone https://github.com/your-username/winutil.git
cd winutil
go mod tidyBelow is the standard, production-ready pattern for checking whether the current process has administrator permissions and, if not, requesting dynamic self-elevation.
package main
import (
"fmt"
"os"
"github.com/one-api/winutil/executable"
)
func main() {
// Check if running with elevated administrator privileges
if !executable.IsAdmin() {
fmt.Println("β οΈ Current process is NOT running as Administrator.")
fmt.Println("Attempting self-elevation...")
// Get the current executable path to re-launch as administrator
exePath, err := os.Executable()
if err != nil {
fmt.Printf("Failed to locate current executable: %v\n", err)
return
}
// Relaunch the executable as administrator, passing the original arguments
// The final parameter 'true' will show the newly spawned elevated console window
err = executable.RunAsAdmin(exePath, os.Args[1:], true)
if err != nil {
fmt.Printf("β Failed to elevate privileges: %v\n", err)
return
}
fmt.Println("Elevation request sent! Exiting current standard instance.")
os.Exit(0)
}
fmt.Println("π‘οΈ Success: Running with full elevated Administrator privileges!")
}This unified example retrieves the system's runtime uptime, total/free physical memory, current security identifier ( SID), and active network NLA internet status.
package main
import (
"fmt"
"github.com/one-api/winutil/executable"
"github.com/one-api/winutil/file"
"github.com/one-api/winutil/network"
"github.com/one-api/winutil/system"
)
func main() {
fmt.Println("=== WINDOWS SYSTEM TELEMETRY ===")
// 1. Check Internet Connectivity (NLA check: no slow socket ping required)
if network.IsInternetAvailable() {
fmt.Println("π Network: Internet is connected and active.")
} else {
fmt.Println("π Network: No internet connection detected.")
}
// 2. Query System Uptime
uptime, err := system.GetSystemUptime()
if err == nil {
fmt.Printf("π System Uptime: %v\n", uptime)
}
// 3. Query Memory Status
totalPhys, availPhys, _, _, err := system.GetMemoryStatus()
if err == nil {
fmt.Printf("π§ Physical Memory: %d GB Total / %d GB Available\n",
totalPhys/(1024*1024*1024), availPhys/(1024*1024*1024))
}
// 4. Query Current User SID
sid, err := executable.GetCurrentUserSID()
if err == nil {
fmt.Printf("π€ User Security SID: %s\n", sid)
}
// 5. Query Storage Capacity on Disk C:
totalSpace, freeSpace, availableSpace, err := file.GetDiskFreeSpace("C:\\")
if err == nil {
fmt.Printf("πΎ Disk C: Total: %d GB | Free: %d GB | Available: %d GB\n",
totalSpace/(1024*1024*1024), freeSpace/(1024*1024*1024), availableSpace/(1024*1024*1024))
}
}Create shortcuts via standard shell COM bindings and inspect or parse target metadata binaries utilizing our lightweight, custom, high-speed LNK parser.
package main
import (
"fmt"
"github.com/one-api/winutil/file"
)
func main() {
shortcutPath := `C:\Users\Public\Desktop\MyShortcut.lnk`
targetPath := `C:\Windows\System32\cmd.exe`
// 1. Create a native Windows shortcut (.lnk file)
err := file.CreateShortcut(shortcutPath, targetPath, "", "", 0)
if err != nil {
fmt.Printf("Failed to create shortcut: %v\n", err)
return
}
fmt.Printf("β
Shortcut created successfully at: %s\n", shortcutPath)
// 2. Parse and resolve shortcut target path using our pure Go parser
lnk, err := file.ParseLnkFile(shortcutPath)
if err != nil {
fmt.Printf("Failed to parse shortcut: %v\n", err)
return
}
fmt.Printf("π Parsed Shortcut target: %s\n", lnk.TargetPath)
if lnk.Description != "" {
fmt.Printf("π Description: %s\n", lnk.Description)
}
}Interact directly with the Windows Shell interface to silently clear cached items, followed by a local kernel call to lock the screen.
package main
import (
"fmt"
"github.com/one-api/winutil/system"
)
func main() {
// 1. Programmatically empty Recycle Bin silently (No sound, progress UI, or confirmations)
fmt.Println("Cleaning up files...")
err := system.EmptyRecycleBin()
if err != nil {
fmt.Printf("Failed to empty recycle bin: %v\n", err)
} else {
fmt.Println("ποΈ Recycle Bin emptied successfully!")
}
// 2. Lock Workstation instantly (equivalent to Win + L)
fmt.Println("Locking screen for security...")
err = system.LockWorkstation()
if err != nil {
fmt.Printf("Failed to lock desktop session: %v\n", err)
return
}
fmt.Println("π Desktop locked successfully.")
}The library is equipped with robust unit tests across all packages. You can run all test suites instantly without compiling CGO:
go test -v ./...To run the built-in diagnostic dashboard demonstrating real-time outputs of the entire library, execute:
go run main.go- License: This project is licensed under the MIT License. Copyright (c) 2026 github.com/one-api.
- Contact: hello@one-api.net or file a GitHub Issue.