Filter
Exclude
Time range
-
Near
【photo_manager_eng_v3_copy.ahk】 全構文 ⇒ #Requires AutoHotkey v2.0 ; エクスプローラーがアクティブな場合のみ、ショートカットキーを有効化 #HotIf WinActive("ahk_class CabinetWClass") ; 【無変換 + テンキー9】: デスクトップのexeをコピーせず、現在のパスを「引数」として直接起動する vk1D & Numpad9:: { currentDir := GetActiveExplorerPath() if (currentDir == "") { MsgBox("エクスプローラーのパスを取得できませんでした。", "エラー", "IconX") return } exePath := "C:\Users\kawa\Desktop\photo_manager_eng_v4.exe" if !FileExist(exePath) { MsgBox("デスクトップにプログラムが見つかりません:`n" exePath, "エラー", "IconX") return } try { ; ★ exeの後ろにスペースを空けてフォルダパスを引き渡します Run('"' exePath '" "' currentDir '"') ToolTip("プログラムを起動しました`n対象: " currentDir) SetTimer(() => ToolTip(), -2000) } catch as err { MsgBox("プログラムの起動に失敗しました。`nエラー: " err.Message, "エラー", "IconX") } } ; 【無変換 + テンキー5】: selectedフォルダ内の指定画像を、Zドライブに新規作成したフォルダへコピー & 自動リネーム & selectedフォルダ削除 vk1D & Numpad5:: { ; 1. 現在アクティブなエクスプローラーのフォルダパスを取得 currentDir := GetActiveExplorerPath() if (currentDir == "") { MsgBox("エクスプローラーのパスを取得できませんでした。", "エラー", "IconX") return } ; 2. 現在のフォルダ内に「selected」フォルダが存在するか確認 selectedDir := currentDir "\selected" if !DirExist(selectedDir) { MsgBox("「selected」フォルダーが現在の場所に存在しません。`n処理を中断します。", "エラー", "IconX") return } ; 3. Zドライブ(保存先の基本パス)が存在するか確認 baseDestDir := "Z:\Saishin\sokorireki\photo\episode\rebel" if !DirExist(baseDestDir) { MsgBox("保存先ベースフォルダーが見つかりません。`nネットワーク接続(Zドライブ)を確認してください。", "エラー", "IconX") return } ; 4. 小窓を開いてフォルダ名の入力を促す ib := InputBox("作成するフォルダー名を入力してください。", "新規フォルダーの作成とコピー", "w350 h130") if (ib.Result == "Cancel" || ib.Value == "") { return ; キャンセルまたは空欄の場合は処理を終了 } newFolderName := ib.Value ; 5. 入力されたフォルダ名で、Zドライブ内にフォルダを新規作成 destDir := baseDestDir "\" newFolderName if !DirExist(destDir) { try { DirCreate(destDir) } catch as err { MsgBox("フォルダーの作成に失敗しました:`n" destDir "`nエラー: " err.Message, "エラー", "IconX") return } } ; 6. 「selected」内の「jpg」「heic」「png」ファイルをコピー extensions := ["jpg", "heic", "png"] copiedCount := 0 try { for ext in extensions { Loop Files, selectedDir "\*." ext { FileCopy(A_LoopFilePath, destDir "\", 1) ; 1 は同名ファイルを上書き copiedCount } } ; 7. コピー完了後、PowerShellを呼び出して自動リネームを実行 if (copiedCount > 0) { ; コピー中であることを一旦通知 ToolTip("コピー中... リネーム処理を準備しています。") ; 動的にリネーム用のPowerShellスクリプトを生成 RunRenamePowerShell(destDir, newFolderName) ; ★ 【後片付け】コピー元フォルダ内の「selected」フォルダを中身ごと強制削除する ★ if DirExist(selectedDir) { try { DirDelete(selectedDir, 1) ; 1を指定することで、フォルダ内が空でなくても丸ごと削除します } } ; 完了通知 ToolTip("コピー & リネーム完了!`n(元フォルダのselectedは自動削除しました)`n保存先: " destDir) SetTimer(() => ToolTip(), -4000) ; 4秒後に通知を消去 } else { MsgBox("「selected」フォルダー内に、コピー対象の画像(jpg, heic, png)が見つかりませんでした。", "お知らせ", "Iconi") } } catch as err { MsgBox("コピー・リネーム処理中にエラーが発生しました。`nエラー: " err.Message, "エラー", "IconX") } } #HotIf ; --- 以下、処理を行う関数群 --- ; コピーしたファイルを撮影日時(または更新日時)順に並び替え、入力フォルダ名で連番リネームする関数 RunRenamePowerShell(folderPath, newName) { psTemplate := " ( $folder = '[[FOLDER_PATH]]' $list = @() Get-ChildItem -LiteralPath $folder -File | ForEach-Object { $f = $_.FullName $date = $null $out = & 'C:\Tools\exiftool.exe' -DateTimeOriginal -s3 $f 2>$null if ($out) { try { $date = [DateTime]::ParseExact($out.Trim(), 'yyyy:MM:dd HH:mm:ss', $null) } catch {} } if (-not $date) { $date = $_.LastWriteTime } $list = ,[PSCustomObject]@{ Path = $f; Date = $date; Ext = $_.Extension } } $tempList = @() foreach ($item in $list) { $tempName = [System.IO.Path]::GetRandomFileName() $item.Ext $tempPath = Join-Path $folder $tempName Rename-Item -LiteralPath $item.Path -NewName $tempName -Force $tempList = [PSCustomObject]@{ TempPath = $tempPath; Date = $item.Date; Ext = $item.Ext } } $i = 1 $tempList | Sort-Object Date | ForEach-Object { Rename-Item -LiteralPath $_.TempPath -NewName ('[[NEW_NAME]]_' $i $_.Ext) -Force $i } )" psCode := StrReplace(psTemplate, "[[FOLDER_PATH]]", folderPath) psCode := StrReplace(psCode, "[[NEW_NAME]]", newName) tempPsFile := A_Temp "\ahk_rename_temp.ps1" if FileExist(tempPsFile) { FileDelete(tempPsFile) } FileAppend(psCode, tempPsFile, "UTF-8-RAW") RunWait("powershell -NoProfile -ExecutionPolicy Bypass -File `"" tempPsFile "`"", , "Hide") if FileExist(tempPsFile) { FileDelete(tempPsFile) } } ; アクティブなエクスプローラーのパスをCOMオブジェクト経由で取得する関数 GetActiveExplorerPath() { activeHwnd := WinExist("A") try { for window in ComObject("Shell.Application").Windows { if (window.hwnd == activeHwnd) { return window.Document.Folder.Self.Path } } } return "" }

1
2
173
@echo off setlocal EnableDelayedExpansion if "%~1"=="" ( echo ファイルがドロップされていません。 pause exit /b ) :: 一時リストファイルの作成 set "listfile=%temp%\file_list_%random%.txt" if exist "!listfile!" del "!listfile!" :: ドラッグされたファイルのパスを一時ファイルに1行ずつ書き出し :loop if "%~1"=="" goto run_ps echo %~1>> "!listfile!" shift goto loop :run_ps :: PowerShellで処理を実行 powershell -NoProfile -ExecutionPolicy Bypass -Command ^ "$list = @();" ^ "Get-Content '!listfile!' | ForEach-Object {" ^ " $f = $_.Trim();" ^ " if ($f -and (Test-Path -LiteralPath $f -PathType Leaf)) {" ^ " $date = $null;" ^ " $out = & 'C:\Tools\exiftool.exe' -DateTimeOriginal -s3 $f 2>$null;" ^ " if ($out) {" ^ " try { $date = [DateTime]::ParseExact($out.Trim(), 'yyyy:MM:dd HH:mm:ss', $null) } catch {}" ^ " }" ^ " if (-not $date) { $date = (Get-Item -LiteralPath $f).LastWriteTime }" ^ " $list = ,[PSCustomObject]@{ Path = $f; Date = $date; Ext = [System.IO.Path]::GetExtension($f) }" ^ " }" ^ "};" ^ "$tempList = @();" ^ "foreach ($item in $list) {" ^ " $tempName = [System.IO.Path]::GetRandomFileName() $item.Ext;" ^ " $tempPath = Join-Path (Split-Path $item.Path) $tempName;" ^ " Rename-Item -LiteralPath $item.Path -NewName $tempName -Force;" ^ " $tempList = [PSCustomObject]@{ TempPath = $tempPath; Date = $item.Date; Ext = $item.Ext }" ^ "};" ^ "$i = 1;" ^ "$tempList | Sort-Object Date | ForEach-Object {" ^ " Rename-Item -LiteralPath $_.TempPath -NewName ('20260329_' $i $_.Ext) -Force;" ^ " $i ;" ^ "}" :: 一時ファイルの削除(後片付け) if exist "!listfile!" del "!listfile!" echo 完了 pause

40
Downloading a disk from @Azure & wanted to keep an eye on its progress so wrote a 1 liner [int]$sleepSeconds = 60 ; [uint64]$oldlength = 0 ; while(1) { $newLength = (ls C:\blah.vhd).Length ; [pscustomobject]@{ Date = get-date ; LengthGB = $newLength / 1GB ; 'MB/s' = if( $oldlength -gt 0 ) { (($newLength - $oldLength) / 1MB) / $sleepSeconds }} ; sleep $sleepSeconds ; $oldlength = $newLength}
2
8
1,218
Replying to @RyoMa_0923
オブジェクトなのはいいとしても、やたらと「PSCustomObject」なのがタチが悪い。見た目だけ文字列で実際には諸々を含んだオブジェクトで、必要な要素だけ取り出さないと式評価が成り立たない、なんてのがしょっちゅうある。 learn.microsoft.com/ja-jp/po…
2
25
3,060
:::editorial::entre::nous::: Se avizora el final de un largo reinado imperial y colonial, en un nuevo mundo multipolar enfocado hacia el oriente, pero en si, en su conjunto bipolar al final. Posiblemente sea el error más fatal que un presidente Estadounidense haya cometido esta arriesgando el 30% del ejercito norteamericano, poniendo en riesgo su capacidad operativa de respuesta. El puesto del mandatario podría estar en vilo si procede con el ataque. Los norteamericanos no van a entender como su flota naval queda superada la fotografía seria de 8 columnas el Abraham Lincoln hundiéndose tipo tetanic. *se ejemplifica en los videos del siguiente link: x.com/alfonso/status/2024508… así como sus bases militares en el medio oriente y ahi los ánimos se caldearán. China y Rusia están en intenso correo aero militar llevan semana, juntos superan por mucho la flota naval norteamericana, su fuerza aérea y la capacidad de ataque mediante misiles hipersónicos. Ambos países se han esforzado en hace saber que ellos respaldan a Iran. No sera un conflicto de unos días serán semanas sino meses si es que se lleva a cabo. Flotas navales Posiblemente sea el error más fatal que un presidente Estadounidense haya cometido esta arriesgando el 30% del ejercito norteamericano, poneindo en riesgo su capacidad operativa de respuesta. [pscustomobject]@{ Country = 'USA' Fleet = 'US Navy' Ships = 293 Metric = 'Battle force ships' AsOf = '2025-10-01' } [pscustomobject]@{ Country = 'CHN' Fleet = 'PLAN (China)' Ships = '370 ' Metric = 'Battle force ships & submarines' AsOf = 'mid-2024' } [pscustomobject]@{ Country = 'RUS' Fleet = 'Russian Navy' Ships = 301 Metric = '222 warships 79 submarines' AsOf = '2025-06' } [pscustomobject]@{ Country = 'IRN' Fleet = 'IRIN (Iran regular navy)' Ships = '100 ' Metric = 'vessels (ships & submarines)' AsOf = '2025-06' } )
1
13
16
794
And this version copies the output straight into your clipboard as a Markdown table 👇 ------- powershell -NoProfile -Command "$depth=2; $root=(Get-Location).Path; $data=Get-ChildItem -Directory -Recurse -Depth $depth | % { $s=(Get-ChildItem -LiteralPath $_.FullName -File -Recurse -Force -EA SilentlyContinue | Measure Length -Sum).Sum; $rel=$_.FullName.Substring($root.Length).TrimStart('\'); [pscustomobject]@{Path=$rel; SizeGB=($s/1GB)} } | Sort-Object SizeGB -Desc; $md=@(); $md =('| Size (GB) | Path |'); $md =('|---:|---|'); foreach($r in $data){ $p=($r.Path -replace '\|','\|'); $md =('| {0:N1} | {1} |' -f $r.SizeGB, $p) }; $md -join \"`n\" | Set-Clipboard" -----
2
258
All good, morning ☀️ Today’s a backup day for me. Used to rely on different cloud drives, but after OneDrive corrupted a few archives with zero recovery options… I kinda lost trust. Now it’s old-school backups again. External drives, manual checks, no surprises. By the way - here’s a handy Windows terminal command to list folders and subfolders (recursion depth = 2) with their size: powershell -NoProfile -Command "$depth=2; Get-ChildItem -Directory -Recurse -Depth $depth | % { $s=(Get-ChildItem -LiteralPath $_.FullName -File -Recurse -Force -EA SilentlyContinue | Measure Length -Sum).Sum; [pscustomobject]@{Path=$_.FullName; SizeGB=[math]::Round($s/1GB,1)} } | Sort SizeGB -Desc | ft -Auto" Super useful to quickly see what’s actually eating your disk before backing things up.
4
10
310
# Load detections and catalog (run as Admin) $detections = Get-MpThreatDetection $catalog = Get-MpThreatCatalog # Create a hashtable for O(1) lookups by ThreatID $threatLookup = @{} foreach ($threat in $catalog) { $threatLookup[$threat.ThreatID] = $threat } # Merge and display (or export) $detections | ForEach-Object { $threat = $threatLookup[$_.ThreatID] [PSCustomObject]@{ ThreatID = $_.ThreatID ThreatName = if ($threat) { $threat.ThreatName } else { "Unknown" } SeverityID = if ($threat) { $threat.SeverityID } else { $null } CategoryID = if ($threat) { $threat.CategoryID } else { $null } DetectionTime = $_.DetectionTime ActionSuccess = $_.ActionSuccess } } | Format-Table -AutoSize
1
14
1,409
Programmieren (Skripten) mit KI Teil 2 Ich hatte ja neulich ein total verunglücktes Beispiel präsentiert. Hier nun ein weiteres, diesmal mit Googles Genimi, welches wesentlich besser lief. Problem war - ich wollte rausfinden, auf welchen von und 100 Servern eine bestimmte VHDX gemountet ist. Ich kann da entweder jeden Server einzeln öffnen und nachschauen aber meine exorbitante Faulheit steht dem entgegen oder ich schicke einen AZUBI drüber aber der wird mich dafür nicht mögen. Außerdem muß ich da immer wieder mal nachschauen. Also folgender mehrstufiger Prompt: Schreib mir ein powershell script das alle windows server die mit "AVD-M" im Namenbeginnen abfragt und die verbundenenfestplattennamen pro server in eine csv datei schreibt. Output kann ich leider nicht posten, denn es sind zu viele Cashtags drin, die X nicht akzeptiert. Aber schonmal nicht schlecht, gar nicht schlecht aber ich sehe, get-ciminstance alleine wird nicht zum Ziel führen, also: Verwende zusätzlich zum get-ciminstancebefehl auch diese befehle um es abzurufen. Output schon fast perfekt aber ich konkretisiere: Frage im script bitte alle server mit den Namen AVD-W11-M-0 -99 ab und verzichte auf eine AD-Abfrage. # Definiert den Pfad für die Ausgabe-CSV-Datei $outputPath = "C:\temp\ServerFestplatten.csv" # Erstellt eine Liste von Servernamen von AVD-W11-M-0 bis AVD-W11-M-99 $serverList = 0..37 | ForEach-Object { "AVD-W11-M-$_ " } # Erstellt ein leeres Array, um die Ergebnisse zu speichern $report = @() # Durchläuft jeden Server in der definierten Liste foreach ($serverName in $serverList) { $cimSession = $null Write-Verbose "Frage Festplatten für Server ab: $serverName" # Prüft, ob der Server erreichbar ist if (-not (Test-Connection -ComputerName $serverName -Count 1 -Quiet)) { Write-Warning "Server $serverName ist nicht erreichbar. " $report = [PSCustomObject]@{ 'Server' = $serverName 'Festplattenmodell' = 'Nicht erreichbar' 'Anzahl Partitionen' = 'N/A' 'Volumebezeichnungen' = 'N/A' } continue } try { # Erstellt eine CIM-Sitzung für effiziente Remote-Befehle $cimSession = New-CimSession -ComputerName $serverName -ErrorAction Stop # Ruft alle Festplatten auf dem Remote-Server ab $disks = Get-Disk -CimSession $cimSession if ($null -eq $disks) { $report = [PSCustomObject]@{ 'Server' = $serverName 'Festplattenmodell' = 'Keine Festplatten gefunden' 'Anzahl Partitionen' = 0 } 'Volumebezeichnungen' '' = continue } # Durchläuft jede Festplatte foreach ($disk in $disks) { # Ruft die zugehörigen Partitionen und Volumes ab, um die Bezeichnungen zu ex $volumeLabels = $disk | Get-Partition -CimSession $cimSession | Get-Volume -C $volumeLabelsString = $volumeLabels -join ' ' , $object = [PSCustomObject]@{ 'Server' 'Festplattenmodell' 'Anzahl Partitionen' 'Volumebezeichnungen' = $serverName = $disk.Model = $disk.NumberOfPartitions = $volumeLabelsString } $report = $object } } catch { Write-Warning "Fehler beim Abrufen der Festplatteninformationen von $serverName. $report = [PSCustomObject]@{ 'Server' = $serverName 'Festplattenmodell' = "Fehler bei der Abfrage" 'Anzahl Partitionen' = 'N/A' 'Volumebezeichnungen' = 'N/A' } } finally { # Bereinigt die CIM-Sitzung if ($cimSession) { Remove-CimSession -CimSession $cimSession } } } # Exportiert den Bericht in eine CSV-Datei if ($report.Count -gt 0) { $report | Export-Csv -Path $outputPath -NoTypeInformation -Encoding UTF8 Write-Host "Bericht wurde erfolgreich nach $outputPath exportiert. " } else { Write-Host "Keine Server zur Verarbeitung gefunden. " } Wow 😳 perfekt - ein überzeugendes Ergebnis. Das Script läuft einwandfrei uns es kommt eine wunderschöne CSV mit genau den Infos, die ich wollte. Hätte ich das, daß Array komplett selbst programmieren müssen, wäre ich lange, viele Stunden dran gesessen. So war das ein Job von nichtmal 10 Minuten. Aber: Ohne Kenntnisse in PowerShell-Scripting geht es nicht. Man muß die KI kontrollieren und den Output bewerten und korrigieren können. Wenn das jedoch gegeben ist, ist der Produktiovitätsgewinn enorm.
6
2
52
2,005
Replying to @gedanken_lost
ich habe Claude Sonnet 4.5 (kostenpflichtig) die gleiche Aufgabe gestellt. Claude ist bekannt, daß es für Progrmmieraufgaben gute Ergebnisse erzielen soll und tatsächlich: # Alle installierten Language Packs abfragen $languages = Get-WinUserLanguageList # Alle Features je Sprache abfragen und Tabelle ausgeben $languages | ForEach-Object {     $lang = $_.LanguageTag     $features = Get-WinLanguageFeature -Language $lang     $result = [PSCustomObject]@{         Language         = $lang         BasicTyping      = ($features | Where-Object { $_.Feature -eq 'Basic Typing' }).State         Handwriting      = ($features | Where-Object { $_.Feature -eq 'Handwriting' }).State         OCR              = ($features | Where-Object { $_.Feature -eq 'OCR' }).State         Speech           = ($features | Where-Object { $_.Feature -eq 'Speech' }).State         TextToSpeech     = ($features | Where-Object { $_.Feature -eq 'TextToSpeech' }).State     }     $result } | Format-Table -AutoSize Deutlich kürzer aber immer noch schlicht Bullshit. Man könnte sagen, die KI schwurbelt. Man kann KI einsetzen. IMHO aber nur dann, wenn man in der Lage ist, die Fehler zu erkennen und wie hier zu erkennen, daß der komplette Code Müll ist. Man kann KI als Assistenzsystem verwenden. Ähnlich wie im Auto der Spurhalteassistent. Aber manche gehen davon aus, KI könne (bald) selbständig coden. Das wird so nicht geschehen. Der Zwang der KI sinnlosen Output zu generieren ist zu groß.😎
3
1
8
858
Aus der beliebten Reihe - "KI macht alles besser, KI wird uns alle ersetzen". Heute: Programmierer braucht man nicht mehr! Ich dachte mir, fragst doch mal ne tolle KI, wie die das löst. Microsoft und einfach jeder drückt dir ja eine KI bei jeder Gelegenheit aufs Auge. 🙂 Aufgabenstellung im Krafmuschelausführungsplan - für IT-Eingeweihte - PowerShell-Script 😉: Anzeige aller installierte Sprachen und deren Sprach-Features (Windows 11). Die Lösung der KI (ChatGPT Pro): $langs = Get-InstalledLanguage # Mögliche Feature-Typen, die Windows als "Capabilities" führt $featureTypes = @(     'Language.Basic',     'Language.Handwriting',     'Language.OCR',     'Language.Speech',     'Language.TextToSpeech' ) # Für schnellere Abfragen einmalig alle Capabilities laden $caps = Get-WindowsCapability -Online | Where-Object { $_.Name -like 'Language.*~~~*~0.0.1.0' } $result = foreach ($l in $langs) {     $tag = $l.LanguageTag  # z.B. de-DE # Mappe jede Feature-Art auf Installed/NotPresent     $featureStatus = @{}     foreach ($ft in $featureTypes) {         $cap = $caps | Where-Object { $_.Name -like "$ft~~~$tag~0.0.1.0" } | Select-Object -First 1         $featureStatus[$ft] = if ($cap) { $cap.State } else { 'NotPresent' }     } [pscustomobject]@{         LanguageTag     = $tag         DisplayName     = $l.DisplayName         BasicTyping     = $featureStatus['Language.Basic']         Handwriting     = $featureStatus['Language.Handwriting']         OCR             = $featureStatus['Language.OCR']         Speech          = $featureStatus['Language.Speech']         TextToSpeech    = $featureStatus['Language.TextToSpeech']     } } # Kompakte Ausgabe $result | Sort-Object LanguageTag | Format-Table -AutoSize Sieht doch total geil aus, nicht? 😃 Beeindruckend, was KI heute alles so kann. 😳👍 So richtig zum angeben. Blöd nur: es ist beeindruckender völliger unglaublicher Bullshit. Nicht mehr. Einfach nur nicht funktionierender Schrott. Nun wollt ihr von mir die Lösung? Die ist simpel: "Get-InstalledLanguage" 😉 Jep, das wars. Mehr braucht es nicht. Ein kleiner Einzeiler - nichtmal, nur ein kleiner Befehl. 😄 Aber wartet, daß war's noch nicht. Der eigentliche Witz kommt noch. Die KI hat den korrekten Befehl sogar gefunden. Schaut mal Zeile 1: $langs = Get-InstalledLanguage Völlig korrekt. Nur der ganze beeindruckend aussehende Schrott darunter, macht die Ausgabe, die daraufhin folgt, kaputt, liefert nicht das Ergebnis. KI versteht nichts. Meiner Meinung nach eine Blase, die bald platzt. 😎
43
17
246
23,001
5 Nov 2025
Quick'n'dirty free disk space monitoring including recording to csv while(1) { $d = [pscustomobject]@{ Date = Get-Date ; 'FreeSpace (GB)' = [int]((get-volume -DriveLetter d).SizeRemaining / 1GB ) } ; $d; export-csv -NoTypeInformation -Append c:\temp\d.free.space.csv -InputObject $d ; start-sleep 60 }
1
1
5
731
23 Oct 2025
Replying to @NetworkChuck
PowerShell FTW: $SSIDs = ( netsh wlan show profiles|select -skip 9 ) | % { ($_ -split ': ')[-1] } $SSIDs | %{ [pscustomobject]@{ SSID = $_ ; Password = $( if( $m = ( netsh wlan show profile name="$_" key=clear |sls "key content\s*:\s*(.*)$")) { $m.matches.Groups[-1].value } ) }} *I didn't use AI 😊
2
6
3,265
25 Sep 2025
here is a powershell script to check which @SierraChart server has best latency for you. save it as "ps1" and run. ``` $hostsList = @( "ds3.sierracharts.com", "ds4.sierracharts.com", "ds4-2.sierracharts.com", "ds12.sierracharts.com", "ds12-2.sierracharts.com", "ds13.sierracharts.com", "ds13-2.sierracharts.com", "ds14.sierracharts.com", "ds22.sierracharts.com", "ds23.sierracharts.com", "ds23-2.sierracharts.com", "ds24.sierracharts.com", "ds26.sierracharts.com", "ds26-2.sierracharts.com", "ds27.sierracharts.com", "ds28.sierracharts.com", "ds28-2.sierracharts.com", "ds30.sierracharts.com", "ds30-2.sierracharts.com", "ds31.sierracharts.com", "ds32.sierracharts.com", "ds32-2.sierracharts.com", "ds40.sierracharts.com" ) Write-Host "Starting ping jobs for each host..." -ForegroundColor Cyan $jobsList = foreach ($singleHost in $hostsList) { Write-Host "Starting job for $singleHost" -ForegroundColor Yellow Start-Job -ScriptBlock { param ($targetHost) $output = ping.exe -n 10 -w 1000 $targetHost 2>&1 # Extract all individual times (e.g. "time=34ms") $times = @() foreach ($line in $output) { if ($line -match "time[=<]\s*(\d )ms") { $times = [int]$matches[1] } } if ($times.Count -gt 0) { $min = ($times | Measure-Object -Minimum).Minimum $max = ($times | Measure-Object -Maximum).Maximum $avg = ($times | Measure-Object -Average).Average $jitter = $max - $min $status = if ($times.Count -eq 10) { "OK" } else { "Partial ($($times.Count)/10)" } } elseif ($output -match "Reply from") { $min = $max = $avg = $jitter = "-" $status = "Partial (No valid times)" } else { $min = $max = $avg = $jitter = "-" $status = "Failed" } [PSCustomObject]@{ Target = $targetHost MinLatencyMs = $min MaxLatencyMs = $max AverageLatencyMs= if ($avg -is [double]) { [math]::Round($avg, 2) } else { $avg } JitterMs = $jitter Status = $status } } -ArgumentList $singleHost } Write-Host "Waiting for all jobs to complete..." -ForegroundColor Cyan $resultsList = $jobsList | Wait-Job | ForEach-Object { Receive-Job $_ } Write-Host "Results received, displaying sorted table:" -ForegroundColor Green # Select only needed properties to hide RunspaceId $resultsList | Select-Object Target, MinLatencyMs, MaxLatencyMs, AverageLatencyMs, JitterMs, Status | Sort-Object Status, AverageLatencyMs | Format-Table -AutoSize Read-Host -Prompt "Press Enter to exit" ```
5
365
📚 PowerShell Workbook - Day 6 - Single and Double Quotes 🔺 When I started writing my first PowerShell scripts, quotes were one of the things that confused me the most. Yet, it only takes a few minutes to understand how PowerShell interprets them. 🔺 Double quotes " " Variables are replaced by their value. Expressions within $() are also evaluated. Examples: $i = 5 "The value is $i" Result: The value is 5 And with $() to evaluate an expression directly: $i = 5 "The value multiplied by 2 is $($i * 2)" Result: The value multiplied by 2 is 10 Example with an object and its property: $user = [PSCustomObject]@{ Name = 'Jean' ; Role = 'Admin' } "The user is $($user.Name)" Result: The user is Jean 🔺 Single quotes ' ' The content is taken literally: variables and expressions are not evaluated. $i = 5 'The value is $i' gives The value is $i 🔺 When you want to write a block of text over multiple lines, you can use what is called a "Here-String": Example with variable expansion: @" The counter is $i The double value is $($i * 2) User: $($user.Name) "@ Example without variable expansion: @' Block of text '@ 💡 To close a Here-String in PowerShell, "@ or '@ must be placed alone on a line, at the very beginning, without space or tab before or after. 🔺 To include double quotes in a string, you can: - Either double the double quotes inside a string of the same type "He said ""Hello""" - Or use the other type of quotes 'He said "Hello"' 🔺 Use the backtick ` to prevent the interpretation of a special character. Example: "`$i is $i" Gives: $i is 5 🔺 I long thought that using single quotes when there was no variable was more efficient, as PowerShell wouldn’t need to check if it should interpret something. But after testing, double quotes turn out to be slightly faster… even without a variable. If you look at my scripts, you will see that I often mix single and double quotes depending on the context. It was while preparing this post that I discovered this performance difference, proof that we can always learn, refine our practices, and improve, even on concepts we thought we had mastered. 📒 Did you miss a day or want to review the previous ones? Head to 👉 l.perezbastien.com/25summer-…
1
3
269
25 Jul 2025
That's the thing. You have to pipe the output to my Get-MgGraphAllPages function which handles the pagination plus converts the result to pscustomobject 👍 powershellgallery.com/packag… or use batching which handles it too plus paralelization doitpshway.com/how-to-use-mi… 🚀
2
2
41
9 Jul 2025
PowerShell 1 liner to show what processes have what version of a given (@Azure) module loaded ps | ForEach-Object { if( $m = $_.Modules | Where { $_.PSObject -and $_.FileName -match '\\az\.accounts\\([^\\] )\\' } -EA 0 ) { [pscustomobject]@{ Process = $_.Name ; PID = $_.Id ; Version = $matches[1]|select -unique } } }
2
2
5
536
あるディレクトリで、なにが容量食ってるのか調べるスクリプト(PowerShell) Get-ChildItem -Directory | Where-Object {-not $_.LinkType} | ForEach-Object { $size = (Get-ChildItem $_.FullName -Recurse -File | Where-Object {-not $_.LinkType} | Measure-Object -Property Length -Sum).Sum [PSCustomObject]@{ Folder = $_.Name SizeGB = [math]::Round($size / 1GB, 2) SizeMB = [math]::Round($size / 1MB, 2) } } | Sort-Object SizeGB -Descending
1
6
552