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
Comments on this entry are closed.
Why so long code? Can’t just the last line be executed and that’s it?
ulidics, have you tried it? It will not work because without having the c# code you cannot invoke Lockworkstation method.
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
}
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!
The code fixed to address the apostrophes issue. Thank you for the feedback.