examples/04-Picker.ps1
|
# 04 - Picker: show PowerShell data (processes) in a sortable list and return the user's choice. if (-not (Get-Command Show-NativeWebView -ErrorAction Ignore)) { Import-Module NativeWebView -ErrorAction Stop } $Rows = Get-Process | Sort-Object WorkingSet64 -Descending | Select-Object -First 15 | ForEach-Object { @{ id = $_.Id; name = $_.ProcessName; mb = [math]::Round($_.WorkingSet64 / 1MB) } } $Html = @' <!doctype html> <html><head><style> body { font-family: Verdana, 'Segoe UI', Arial, sans-serif; font-size: 12px; color: #454545; padding: 16px; background: #F9F9F9; } table { border-collapse: collapse; width: 100%; background: white; } th, td { padding: 6px 10px; text-align: left; border-bottom: 1px solid #CCCCCC; } th { background: #154363; color: white; cursor: pointer; } tr.row:hover { background: #e8eff6; color: #095495; cursor: pointer; } </style></head> <body> <p>Click a process to pick it.</p> <table><thead><tr><th data-key="name">Name</th><th data-key="id">Id</th><th data-key="mb">MB</th></tr></thead><tbody id="rows"></tbody></table> <script> var rows = []; function draw() { var body = document.getElementById("rows"); body.textContent = ""; rows.forEach(function (r) { var tr = document.createElement("tr"); tr.className = "row"; [r.name, r.id, r.mb].forEach(function (v) { var td = document.createElement("td"); td.textContent = v; tr.appendChild(td); }); tr.onclick = function () { kHost.send({ action: "pick", id: r.id, name: r.name }); }; body.appendChild(tr); }); } document.querySelectorAll("th").forEach(function (th) { th.onclick = function () { var k = th.dataset.key; rows.sort(function (a, b) { return a[k] > b[k] ? 1 : -1; }); draw(); }; }); kHost.on(function (m) { if (m.action === "rows") { rows = m.rows; draw(); } }); kHost.send({ action: "ready" }); </script> </body></html> '@ $Picked = @{} Show-NativeWebView -Html $Html -Title "Pick a process" -Width 520 -Height 560 -OnMessage { param($Message, $Window) $Data = $Message | ConvertFrom-Json if ($Data.action -eq "ready") { $Window.Send("rows", @{ rows = $Rows }) } if ($Data.action -eq "pick") { $Picked.Id = $Data.id; $Picked.Name = $Data.name; $Window.Close() } }.GetNewClosure() if ($Picked.Count -gt 0) { Write-Host ("Picked " + $Picked.Name + " (" + $Picked.Id + ")") } |