I'm facing quite weird error while trying to run a proccess with elevated privileges. I wrote a PS function that gets a command and user credentials and it should execute the command under those credentials. It's like Start-Process cmdlet but I wrote the function because I need to capture the output of the executed command. The point is that is supposed that when I set the property Verb
of the ProcessStartInfo
to "runas" that is supposed to launch the UAC.
My function is here:
Function Grant-ElevatedPrivileges {
[cmdletBinding()]
param(
[Parameter(Mandatory=$true)]
[String]$command
,
[Parameter(Mandatory=$true)]
[System.Management.Automation.PSCredential]$credential
)
Write-Verbose -msg "EXECUTING COMMAND WITH ELEVATED PRIVILEGES: $command"
# Write-Host "$command"
$result = @{'result' = $false; 'output' = $false; 'error' = $false};
$psi = New-object System.Diagnostics.ProcessStartInfo
#$psi.CreateNoWindow = $true
$psi.UseShellExecute = $false
$psi.RedirectStandardOutput = $true
$psi.RedirectStandardError = $true
$psi.FileName = 'C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe'
$psi.Arguments = @"
-ExecutionPolicy Bypass -noprofile $command
"@
$psi.UserName = $credential.GetNetworkCredential().UserName
if ($credential.GetNetworkCredential().Domain -ne "") { $psi.Domain = $credential.GetNetworkCredential().Domain }
$psi.Password = $credential.Password
$psi.Verb = "runas"
$process = New-Object System.Diagnostics.Process
$process.StartInfo = $psi
try {
$result['result'] = $process.Start()
$process.WaitForExit()
$result['output'] = $process.StandardOutput.ReadToEnd()
$result['error'] = $process.StandardError.ReadToEnd()
} catch [System.ComponentModel.Win32Exception] {
if (($_.Exeption.NativeErrorCode) -eq 1326) {
Write-Verbose "USUARIO O CONTRASEÑA INCORRECTA"
$result['error'] = "BADUSER"
} else {
$result['error'] = $_.Exception.Message
}
$result['result'] = $false
} catch {
$result['result'] = $false
$result['error'] = Write-Error $_.Exception.Message
}
if ($result['error'] -ne '') {
Write-Verbose $result['error']
$result['result'] = $false
}
$result
}
I check the behaviour I mention by invoking the function:
Grant-ElevatedPrivileges -command "([Security.Principal.WindowsPrincipal] [Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole] 'Administrator')" -credential $creds -Verbose
That should return True if the command where executed under admin privileges...
Any ideas about what I'm missing?
Thanks for your advices or ideas ;)