2013-03-01 2 views
19

나는 Powershell 스크립트를 스크립트에서 재부팅 한 후 중단했던 곳에서 계속 할 수있는 방법을 찾고있다. 예를 들어 Powershell 자동화를 통해 DC를 구축하고 PC를 TESTDC01로 이름을 바꾼 다음 재부팅해야하지만 재부팅 후에 dcpromo 등으로 이동하는 스크립트를 계속 진행하십시오.Powershell - Reboot and Continue Script

이 작업이 가능합니까?

건배!

+5

내가 스크립트에서이 작업을 수행 한 방법은 스크립트의 후 재부팅 부분을해야 매개 변수를 사용하여 스크립트를 실행 레지스트리에서하여 runonce 키를 설정하는 것입니다. – EBGreen

+0

스크립트의 계속 진행 부분을 어떻게 지정합니까? – PnP

+0

파티에 늦지 만 한 가지 방법으로'script1.ps1'을 실행하면 서버를 재부팅하기 전에 RunOnce regkey를 추가하여'script2.ps1'을 실행하지만 서버를 부팅하기 전에 서버를 완전히 부팅 할 수 있도록주의해야합니다. 스크립트를 실행하십시오. – user4317867

답변

18

Hey, Scripting Guy 시리즈의 TechNet에는 컴퓨터 이름 바꾸기 및 재부팅 후 스크립트 다시 시작에 대해 설명하는 것과 매우 유사한 상황이 있습니다. 마법은 버전 3의 일부인 새로운 워크 플로우를 사용하는 것입니다 : 워크 플로가 선언 된

workflow Rename-And-Reboot { 
    param ([string]$Name) 
    Rename-Computer -NewName $Name -Force -Passthru 
    Restart-Computer -Wait 
    Do-MoreStuff 
} 

되면 (이 변수에 할당하지 않습니다를)가 정기적를 것처럼, 당신은 그것을 호출 할 수 있습니다 cmdlet. 진짜 마법은 Restart-Computer cmdlet의 -Wait 매개 변수입니다.

Rename-And-Reboot PowerShellWorkflows 

자료 : http://blogs.technet.com/b/heyscriptingguy/archive/2013/01/23/powershell-workflows-restarting-the-computer.aspx

PowerShell은 가능한 선택, 당신은 여러 개의 작은 스크립트로 기존의 스크립트를 중단하고 시작시 실행되는 마스터 스크립트를 가질 수있다되지 나중에 V3 또는 일부 저장된 상태를 확인하는 경우 어딘가에 (파일, 레지스트리 등), 적절한 위치에서 계속하기 위해 새 스크립트를 실행하기 시작합니다. 다음과 같이하십시오 :

$state = Get-MyCoolPersistedState 
switch ($state) { 
    "Stage1" { . \Path\To\Stage1.ps1 ; break } 
    "Stage2" { . \Path\To\Stage2.ps1 ; break } 
    "Stage3" { . \Path\To\Stage3.ps1 ; break } 
    default { "Uh, something unexpected happened" } 
} 

작은 스크립트로 이동할 때 상태를 적절하게 설정해야합니다.

+2

"Restart-Computer -Wait"을 사용하려고하면 예외가 발생합니다. "로컬 컴퓨터가 다시 시작될 때까지 기다릴 수 없습니다.Wait 매개 변수가 지정되면 로컬 컴퓨터가 무시됩니다. " – BrainSlugs83

+0

기사의 재시작 가능성에 대한 실제 트릭, 특히 로컬 실행에 사용되는 경우 ... 스크립트가 다시 예약 할 작업을 만듭니다 ... 같은 작업을 수행 할 수 있습니다 자신의 스크립트, 워크 플로우가있는 것 –

5

워크 플로를 사용하여 PS 3.0을 확인하십시오. 나는 아직 그들과 함께 일한 적이 없지만 재시작으로부터 회복 할 것으로 생각된다.

10

위의 대답은 사실이지만 powershell 스크립트의 원격 실행에만 적용됩니다.

workflow Resume_Workflow 
{ 
    ..... 
    Rename-Computer -NewName some_name -Force -Passthru 
    Restart-Computer -Wait 
    # Do some stuff 
    ..... 
} 
# Create the scheduled job properties 
$options = New-ScheduledJobOption -RunElevated -ContinueIfGoingOnBattery -StartIfOnBattery 
$secpasswd = ConvertTo-SecureString "Aa123456!" -AsPlainText -Force 
$credential = New-Object System.Management.Automation.PSCredential ("WELCOME\Administrator", $secpasswd) 
$AtStartup = New-JobTrigger -AtStartup 

# Register the scheduled job 
Register-ScheduledJob -Name Resume_Workflow_Job -Trigger $AtStartup -ScriptBlock ({[System.Management.Automation.Remoting.PSSessionConfigurationData]::IsServerManager = $true; Import-Module PSWorkflow; Resume-Job -Name new_resume_workflow_job -Wait}) -ScheduledJobOption $options 
# Execute the workflow as a new job 
Resume_Workflow -AsJob -JobName new_resume_workflow_job 

참고 [System.Management.Automation.Remoting.PSSessionConfigurationData]::IsServerManager 플래그 만 워크 플로가있는 경우 true로 설정되어야한다 : 로컬 컴퓨터를 다시 시작 같은 후 는 windows web portal에 따르면, 방법은 중단 된 부분에서 로컬로 실행되는 스크립트 이력서를하는 작업은 다시 시작한 후에 로컬로 실행됩니다.

+1

사용 된 자격 증명은 무엇입니까? 귀하의 스크립트를 테스트했으며 생성 된 작업을 볼 수는 있지만 재부팅 후에 일시 중단 상태입니다 : Get-Job | Format-Table - 자동 크기 조정 – codea

0

누군가에게 도움이된다면, 서버를 재부팅 한 다음 \\server\c$이 오프라인이 될 때까지 반복하십시오. 다음으로 서버를 다시 온라인 상태로 확인하고 스크립트를 계속 진행하기 위해 While (-not(Test-path "\\$server\c$"))을 루프합니다.

이 코드는 작동하지만 있지만 확실히 개선 될 수 있습니다. 재부팅되는 서버의 CSV 로그를 생성합니다. 또한 PowerShell v2 이상에서도 작동해야합니다. 과거

Param([Parameter(Mandatory=$true)][string]$server) 
$ErrorActionPreference = "SilentlyContinue" 

Try{ 
$LastReboot = Get-EventLog -ComputerName $server -LogName system | Where-Object {$_.EventID -eq '6005'} | Select -ExpandProperty TimeGenerated | select -first 1 

(Invoke-WmiMethod -ComputerName $server -Path "Win32_Service.Name='HealthService'" -Name PauseService).ReturnValue | Out-Null 

Restart-Computer -ComputerName $server -Force 

#New loop with counter, exit script if server did not reboot. 
$max = 20;$i = 0 
DO{ 
IF($i -gt $max){ 
     $hash = @{ 
      "Server" = $server 
      "Status" = "FailedToReboot!" 
      "LastRebootTime" = "$LastReboot" 
      "CurrentRebootTime" = "FailedToReboot!" 
      } 
$newRow = New-Object PsObject -Property $hash 
$rnd = Get-Random -Minimum 5 -Maximum 40 
Start-Sleep -Seconds $rnd 
Export-Csv D:\RebootResults.csv -InputObject $newrow -Append -Force 
    "Failed to reboot $server" 
    exit}#exit script and log failed to reboot. 
    $i++ 
"Wait for server to reboot" 
    Start-Sleep -Seconds 15 
}#end DO 
While (Test-path "\\$server\c$") 

$max = 20;$i = 0 
DO{ 
IF($i -gt $max){ 
     $hash = @{ 
      "Server" = $server 
      "Status" = "FailedToComeOnline!" 
      "LastRebootTime" = "$LastReboot" 
      "CurrentRebootTime" = "FailedToReboot!" 
      } 
$newRow = New-Object PsObject -Property $hash 
$rnd = Get-Random -Minimum 5 -Maximum 40 
Start-Sleep -Seconds $rnd 
Export-Csv D:\RebootResults.csv -InputObject $newrow -Append -Force 
    "$server did not come online" 
    exit}#exit script and log failed to come online. 
    $i++ 
    "Wait for [$server] to come online" 
    Start-Sleep -Seconds 15 
}#end DO 
While (-not(Test-path "\\$server\c$")) 

$CurrentReboot = Get-EventLog -ComputerName $server -LogName system | Where-Object {$_.EventID -eq '6005'} | Select -ExpandProperty TimeGenerated | select -first 1 
    $hash = @{ 
      "Server" = $server 
      "Status" = "RebootSuccessful" 
      "LastRebootTime" = $LastReboot 
      "CurrentRebootTime" = "$CurrentReboot" 
       } 

$newRow = New-Object PsObject -Property $hash 
$rnd = Get-Random -Minimum 5 -Maximum 40 
Start-Sleep -Seconds $rnd 
Export-Csv D:\RebootResults.csv -InputObject $newrow -Append -Force 

}#End Try. 

Catch{ 
$errMsg = $_.Exception 
"Failed with $errMsg" 
}