Remotely Lock & shutdown computers using PowerShell

PowerShell takes the functionality of batch scripts to the next level.

the following needs to be run on each computer if using a workgroup setup. or changed in your AD security policy (to make it permanent – which isn’t advisable without signing the script)

https://www.howtogeek.com/117192/how-to-run-powershell-commands-on-remote-computers/

Enable-PSRemoting
Set-executionpolicy unrestricted
Set-Item WSMan:\localhost\Client\TrustedHosts -Value "192.168.1.250" -Force
Get-Item WSMan:\localhost\Client\TrustedHosts
Restart-Service WinRM

the above assumes that your server IP is 192.168.1.250, changed as appropriate

Now to the actual shutdown code:

Function Get-MyCredential {
  param(
		[string]$username,
		[string]$password
	)

	$secStr = new-object -typename System.Security.SecureString
	$password.ToCharArray() | ForEach-Object {$secStr.AppendChar($_)}
	return new-object -typename System.Management.Automation.PSCredential -argumentlist $username,$secStr
}

Function Lock-Machine {
	param(
		$machineName
	)

	& winrm set winrm/config/client `@`{TrustedHosts = `"$machineName`"`}
	Invoke-Command -ComputerName $machineName -ScriptBlock { tsdiscon.exe console } -Credential (Get-MyCredential User Pa$$W0rd)
}

Function Hibernate-Machine {
	param(
		$machineName
	)

	& winrm set winrm/config/client `@`{TrustedHosts = `"$machineName`"`}
	Invoke-Command -ComputerName $machineName -ScriptBlock { &"$env:SystemRoot\System32\rundll32.exe" powrprof.dll,SetSuspendState Hibernate } -Credential (Get-MyCredential Administrator password)	
}
Lock-Machine "192.168.1.84"
#Lock-Workstation "NameOfTheComputer" (Get-Credential)
Stop-Computer -ComputerName 192.168.1.85 -Force -Credential (Get-MyCredential User Pa$$W0rd)