Link to home
Start Free TrialLog in
Avatar of ajwellman
ajwellman

asked on

Powershell -whatif question

I am trying to force logoff remote computers via a powershell script.  I would like to use the -whatif to make sure it is doing what I want but don't know hoe to implement it.
My powershell contains:
foreach ($_ in get-content servers.txt) {(gwmi win32_operatingsystem -ComputerName $_).Win32Shutdown(4)}
How  can it use the -whatif condition with this stafement?

Thanks for any help.

Art W.
Avatar of Qlemo
Qlemo
Flag of Germany image

You can't use -WhatIf with WMI directly, so you have to implement it yourself. But that can get quite complex, if done correctly.
And please don't use $_ as a foreach variable - it is a predefined var standing for "the current object" in a loop.

How do you want the command to be used? In a script without defining functions (your own "cmdlets")? If so, we would have to allow for a commandline parameter for the script, for example:
$whatif = $args[0] -eq '-whatif'
Get-Content Servers.txt | % {
  $OS = gwmi Win32_OperatingSystem -Computername $_
  if ($whatif) {
    write-host "WhatIf: Shutting down $_"
  } else {
    $OS.Win32Shutdown(4)
  } 
}

Open in new window

You would call the script with e.g.
 .\remoteshutdown.ps1 -whatif
from powershell get-help stop-computer -examples
$s = get-content servers.txt
$c = get-credential domain01\admin01  ## needs a domain Admin credential
stop-computer -computername $s -force -throttlelimit 10 -credential $c -WhatIf

Open in new window

ASKER CERTIFIED SOLUTION
Avatar of Qlemo
Qlemo
Flag of Germany image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of ajwellman
ajwellman

ASKER

This worked great.  Since I wanted to force a logoff rather than a reboot, I couldn't find a cmdlet to do that.
Thank you all who responded.  It is a great help.
Art W