Shutdown PCs Idle Script

This PowerShell script, written by Richard Easton, is designed to shut down PCs that have no one logged in. The script uses Active Directory to generate a list of computers and then shuts them down using the Stop-Computer cmdlet.

Prerequisites


The Script

This section of the script sets up the necessary variables and paths:


#set Active Directory Base search area.
#$ousearchbase = "OU=[yourPC'sOU],DC=[domain],DC=org"

#Set domain admin credentials (get-credentials prompts of password input)
#$username / $Password sends them to the PS script, use this for scheduled tasks

#base paths
$basepath = "c:\shutdown"
$logpath = "$basepath\logs"
#replace anything in [] with your information.
$username = "domain\[dadmin account]"
#replace anything in [] with your information.
$password = convertto-securestring "[password]" -AsPlainText -Force
$cred = new-object -typename System.Management.Automation.PSCredential -argumentlist $username, $password

How It Works

Getting the List of PCs from Active Directory

This section of the script uses the Get-ADComputer cmdlet to generate a list of computers in the specified Active Directory base search area:


#generate the list of PC from the AD.
Get-ADComputer -Filter * -SearchBase $ousearchbase -properties Name | Select-Object name | Sort-Object name | Out-File -FilePath $file -NoClobber

Removing Blank Lines from the File

This section of the script removes any blank lines from the file:


#Remove any blank lines from the file.
(Get-Content $file) | Where-Object {$_.trim() -ne "" } | set-content $file

Shutting Down PCs

This section of the script reads through the list of PCs and shuts them down using the Stop-Computer cmdlet:


#read through the list for each pc name and run the stop-computer cmdlet (will shutdown any computer that doesn't have anyone logged in.
foreach ($name in $null -ne $content) {
  if ($name.Trim() -eq "name") {
  } elseif ($name.Trim() -eq "----" ) {
  } Else {
    #stop the $name of the computer.
    $pc = $name.Trim()
    Stop-Computer -ComputerName $pc -asjob -ErrorAction SilentlyContinue -Authentication Default -Credential $cred -whatif
    write-host $pc
    $ct = Get-Date -DisplayHint DateTime
    $result = "$ct $pc Stop-Computer sent"
    out-file -FilePath $log -Append -Encoding string -InputObject $result -NoClobber
  }
}

Usage Examples

This script can be used to automate the process of shutting down PCs that have no one logged in. Simply modify the script to include your own Active Directory base search area and credentials, then schedule it to run at a time that suits you.

Conclusion

This PowerShell script provides an effective way to shut down PCs that have no one logged in. By modifying the script to fit your specific needs, you can automate this process and free up resources on your network.