≡ Menu

Lock your workstation using PowerShell

One other nice thing I found with PowerShell is it’s ability of using APIs by importing DLLs. Below is one example, where user32.dll is imported and LockWorkstation Function is invoked to lock the desktop. Btw, I grabbed this script from TechNet Library

Function Lock-WorkStation {
$signature = @”
[DllImport(“user32.dll”, SetLastError = true)]
public static extern bool LockWorkStation();
“@

$LockWorkStation = Add-Type -memberDefinition $signature -name “Win32LockWorkStation” -namespace Win32Functions -passthru
$LockWorkStation::LockWorkStation() | Out-Null
}

After executing above code, invoking “Lock-WorkStation” command from PowerShell window will lock your PC.

Happy Learning..,
Sitaram Pamarthi

{ 5 comments… add one }
  • uldics February 4, 2016, 6:07 pm

    Why so long code? Can’t just the last line be executed and that’s it?

    • TechiBee February 7, 2016, 4:20 pm

      ulidics, have you tried it? It will not work because without having the c# code you cannot invoke Lockworkstation method.

  • Rich July 16, 2016, 11:52 pm

    Does not work.
    corrected code is:

    Function Lock-WorkStation {
    $signature = @’
    [DllImport(“user32.dll”, SetLastError = true)]
    public static extern bool LockWorkStation();
    ‘@
    $name = “Win32LockWorkStation”
    $LockWorkStation = Add-Type -memberDefinition $signature -name $name -namespace Win32Functions -passthru
    $LockWorkStation::LockWorkStation() | Out-Null
    }

  • OldGreyBeard January 15, 2019, 7:48 pm

    Those flipping apostrophes! Both scripts suffer from the same small but irritating ‘publication’ issue – bent quotes (“”)! If you copy and paste from the above (either version) you will get these ‘bent’ quotes and they do not work in Powershell. Powershell needs straight quotes.
    Copy and paste either solution, change the bent quotes to straight quotes and bingo the script works.

    I now have a ‘smartphone’ LockScreen button on my PC & laptop, which is what I was seeking.
    Thank you very much guys for helping me out – very much appreciated (you are ref’d in my little script).

    If you are like me, to actual see the problem, you will need you glasses when doing this.
    Have fun peoples – pass it forward!

    • Wintel Rocks February 16, 2019, 6:36 pm

      The code fixed to address the apostrophes issue. Thank you for the feedback.

Cancel reply

Leave a Comment