Reputation: 167
Edited:
I have a powershell script that calls another script as elevated domain admin which returns an access denied error as follows:
Exception calling "Add" with "1" argument(s): "Access is denied.
"
At \\server\software$\!SystemSetup\PS_Scripts\LocalAdmin.ps1:16 char:5
+ $AdminGroup.Add($User.Path)
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : CatchFromBaseAdapterMethodInvokeTI
Using this method to call the script produces the error:
$Cred = Get-Credential
Start-Process -FilePath "powershell.exe" -ArgumentList "-NoProfile -NoExit -ExecutionPolicy Bypass -File $ScriptLocation" -Credential $Cred
However, If I just right click and run as administrator and enter my domain credentials to call the script (without using $Cred
) works fine:
Start-Process -FilePath "powershell.exe" -ArgumentList "-NoProfile -NoExit -ExecutionPolicy Bypass -File $ScriptLocation"
The script that I am calling looks like this:
$WindowsVersion = Get-WmiObject -Class Win32_OperatingSystem | ForEach-Object -MemberName Caption
If ($WindowsVersion -match 'Microsoft Windows 10 Enterprise') {
$DomainName = "DOMAIN.COM"
$ComputerName = (hostname)
$Username = (Get-CimInstance -ClassName Win32_ComputerSystem | Select-Object -ExpandProperty UserName).Split('\')[1]
$AdminGroup = [ADSI]"WinNT://$ComputerName/Administrators,group"
$User = [ADSI]"WinNT://$DomainName/$UserName,user"
$AdminGroup.Add($User.Path)
Write-Host "$Username added to Administrators"
} Elseif ($WindowsVersion -match 'Microsoft Windows 7 Enterprise' -or $WindowsVersion -match 'Microsoft Windows 7 Professional') {
$DomainName = "DOMAIN.COM"
$ComputerName = (hostname)
$Username = (Get-WmiObject -Class Win32_ComputerSystem | Select-Object -ExpandProperty UserName).Split('\')[1]
$AdminGroup = [ADSI]"WinNT://$ComputerName/Administrators,group"
$User = [ADSI]"WinNT://$DomainName/$UserName,user"
$AdminGroup.Add($User.Path)
Write-Host "$Username added to Administrators"
} Else {
Write-Host "Could not determine OS version"
}
I cannot figure out why storing my domain admin credentials in $Cred and passing it to the script gives me the access denied once it gets to $AdminGroup.Add($User.Path)
Upvotes: 0
Views: 762
Reputation: 394
Going off of TheIncorrigible1's comment, You can add this to your script at the beginning to check if it is running as admin. If it is not, it will relaunch as admin
If (-Not ([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole] "Administrator")) {
$Arguments = "& '" + $MyInvocation.MyCommand.Definition + "'"
Start-Process Powershell -Verb RunAs -ArgumentList $Arguments
Break
}
Then depending on your UAC setting you may be prompted to allow it to run with elevated privilege.
Upvotes: 1