使用Get-Credentials调用另一个Powershell脚本-奇数结果

时间:2018-10-23 13:22:24

标签: powershell

编辑:

我有一个Powershell脚本,它以提升的域管理员身份调用另一个脚本,该脚本返回如下所示的拒绝访问错误:

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

使用此方法调用脚本会产生错误:

$Cred = Get-Credential

Start-Process -FilePath "powershell.exe" -ArgumentList "-NoProfile -NoExit -ExecutionPolicy Bypass -File $ScriptLocation" -Credential $Cred

但是,如果我只是右键单击并以管理员身份运行,然后输入域凭据来调用脚本(不使用$Cred),效果很好:

Start-Process -FilePath "powershell.exe" -ArgumentList "-NoProfile -NoExit -ExecutionPolicy Bypass -File $ScriptLocation"

我正在调用的脚本如下:

$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"
}

我无法弄清楚为什么将我的域管理员凭据存储在$ Cred中并将其传递给脚本后,一旦访问$AdminGroup.Add($User.Path),我的访问将被拒绝

1 个答案:

答案 0 :(得分:1)

关闭TheIncorrigible1的注释,您可以在开始时将其添加到脚本中,以检查其是否以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
}

然后,根据您的UAC设置,可能会提示您允许它以提升的特权运行。