簡體   English   中英

檢查是否需要重新啟動並在重新啟動后繼續執行 Powershell 腳本?

[英]Check if a reboot is needed and continue Powershell script after reboot?

這個問題之前被問過幾次,但我在其中任何一個中都找不到解決方案。

基本上,如果需要,我需要腳本在重新啟動后繼續。 它將檢查一些注冊表項並確定是否需要重新啟動機器。

我嘗試以各種方式使用“工作流程”,但無法成功運行。

這是我的代碼的粗略描述:

function (check-if-computer-needs-a-reboot){
    if(this and that)

    try{

    return $true
    }
    catch{}

    return $false
    }

if(check-if-computer-needs-a-reboot = $true){

Write-Host "The machine is rebooting..."
Restart-Computer -Wait -Force
Write-Host "The machine was successfully rebooted"

}

    else 

    {
    Write-Host "No pending reboot" 
    }

希望 Stack-overflow 的向導可以提供幫助。

任何幫助將不勝感激!!!

要在重新啟動后繼續執行某些操作,您需要向 Runonce 注冊表項添加一個值,以指定重新啟動后要執行的操作。

將您的腳本分成兩部分(Preboot 和 Postboot)。 將以下內容放在 Preboot.ps1 的末尾:

if(check-if-computer-needs-a-reboot){
  REG ADD "HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Runonce" /V "Postboot" /d "\"%~dpPostboot.ps1\" MyParameters" /t REG_SZ /f
  Write-Host "The machine is rebooting..."
  Restart-Computer -Wait -Force
}
# Fall through if reboot was not needed, so continue with part 2
Write-Host "No pending reboot... continuing"
"%~dpPostboot.ps1"

筆記:

  1. 我從 .bat 文件中復制了它。 在 .bat 文件中,“%~dp0”表示“當前腳本運行的驅動器和路徑”。 Powershell 中的語法可能會有些不同。

  2. 雖然 Powershell 可以運行其他程序,例如 REG.EXE,但 Powershell 有自己的內置 HKLM:PSdrive。 這應該比使用 REG.EXE 更有效。 我把它留給你做轉換。

  3. 在您的代碼中,您測試一個布爾值是否“等於”$True。 除非該值不是真正的布爾值並且可能不是True 或 False,否則這種比較是不必要的。 如上所示,只需測試布爾值本身。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM