0

Hey I am very new to PowerShell and found one of Ed Wilson's helpful scripts on his blog: http://blogs.technet.com/b/heyscriptingguy/archive/2012/11/12/force-a-domain-wide-update-of-group-policy-with-powershell.aspx.

I needed to customize it a little for my needs and just need some help getting the right code down.

I will just use his code because all I did was replace it with my credentials and AD info:

$cn = Get-ADComputer -filt *
$cred = Get-Credential iammred\administrator
$session = New-PSSession -cn $cn.name -cred $cred
icm -Session $session -ScriptBlock {gpupdate /force}

What I added was the next two lines to attempt to pause the script to allow the gpupdate to process then restart the computer(s):

Start-Sleep -s 120
Restart-Computer -ComputerName $cn.name

When I run the script all together it seems to just hang after I enter my credentials. My guess would be it doesn't like the way I present the Start-Sleep cmdlet because I can run the Restart-Computer cmdlet with success without Start-Sleep. The problem is it doesn't wait for gpupdate to finish so the policy doesn't get pushed. I do not get any errors when I run the script, it just hangs. I have left it running for about 10 minutes with no success.

I appreciate any help or suggestions to make this script work properly. Thanks in advance for any input.

Raf
  • 9,681
  • 1
  • 29
  • 41
Grass Ark
  • 1
  • 1
  • 3

2 Answers2

1

There's nothing wrong with your sleep invocation but it isn't the best way to go. You can wait on the job to finish with a timeout (in case the command hangs) e.g.:

$job = icm -Session $session -ScriptBlock {gpupdate /force} -AsJob
Wait-Job $job -Timeout 120
Remove-PSSession $session
Restart-Computer $cn.name
Keith Hill
  • 194,368
  • 42
  • 353
  • 369
  • Thanks a lot. Works great, thank you for the example on how to use the -AsJob cmdlet I had read about it but didn't know how to use it properly. – Grass Ark May 02 '14 at 15:17
0

@Keith Hill is right, sleep looks good. Another thing you can do is push the sleep/restart commands onto your target machines:

icm -Session $session -ScriptBlock {
    gpupdate /force; Start-Sleep -s 120; Restart-Computer -Force}
Raf
  • 9,681
  • 1
  • 29
  • 41
  • When I added this code I got an error saying that the client couldn't connect to the destination. I verified that the machine I am testing this to run on is accepting requests via winrm quickconfig. Anything else I may need to do? Thanks for the help by the way. – Grass Ark May 02 '14 at 15:23