Search code examples
powershellpowershell-2.0powershell-3.0powershell-4.0

Restart machine using powershell script


I am running the below code but the restart is not working. My intention was to run restart command parallelly on all remote machines at once.

$YourFile = gc "machinelst.txt"
$username = "user1"
$password = "pass1"
$secpw = ConvertTo-SecureString $password -AsPlainText -Force
$cred  = New-Object Management.Automation.PSCredential ($username, $secpw)

foreach ($computer in $YourFile)
{
    Invoke-Command -ComputerName $computer -credential $cred -ErrorAction Stop -ScriptBlock { Restart-Computer -ComputerName $computer -Force } -AsJob
     
} 

enter image description here


Solution

  • try this (you will can add -asjob if it's work) :

    $username = "yourdomain\user1"
    $password = ConvertTo-SecureString "pass1" -AsPlainText -Force
    $cred = new-object -typename System.Management.Automation.PSCredential -argumentlist $username, $password
    
    get-content "machinelst.txt" | %{
    Restart-Computer -ComputerName $_ -Authentication default -Credential $cred
    
    }
    

    if you want use job, you can do it :

    $listjob=@()
    
    get-content "machinelst.txt" | %{
    $listjob+=Restart-Computer -ComputerName $_ -Authentication default -Credential $cred -AsJob
    }
    
    $listjob | Wait-Job -Timeout 30
    
    $listjob | %{
    
        if ($_.State -eq 'Failed' )
        {
          Receive-Job -Job $_ -Keep
        }
       
    }