I run this script:
if (Copy-Item .\test.ps1 $env:SystemRoot\System32)
{
Write-Host "Done."
exit 0
}
else
{
Write-Host "Not done."
Write-Host "You must be root."
exit 1
}
When I run this script as a normal user I got the message in else
statement, because I am not root. And this is okay.
But I run this script as root I also got the message in else
statement! But file copy operation is succeded. I can't get the message in if
statement. Why?
I also check the error code and its always False
.
if (!([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator) { Write-Error 'Please run as administrator'; exit }
#Requires -RunAsAdministrator
at the start of your script, then the whole script would only run if you are admin