I would like to create a script that detect and delay a shutdown on Windows 10 PC's and show a Message if a USB-Stick is plugged in at the moment of the shutdown.
My problem is that my script is not stop the shutdown. Im pretty new to Powershell. Sry for my english.
This is what i got:
[System.Reflection.Assembly]::Load("System.Management, Version=2.0.0.0,
Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a")
$Man = New-Object System.Management.ManagementClass("Win32_USBHub")
[System.Management.ManagementObjectCollection]$Devs = $Man.GetInstances()
$global:shuttingDown = $false
$sysevent = [microsoft.win32.systemevents]
Register-ObjectEvent -InputObject $sysevent -EventName "SessionEnding" -Action {$global:shuttingDown = $true; Write-Host " SessionEnding"}
Register-ObjectEvent -InputObject $sysevent -EventName "SessionEnded" -Action {$global:shuttingDown = $true; Write-Host " SessionEnded"}
do {
Start-Sleep -Seconds 1
if ($global:shuttingDown) {
& "$env:SystemRoot\System32\Shutdown.exe" -a ;
$Devs | ForEach-Object {
if($_.GetPropertyValue("Name").ToString() -eq "USB-Massenspeichergerät"){
Add-Type -AssemblyName PresentationCore,PresentationFramework
$ButtonType = [System.Windows.MessageBoxButton]::Ok
$MessageboxTitle = “USB-Stick gefunden”
$Messageboxbody = “Es wurde ein USB-Stick gefunden. Nicht vergessen mitzunehmen ;)”
$MessageIcon = [System.Windows.MessageBoxImage]::Warning
[System.Windows.MessageBox]::Show($Messageboxbody,$MessageboxTitle,$ButtonType,$messageicon)
Write-Output ""
Write-Output $_.GetPropertyValue("Name").ToString()
Write-Output ""
}
$Devs.Dispose()
$Man.Dispose()
}
}
Write-Host " Waiting for Shutdown"
} while ($true)
thx for your help
so basically, if $global:shuttingDown holds value then use a Break
do {
Start-Sleep -Seconds 1
if ($global:shuttingDown) {break}
Write-Host " Waiting for Shutdown"
} while ($true)