none
Register-ScheduledJob - Access Denied RRS feed

  • Question

  • I know this is the PowerShell forum, and my question is a mix of SCCM / MDT / PowerShell.  But this seemed like the best place to start, since this is script is a little advanced for some SCCM admin's PowerShell knoledge.

    I have a script I used successfully when manually configuring SCCM Distribution Points to configure the DP PKI cert.

    When I tried to use that script inside a MDT Task Sequence it failed, because it was running everything as 'NT Authority\SYSTEM' and it's dealing with the local cert store and enrolling certificates where a user account is needed.

    I found this script to run it as a scheduled job, and it worked perfectly in MDT.
    https://www.powershellgallery.com/packages/Invoke-CommandAs/2.1/Content/Invoke-CommandAs.psm1

    Well now I'm trying to move this all in to a SCCM MDT Task Sequence and it's failing:

    VERBOSE: Register-ScheduledJob: 15469dac-56b5-4a54-9570-9607b866c1d5
    PS>TerminatingError(Register-ScheduledJob): "The running command stopped because the preference variable "ErrorActionPreference" or common parameter is set to Stop: An access denied error occurred when registering scheduled job definition 15469dac-56b5-4a54-9570-9607b866c1d5.  Try running Windows PowerShell with elevated user rights; that is, Run As Administrator."
    >> TerminatingError(Register-ScheduledJob): "An access denied error occurred when registering scheduled job definition 15469dac-56b5-4a54-9570-9607b866c1d5.  Try running Windows PowerShell with elevated user rights; that is, Run As Administrator."
    >> TerminatingError(Register-ScheduledJob): "An access denied error occurred when registering scheduled job definition 15469dac-56b5-4a54-9570-9607b866c1d5.  Try running Windows PowerShell with elevated user rights; that is, Run As Administrator."
    >> TerminatingError(Register-ScheduledJob): "An access denied error occurred when registering scheduled job definition 15469dac-56b5-4a54-9570-9607b866c1d5.  Try running Windows PowerShell with elevated user rights; that is, Run As Administrator."
    >> TerminatingError(Register-ScheduledJob): "An access denied error occurred when registering scheduled job definition 15469dac-56b5-4a54-9570-9607b866c1d5.  Try running Windows PowerShell with elevated user rights; that is, Run As Administrator."
    An access denied error occurred when registering scheduled job definition 15469dac-56b5-4a54-9570-9607b866c1d5.  Try running Windows PowerShell with elevated user rights; that is, Run As Administrator.
    Register-ScheduledJob : An access denied error occurred when registering scheduled job definition
    15469dac-56b5-4a54-9570-9607b866c1d5.  Try running Windows PowerShell with elevated user rights; that is, Run As
    Administrator.

    Since this is SCCM, I realized that Group Policy wasn't being fetched until the end of the Task Sequence, so I added commands before the reboot preceding this step in the TS to add the AD groups that contain the service account used in this script, but that didn't seem to make any difference.

    After the TS errors out, I [F8] and started PowerShell, confirmed it was an Administrator prompt, confirmed my service account was in the local Administrators group, and ran the script from there.  Same error.

    So I'm trying to figure out what else I can debug / log to find out where this script / Register-ScheduledJob command may be going wrong, something specific to a SCCM Task Sequence. 

    • $Credential not being built correctly?
    • Needs an actual active profile session (like MDT runs while logged onto the .\Administrator desktop)?

    Open to any suggestions on what I can check.

    Thanks!


    There's no place like 127.0.0.1


    • Edited by Matt5150 Wednesday, January 9, 2019 12:38 AM Typo
    • Moved by jrv Wednesday, January 9, 2019 12:59 AM Better forum
    Wednesday, January 9, 2019 12:37 AM

Answers

All replies

  • Sorry but this forum is not for custom changes to scripts you have found on the Internet.  Ask the author of the script for help.

    "Access Denied" means that you don't have permission to do what you are trying to do.  This is a basic Windows error that any tech knows.  Check your permission.

    Post SCCM related issues to the SCCM forum.


    \_(ツ)_/

    Wednesday, January 9, 2019 12:58 AM
  • I have moved this to the CCM PowerShell forum for best assistance.


    \_(ツ)_/

    Wednesday, January 9, 2019 12:59 AM
  • I have moved this to the CCM PowerShell forum for best assistance.


    \_(ツ)_/

    Thanks, didn't even know this particular forum existed. ;)

    There's no place like 127.0.0.1

    Wednesday, January 9, 2019 1:25 AM
  • Your error says you are not elevated. You mention you run as Administrator. Administrator can still be elevated.
    From your F8, run this:

    $UserPrincipal=New-Object System.Security.Principal.WindowsPrincipal([System.Security.Principal.WindowsIdentity]::GetCurrent())
    $UserPrincipal.IsInRole([System.Security.Principal.WindowsBuiltInRole]::Administrator)

    If you are indeed elevated, it will return True.

    If not already in it, consider adding logging to your script and include the above code to verify that the script is indeed running in an elevated context.

    • Marked as answer by Matt5150 Monday, February 11, 2019 6:21 PM
    • Unmarked as answer by Matt5150 Monday, February 11, 2019 6:21 PM
    Wednesday, January 9, 2019 11:31 AM
  • Your error says you are not elevated. You mention you run as Administrator. Administrator can still be elevated.
    From your F8, run this:

    $UserPrincipal=New-Object System.Security.Principal.WindowsPrincipal([System.Security.Principal.WindowsIdentity]::GetCurrent())
    $UserPrincipal.IsInRole([System.Security.Principal.WindowsBuiltInRole]::Administrator)

    If you are indeed elevated, it will return True.

    If not already in it, consider adding logging to your script and include the above code to verify that the script is indeed running in an elevated context.

    It does come back as "True".

    There's no place like 127.0.0.1

    Wednesday, January 9, 2019 11:53 PM
  • The script you referred to takes a number of parameters, some relating to running it on remote machines and using either a specified user account, local system account and one that specifically tells it to execute elevated.

    How are you calling your script from MDT ? 
    Does the script only affect the system on which the Task Sequence runs or are you trying to get it to do something on yet another system ? 
    Thursday, January 10, 2019 8:16 AM
  • All local.  Here is the sanitized version of the script I'm running:

    function Invoke-CommandAs {
    
    # Removed remarked text to save space here
    
        #Requires -Version 3
    
        [cmdletbinding(DefaultParameterSetName="None")]
        Param(
        
            [Parameter(Mandatory = $false, ParameterSetName = 'ComputerName', Position=0)]
            [string[]]$ComputerName,
        
            [Parameter(Mandatory = $false, ParameterSetName = 'ComputerName')]
            [System.Management.Automation.PSCredential]$Credential,
        
            [Parameter(Mandatory = $false, ParameterSetName = 'PSSession', Position=0)]
            [System.Management.Automation.Runspaces.PSSession[]]$Session,
        
            [Parameter(Mandatory = $true,  Position=1)]
            [ScriptBlock]$ScriptBlock,
        
            [Parameter(Mandatory = $false)]
            [Object[]]$ArgumentList,
        
            [System.Management.Automation.Runspaces.AuthenticationMechanism]$Authentication,
    
            [System.Management.Automation.PSCredential]$As,
        
            [Parameter(Mandatory = $false)]
            [Switch]$AsSystem,
    
            [Parameter(Mandatory = $false)]
            [String]$AsGMSA,
        
            [Parameter(Mandatory = $false)]
            [Switch]$RunElevated,
        
            [Parameter(Mandatory = $false, ParameterSetName = 'ComputerName')]
            [Parameter(Mandatory = $false, ParameterSetName = 'PSSession')]
            [Switch]$AsJob,
        
            [Parameter(Mandatory = $false, ParameterSetName = 'ComputerName')]
            [Parameter(Mandatory = $false, ParameterSetName = 'PSSession')]
            [String]$JobName,
        
            [Parameter(Mandatory = $false, ParameterSetName = 'ComputerName')]
            [Parameter(Mandatory = $false, ParameterSetName = 'PSSession')]
            [Int]$ThrottleLimit
        
        )
    
        function Invoke-ScheduledTask {
    
            #Requires -Version 3
            
            [cmdletbinding()]
            Param(
            [Parameter(Mandatory = $true)][ScriptBlock]$ScriptBlock,
            [Parameter(Mandatory = $false)][Object[]]$ArgumentList,
            [Parameter(Mandatory = $false)][System.Management.Automation.PSCredential]$Credential,
            [Parameter(Mandatory = $false)][Switch]$AsSystem,
            [Parameter(Mandatory = $false)][String]$AsGMSA,
            [Parameter(Mandatory = $false)][Switch]$RunElevated
    
            )
    
            Begin { 
            
                $JobName = [guid]::NewGuid().Guid 
    
            }
        
            Process {
            
                Try {
                    
                    # DEBUG START
                    Write-Warning "DEBUG START"
                    $UserPrincipal=New-Object System.Security.Principal.WindowsPrincipal([System.Security.Principal.WindowsIdentity]::GetCurrent())
                    $AdminTEST = $UserPrincipal.IsInRole([System.Security.Principal.WindowsBuiltInRole]::Administrator)
                    Write-Verbose "IsElevated? = $AdminTEST"
                    Write-Warning "DEBUG END"
                    # DEBUG END
                    
                    $JobName = [guid]::NewGuid().guid
    
                    Write-Verbose "Register-ScheduledJob: $JobName"
                    $JobParameters = @{ }
                    If ($ScriptBlock)  { $JobParameters['ScriptBlock']  = $ScriptBlock }
                    If ($ArgumentList) { $JobParameters['ArgumentList'] = $ArgumentList }
                    If ($Credential)   { $JobParameters['Credential'] = $Credential }
                    If ($RunElevated)  { $JobParameters['ScheduledJobOption'] = New-ScheduledJobOption -RunElevated }
    
                    # Little bit of inception to get $Using variables to work.
                    # Collect $Using:variables, Rename and set new variables inside the job.
    
                    # Inspired by Boe Prox, and his https://github.com/proxb/PoshRSJob module
                    #      and by Warren Framem and his https://github.com/RamblingCookieMonster/Invoke-Parallel module
    
                    $JobParameters['Using'] = @()
                    $UsingVariables = $ScriptBlock.ast.FindAll({$args[0] -is [System.Management.Automation.Language.UsingExpressionAst]},$True)
                    If ($UsingVariables) {
    
                        $ScriptText = $ScriptBlock.Ast.Extent.Text
                        $ScriptOffSet = $ScriptBlock.Ast.Extent.StartOffset
                        ForEach ($SubExpression in ($UsingVariables.SubExpression | Sort { $_.Extent.StartOffset } -Descending)) {
    
                            $Name = '__using_{0}' -f (([Guid]::NewGuid().guid) -Replace '-')
                            $Expression = $SubExpression.Extent.Text.Replace('$Using:','$').Replace('${Using:','${'); 
                            $Value = [System.Management.Automation.PSSerializer]::Serialize((Invoke-Expression $Expression))
                            $JobParameters['Using'] += [PSCustomObject]@{ Name = $Name; Value = $Value } 
                            $ScriptText = $ScriptText.Substring(0, ($SubExpression.Extent.StartOffSet - $ScriptOffSet)) + "`${Using:$Name}" + $ScriptText.Substring(($SubExpression.Extent.EndOffset - $ScriptOffSet))
    
                        }
                        $JobParameters['ScriptBlock'] = [ScriptBlock]::Create($ScriptText.TrimStart("{").TrimEnd("}"))
                    }
    
                    $JobScriptBlock = [ScriptBlock]::Create(@"
    
                        Param(`$Parameters)
    
                        `$JobParameters = @{}
                        If (`$Parameters.ScriptBlock)  { `$JobParameters['ScriptBlock']  = [ScriptBlock]::Create(`$Parameters.ScriptBlock) }
                        If (`$Parameters.ArgumentList) { `$JobParameters['ArgumentList'] = `$Parameters.ArgumentList }
        
                        If (`$Parameters.Using) { 
                            `$Parameters.Using | % { Set-Variable -Name `$_.Name -Value ([System.Management.Automation.PSSerializer]::Deserialize(`$_.Value)) }
                            Start-Job @JobParameters | Receive-Job -Wait -AutoRemoveJob
                        } Else {
                            Invoke-Command @JobParameters
                        }
    
    "@)
    
                    $ScheduledJob = Register-ScheduledJob -Name $JobName -ScriptBlock $JobScriptBlock -ArgumentList $JobParameters -ErrorAction Stop
    
                    If (($AsSystem) -or ($AsGMSA)) {
    
                        # Use ScheduledTask to execute the ScheduledJob to execute with the desired credentials.
    
                        If (Get-Command 'Register-ScheduledTask' -ErrorAction SilentlyContinue) {
    
                            # For Windows 8 / Server 2012 and Newer
    
                            Write-Verbose "Register-ScheduledTask"
                            $TaskParameters = @{ TaskName = $ScheduledJob.Name }
                            $TaskParameters['Action'] = New-ScheduledTaskAction -Execute $ScheduledJob.PSExecutionPath -Argument $ScheduledJob.PSExecutionArgs
                            $RunLevel = If ($RunElevated) { 'Highest' } Else { 'Limited' }
                            If ($AsSystem) {
                                $TaskParameters['Principal'] = New-ScheduledTaskPrincipal -UserID "NT AUTHORITY\SYSTEM" -LogonType ServiceAccount -RunLevel $RunLevel
                            } ElseIf ($AsGMSA) {
                                $TaskParameters['Principal'] = New-ScheduledTaskPrincipal -UserID $AsGMSA -LogonType Password -RunLevel $RunLevel
                            }
                            $ScheduledTask = Register-ScheduledTask @TaskParameters -ErrorAction Stop
    
                            Write-Verbose "Start-ScheduledTask"
                            $CimJob = $ScheduledTask | Start-ScheduledTask -AsJob -ErrorAction Stop
                            $CimJob | Wait-Job | Remove-Job -Force -Confirm:$False
    
                        } Else {
     
                            # For Windows 7 / Server 2008 R2
    
                            Write-Verbose "Register-ScheduledTask"
                            $ScheduleService = New-Object -ComObject("Schedule.Service")
                            $ScheduleService.Connect()
                            $ScheduleTaskFolder = $ScheduleService.GetFolder("\")
                            $TaskDefinition = $ScheduleService.NewTask(0) 
                            $TaskAction = $TaskDefinition.Actions.Create(0)
                            $TaskAction.Path = $ScheduledJob.PSExecutionPath
                            $TaskAction.Arguments = $ScheduledJob.PSExecutionArgs
                            If ($AsSystem) {
                                $ScheduledTask = $ScheduleTaskFolder.RegisterTaskDefinition($ScheduledJob.Name,$TaskDefinition,6,"System",$null,5)
                            } ElseIf ($AsGMSA) {
                                # Needs to be tested
                                $ScheduledTask = $ScheduleTaskFolder.RegisterTaskDefinition($ScheduledJob.Name,$TaskDefinition,6,$AsGMSA,$null,5)
                            }
    
                            Write-Verbose "Start-ScheduledTask"
                            $ScheduledTask.Run($null) | Out-Null
    
                        }
    
                        Write-Verbose "Get-ScheduledJob"
                        While (-Not($Job = Get-Job -Name $ScheduledJob.Name -ErrorAction SilentlyContinue)) { Start-Sleep -Milliseconds 200 }
    
                        Write-Verbose "Receive-ScheduledJob"
                        $Job | Wait-Job | Receive-Job -Wait -AutoRemoveJob
    
                    } Else {
    
                        # It no other credentials where provided, execute the ScheduledJob as is.
                        Write-Verbose "Start-ScheduledTask"
                        $Job = $ScheduledJob.StartJob()
    
                        Write-Verbose "Receive-ScheduledJob"
                        $Job  | Receive-Job -Wait -AutoRemoveJob
        
                    }
    
                } Catch { Throw $_ }
    
            }
    
            End {
    
                If ($ScheduledTask) {
                    Write-Verbose "Unregister ScheduledTask"
                    #Try { $ScheduledTask | Unregister-ScheduledTask -Confirm:$False } Catch {}
                }
    
                If ($ScheduledJob) {
                    Write-Verbose "Unregister ScheduledJob"
                    # For Windows 8 / Server 2012 and Newer
                    Try { $ScheduledJob | Unregister-ScheduledJob -Force -Confirm:$False | Out-Null } Catch {} 
                    # For Windows 7 / Server 2008 R2
                    Try { $ScheduleTaskFolder.DeleteTask($ScheduledJob.Name, 0) | Out-Null } Catch {}
                }
    
            }
    
        }
    
        If ($ComputerName -or $Session) { 
    
            # Collect the functions to bring with us in the remote session:
            $_Function = ${Function:Invoke-ScheduledTask}.Ast.Extent.Text
    
            # Collect the $Using variables to load in the remote session:
            $_Using = @()
            $UsingVariables = $ScriptBlock.ast.FindAll({$args[0] -is [System.Management.Automation.Language.UsingExpressionAst]},$True)
            If ($UsingVariables) {
    
                $ScriptText = $ScriptBlock.Ast.Extent.Text
                $ScriptOffSet = $ScriptBlock.Ast.Extent.StartOffset
                ForEach ($SubExpression in ($UsingVariables.SubExpression | Sort { $_.Extent.StartOffset } -Descending)) {
    
                    $Name = '__using_{0}' -f (([Guid]::NewGuid().guid) -Replace '-')
                    $Expression = $SubExpression.Extent.Text.Replace('$Using:','$').Replace('${Using:','${'); 
                    $Value = [System.Management.Automation.PSSerializer]::Serialize((Invoke-Expression $Expression))
                    $_Using += [PSCustomObject]@{ Name = $Name; Value = $Value } 
                    $ScriptText = $ScriptText.Substring(0, ($SubExpression.Extent.StartOffSet - $ScriptOffSet)) + "`${Using:$Name}" + $ScriptText.Substring(($SubExpression.Extent.EndOffset - $ScriptOffSet))
    
                }
                $ScriptBlock = [ScriptBlock]::Create($ScriptText.TrimStart("{").TrimEnd("}"))
            }
    
            $Parameters = @{}
            If ($ComputerName)   { $Parameters['ComputerName']   = $ComputerName   }
            If ($Credential)     { $Parameters['Credential']     = $Credential     }
            If ($Session)        { $Parameters['Session']        = $Session        }
            If ($Authentication) { $Parameters['Authentication'] = $Authentication }
            If ($AsJob)          { $Parameters['AsJob']          = $AsJob          }
            If ($JobName)        { $Parameters['JobName']        = $JobName        }
            If ($ThrottleLimit)  { $Parameters['ThrottleLimit']  = $ThrottleLimit  }
    
            Invoke-Command @Parameters -ScriptBlock {
    
                # Create the functions/variables we packed up with us previously:
                $Using:_Function | % { Invoke-Expression $_ }
                $Using:_Using | % { Set-Variable -Name $_.Name -Value ([System.Management.Automation.PSSerializer]::Deserialize($_.Value)) }
    
                $Parameters = @{}
                If ($Using:ScriptBlock)  { $Parameters['ScriptBlock']  = [ScriptBlock]::Create($Using:ScriptBlock) }
                If ($Using:ArgumentList) { $Parameters['ArgumentList'] = $Using:ArgumentList                       }
                If ($Using:As)           { $Parameters['Credential']   = $Using:As                                 }
                If ($Using:AsSystem)     { $Parameters['AsSystem']     = $True                                     }
                If ($Using:AsGMSA)       { $Parameters['AsGMSA']       = $Using:AsGMSA                             }
                If ($Using:RunElevated)  { $Parameters['RunElevated']  = $True                                     }
    
                Invoke-ScheduledTask @Parameters
    
            }
    
        } Else {
    
            $Parameters = @{}
            If ($ScriptBlock)  { $Parameters['ScriptBlock']  = $ScriptBlock  }
            If ($ArgumentList) { $Parameters['ArgumentList'] = $ArgumentList                        }
            If ($As)           { $Parameters['Credential']   = $As                                  }
            If ($AsSystem)     { $Parameters['AsSystem']     = $True                                }
            If ($AsGMSA)       { $Parameters['AsGMSA']       = $AsGMSA                              }
            If ($RunElevated)  { $Parameters['RunElevated']  = $True                                }
    
            Invoke-ScheduledTask @Parameters
    
        }
            
    }
    
    New-Item -ItemType Directory -Force -Path C:\Temp | Out-Null
    $OutFile = "C:\Temp\SCCM-DP-CertScript.log"
    $Transcript = "C:\Temp\SCCM-DP-CertScript-Transcript.log"
    If (Test-Path $Transcript) {
        Remove-Item $Transcript -Force
    }
    Start-Transcript -Path $Transcript -Force
    $VerbosePreference = 'Continue'
    
    Invoke-CommandAs -ScriptBlock { 
        ## Defined VARs
    
        $strUser = "Domain\ServiceAccount"
        $strPassword = ConvertTo-SecureString "password" -AsPlainText -Force
        $Credentials = New-Object System.Management.Automation.PsCredential $strUser,
        $strPassword
        #$GetCreds = Get-Credential
        $WebCertTemp = "ConfigMgr Web Server Certificate"                    # Name of Certificate Template Autoenrolled for SCCM IIS Servers
        $iisSite = "Default Web Site"
        $CertStore = Get-ChildItem cert:\LocalMachine\My                     # "cert:\$ServerName\My" ????
        $DPCertTemp = "ConfigMgrClientDistributionPointCertificate"          # Name of Certificate Template created for SCCM DPs
        $DPCertTempDisp = "ConfigMgr Client Distribution Point Certificate"  # Name of Certificate Template created for SCCM DPs
        if (!$env:userdnsdomain) {  
            $ServerName = "$env:computername.domain.com"                       
        } Else {
            $ServerName = "$env:computername.$env:userdnsdomain" 
        }
                    
        $CertStorePath = "cert:\LocalMachine\My"                     # "cert:\$ServerName\My" ????
        $CertStore = Get-ChildItem cert:\LocalMachine\My                     # "cert:\$ServerName\My" ????
        $CertsFilePath = "DPCertsPath:\$DPCertsPath"
        $CertSavePath = "C:\Temp\$ServerName" + "-DPcert.pfx"
        $DPCertsPath = $ServerName + "-DPcert.pfx"
        $CertPass = "password"
        $SecurePass = $CertPass | ConvertTo-SecureString -AsPlainText -Force
    
        ## Get Web Certificate
        Write-Output "Locating $WebCertTemp Certificate"
        ForEach ($WebCert in $CertStore) {
            $WebTempHash = ($WebCert.extensions | where-object {$_.oid.FriendlyName -match "Certificate Template Information"}).format(0).split(",")[0]
            $WebTemplate = $WebTempHash.trimstart("Template=").split("(")[0]
            If ($WebTemplate -like $WebCertTemp) {
                $WebCertThumb = $WebCert.Thumbprint
                Write-Output "Found - Thumbprint = $WebCertThumb" ; ""
            }
        }
        
        ## Set Web Certificate and HTTPS Binding
        Write-Output "Configuring HTTPS Binding for Default Webiste"
        Try {New-WebBinding -Name $iisSite -Protocol "https" -Port 443 -SslFlags 0} Catch {}
        Write-Output "Configuring $WebCertTemp for HTTPS Binding" ; ""
        Try {New-Item -Path "IIS:\SslBindings\*!443!" -Thumbprint $WebCertThumb -SSLFlags 0} Catch {}
        
        ## Get DP Certificate
        Write-Output "New / Reimage - Skipping check for existing FQDN Certificate for $ServerName" ; ""
    
        Write-Output "Checking LocalMachine CertStore."
        ForEach ($DPCert in $CertStore) {
            Remove-Variable DPCertThumb -ErrorAction SilentlyContinue
            $DPTempHash = ($DPCert.extensions | where-object {$_.oid.FriendlyName -match "Certificate Template Information"}).format(0).split(",")[0]
            $DPTemplate = $DPTempHash.trimstart("Template=").split("(")[0]
            If ($DPTemplate -like $DPCertTempDisp) {
                #$DPCertPath = $DPCert.PSParentPath
                $DPCertThumb = $DPCert.Thumbprint
                Write-Output "Existing Certificate found in CertStore.  Thumbprint: $DPCertThumb" ; ""
                #$DPCertPath
            }
        }
        If ($DPCertThumb -eq $null) {
            Write-Output "Existing Certificate not found in LocalMachine CertStore. Enrolling New Certificate."
            Set-Location -Path $CertStorePath
            Get-Certificate -CertStoreLocation $CertStorePath -Template $DPCertTemp -Url ldap: -DnsName $ServerName #-Credential $Credentials
            $CertStore = Get-ChildItem cert:\LocalMachine\My 
            ForEach ($DPCert in $CertStore) {
                $DPTempHash = ($DPCert.extensions | where-object {$_.oid.FriendlyName -match "Certificate Template Information"}).format(0).split(",")[0]
                $DPTemplate = $DPTempHash.trimstart("Template=").split("(")[0]
                If ($DPTemplate -like $DPCertTempDisp) {
                    #$DPCertPath = $DPCert.PSParentPath
                    $DPCertThumb = $DPCert.Thumbprint
                    Write-Output "New Certificate Enrolled.  Thumbprint: $DPCertThumb"
                    #$DPCertPath
                }
            }
        }
    
        ## Export DP Certificate and Delete from LocalMachine CertStore
        "" ; ""
        Write-Output "Exporting Cert PFX to $CertSavePath"
        Try { 
            New-Item -ItemType Directory -Force -Path C:\Temp | Out-Null
            Get-ChildItem -Path $CertStorePath\$DPCertThumb | Export-PfxCertificate -FilePath "Microsoft.PowerShell.Core\FileSystem::$CertSavePath" -Password $SecurePass
        } Catch [System.Runtime.InteropServices.COMException] {
            Write-Warning "User Name or Password is Incorrect"
        }
        New-PSDrive -Name DPCertsPath -PSProvider FileSystem -Root "\\Server\Share\Certificates\DP" -Credential $Credentials
        Move-Item $CertSavePath -Destination $CertsFilePath -Force #DPCertsPath:\$DPCertsPath
    
        If (Test-Path $CertsFilePath) {
            Write-Output "Removing Cert and Private Key from Local CertStore" ; ""
            Remove-Item -Path cert:\LocalMachine\My\$DPCertThumb -DeleteKey -Confirm:$false
        } Else {
            Write-Warning "Export Failed - Cert not deleted. (Check Permissions)"
        }
    
        Remove-PSDrive -Name DPCertsPath
        Set-Location C:
    
    } -AsSystem | Out-File $OutFile
    
    Stop-Transcript


    There's no place like 127.0.0.1



    • Edited by Matt5150 Friday, January 11, 2019 5:55 PM
    Thursday, January 10, 2019 6:27 PM
  • The script you referred to takes a number of parameters, some relating to running it on remote machines and using either a specified user account, local system account and one that specifically tells it to execute elevated.

    How are you calling your script from MDT ? 
    Does the script only affect the system on which the Task Sequence runs or are you trying to get it to do something on yet another system ? 

    From MDT - Task in State Restore:  Run PowerShell Script: "%SCRIPTROOT%\SCCM\SCCM-MDT-ProvisionDPCert.ps1"

    From SCCM - MDT Task before Application Installation:   "Run PowerShell Script" - (Package) Script Name: "SCCM-MDT-ProvisionDPCert.ps1"

    The SCCM TS also has a command before and after to add/remove the service account called in the script to and from the local Administrators group.

    cmd /c net localgroup administrators /add "domain\account"
    cmd /c net localgroup administrators /delete "domain\account"


    There's no place like 127.0.0.1

    Thursday, January 10, 2019 7:04 PM
  • I didn't try the actual scriptblock code as the error you receive indicates that that is not the issue.

    I can reproduce your error by running a non-elevated Powershell session and running the function with something like this:

    Invoke-CommandAs -ScriptBlock { Get-ADuser -filter * -Credential (Get-Credential) } -Verbose


    This produces the following output:

    WARNING: DEBUG START
    VERBOSE: IsElevated? = False
    WARNING: DEBUG END
    VERBOSE: Register-ScheduledJob: 9a1e5972-8503-4906-b71e-7ec33f3eb3e8
    Register-ScheduledJob : An access denied error occurred when registering scheduled job definition 9a1e5972-8503-4906-b71e-7ec33f3eb3e8.  Try running Windows PowerShell with elevated user rig
    hts; that is, Run As Administrator.
    At line:135 char:33
    + ... eduledJob = Register-ScheduledJob -Name $JobName -ScriptBlock $JobScr ...
    +                 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
        + CategoryInfo          : PermissionDenied: (Microsoft.Power...edJobDefinition:ScheduledJobDefinition) [Register-ScheduledJob], RuntimeException
        + FullyQualifiedErrorId : UnauthorizedAccessToRegisterScheduledJobDefinition,Microsoft.PowerShell.ScheduledJob.RegisterScheduledJobCommand



    If i run the same command in an elevated session, it prompts for credentials as desired, and the output shows:

    ARNING: DEBUG START
    VERBOSE: IsElevated? = True
    WARNING: DEBUG END
    VERBOSE: Register-ScheduledJob: c96cc6cc-d211-4486-ae73-d502bb7b8fe6
    VERBOSE: Start-ScheduledTask
    VERBOSE: Receive-ScheduledJob
    Windows PowerShell Credential Request: cmdlet Get-Credential at command pipeline position 1
    Warning: A script or application on the remote computer LOCALHOST is requesting your credentials. Enter your credentials only if you trust the remote computer and the application or script th
    at is requesting them.
    
    Supply values for the following parameters:
    
    
    RunspaceId            : 84a62ae6-897c-4519-9bef-b50ed9239ffb
    PSSourceJobInstanceId : e45de3e3-aa48-4ecb-870b-4c75482bdbae
    DistinguishedName     : CN=Administrator,CN=Users,DC=vmcorp,DC=local
    Enabled               : True
    GivenName             : 
    Name                  : Administrator
    ObjectClass           : user
    ObjectGUID            : ddc93117-2639-4d3b-9fbe-7488f51720ca
    SamAccountName        : Administrator
    SID                   : S-1-5-21-1968322116-597243378-3524102898-500
    Surname               : 
    UserPrincipalName     : 
    
    # and a bunch more accounts...
    
    VERBOSE: Unregister ScheduledJob

    So your problem is related to how the script is started and/or the user context in which it runs. It's unrelated to the user account you specify for the certificate stuff as your script fails before that account is even referenced by the script.

    ConfigMgr runs things as SYSTEM by default and should not give any elevation problems. If you need to somewhat securely feed credentials to a script, you could use a Run Command Line step in conjunction with the OSDDoNotLogCommand Task Sequence variable and modify your script to take a UserName and Password parameter. Though not perfect, its always better than hardcoding credentials in a script. 

    You may also want to modify the debug bit to this:

    # DEBUG START
    Write-Warning "DEBUG START"
    $UserPrincipal=New-Object System.Security.Principal.WindowsPrincipal([System.Security.Principal.WindowsIdentity]::GetCurrent())
    $AdminTEST = $UserPrincipal.IsInRole([System.Security.Principal.WindowsBuiltInRole]::Administrator)
    Write-Verbose "Running as: $($UserPrincipal.Identities.Name)"
    Write-Verbose "IsElevated? = $AdminTEST"
    Write-Warning "DEBUG END"
    # DEBUG END

    Then after running the TS, check your Transcript log to verify which account is actually executing the script.


    On a side note, you may want to consider changing the $Certpass value as you didn't strip it from the code you posted. (proving how easy it is to make mistakes with scripts containing actual credentials :))

    Friday, January 11, 2019 10:58 AM
  • That's an old password for a deleted cert.  I went ahead and cleared it out anyway to prevent confusion. ;)

    I added your debug code:

    **********************
    Windows PowerShell transcript start
    Start time: 20190111122850
    Username: CBSH\SYSTEM
    RunAs User: CBSH\SYSTEM
    Configuration Name: 
    Machine: TEST-KP-D3MZQP2 (Microsoft Windows NT 10.0.17134.0)
    Host Application: C:\WINDOWS\system32\windowspowershell\v1.0\powershell.exe -NoProfile -noninteractive -ExecutionPolicy Bypass -Command & 'D:\_SMSTaskSequence\Packages\001002A5\SCCM-MDT-ProvisionDPCert.ps1'  ; exit ($LASTEXITCODE -bor [int](-not $? -and -not $LASTEXITCODE)) 
    Process ID: 4904
    PSVersion: 5.1.17134.228
    PSEdition: Desktop
    PSCompatibleVersions: 1.0, 2.0, 3.0, 4.0, 5.0, 5.1.17134.228
    BuildVersion: 10.0.17134.228
    CLRVersion: 4.0.30319.42000
    WSManStackVersion: 3.0
    PSRemotingProtocolVersion: 2.3
    SerializationVersion: 1.1.0.1
    **********************
    Transcript started, output file is C:\Temp\SCCM-DP-CertScript-Transcript.log
    WARNING: DEBUG START
    VERBOSE: Running as: NT AUTHORITY\SYSTEM
    VERBOSE: IsElevated? = True
    WARNING: DEBUG END
    VERBOSE: Register-ScheduledJob: 675e27d1-6996-4a91-96e0-44717bb16038
    PS>TerminatingError(Register-ScheduledJob): "The running command stopped because the preference variable "ErrorActionPreference" or common parameter is set to Stop: An access denied error occurred when registering scheduled job definition 675e27d1-6996-4a91-96e0-44717bb16038.  Try running Windows PowerShell with elevated user rights; that is, Run As Administrator."
    >> TerminatingError(Register-ScheduledJob): "An access denied error occurred when registering scheduled job definition 675e27d1-6996-4a91-96e0-44717bb16038.  Try running Windows PowerShell with elevated user rights; that is, Run As Administrator."
    >> TerminatingError(Register-ScheduledJob): "An access denied error occurred when registering scheduled job definition 675e27d1-6996-4a91-96e0-44717bb16038.  Try running Windows PowerShell with elevated user rights; that is, Run As Administrator."
    >> TerminatingError(Register-ScheduledJob): "An access denied error occurred when registering scheduled job definition 675e27d1-6996-4a91-96e0-44717bb16038.  Try running Windows PowerShell with elevated user rights; that is, Run As Administrator."
    >> TerminatingError(Register-ScheduledJob): "An access denied error occurred when registering scheduled job definition 675e27d1-6996-4a91-96e0-44717bb16038.  Try running Windows PowerShell with elevated user rights; that is, Run As Administrator."
    An access denied error occurred when registering scheduled job definition 675e27d1-6996-4a91-96e0-44717bb16038.  Try running Windows PowerShell with elevated user rights; that is, Run As Administrator.
    Register-ScheduledJob : An access denied error occurred when registering scheduled job definition
    675e27d1-6996-4a91-96e0-44717bb16038.  Try running Windows PowerShell with elevated user rights; that is, Run As
    Administrator.
    At D:\_SMSTaskSequence\Packages\001002A5\SCCM-MDT-ProvisionDPCert.ps1:269 char:33
    + ... eduledJob = Register-ScheduledJob -Name $JobName -ScriptBlock $JobScr ...
    +                 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
        + CategoryInfo          : PermissionDenied: (Microsoft.Power...edJobDefinition:ScheduledJobDefinition) [Register-S
       cheduledJob], RuntimeException
        + FullyQualifiedErrorId : UnauthorizedAccessToRegisterScheduledJobDefinition,Microsoft.PowerShell.ScheduledJob.Reg
       isterScheduledJobCommand
    PS>$global:?
    False
    **********************
    Windows PowerShell transcript end
    End time: 20190111122851
    **********************
    


    There's no place like 127.0.0.1

    Friday, January 11, 2019 6:33 PM
  • From what i found you cannot use Register-ScheduleJob as System:
    https://social.technet.microsoft.com/Forums/en-US/af3b2683-2c48-4ff9-8587-2639320d8992/psv3-registerscheduledjob-as-system?forum=ITCG

    What happens if you run the script from a TS as command line and specify to run the whole script as a specific adminstrative user ?

    • Marked as answer by Matt5150 Monday, February 11, 2019 6:21 PM
    Monday, January 14, 2019 10:04 AM
  • In my MDT only environment, running it as a PS Task works fine (assuming I'm correct that MDT also runs everything as NT Authority\SYSTEM).

    In a SCCM / MDT Task Sequence, I'm not sure yet what the complete results are...

    I disabled the PS task and configured a "Run Command Line" task with the same package, and CMD:

    cmd /c powershell.exe -ExecutionPolicy Bypass -Command .\SCCM-MDT-ProvisionDPCert.ps1

    "Run this step as the following account:" set for the domain SA account.

    Transcript shows "Running as <Domain\SA Account>"
    And, "IsElevated?=True"

    But the the work the script is supposed to perform didn't complete, and the TS failed because the 10 minute timeout I set for that Task was reached, so the script must have been hung prompting or something else.  I may need to get PSEXEC over there and try some different types of RunAs operations.

    Might be something in my CMD line I used, so I'll try some different methods to call it, but since the transcript was recorded I think it was executed properly.


    There's no place like 127.0.0.1



    • Edited by Matt5150 Monday, January 14, 2019 9:22 PM Typo
    Monday, January 14, 2019 9:18 PM
  • By default, MDT runs everything as the local administrator account. 
    If the transcript log was created it did indeed execute the script. Maybe the log can give a hint as to where it halted ?
    Tuesday, January 15, 2019 7:01 AM
  • It shows the last thing ran before he hangs is "Get-Scheduled Job".

    Transcript started, output file is C:\Temp\SCCM-DP-CertScript-Transcript.log
    WARNING: DEBUG START
    VERBOSE: Running as: Domain\ServiceAccount
    VERBOSE: IsElevated? = True
    WARNING: DEBUG END
    VERBOSE: Register-ScheduledJob: c1827071-9882-4c39-9aba-09962bb3a8a1
    VERBOSE: Register-ScheduledTask
    VERBOSE: Start-ScheduledTask
    VERBOSE: Get-ScheduledJob
    


    I set the task to timeout in 90 minutes and after waiting about 30 I popped in, opened task scheduler, and found the job "Queued".  I have no idea what this pause is from.  I'm guessing credentials but I don't see that logged.  I'm going to see if there is a way to make this script run interactive / visible and run it again.

    I manually started the task, then things began to proceed normally and the TS eventually ended clean.

    But when I checked the transcript log again, it looks like it didn't run with the correct credentials.  The SA supplied does have rights to enroll the cert.  It's the same script being ran in MDT successfully.

    VERBOSE: Get-ScheduledJob
    VERBOSE: Receive-ScheduledJob
    CertEnroll::CX509Enrollment::Enroll: You do not have permission to request this type of certificate.: The permissions 
    on the certificate template do not allow the current user to enroll for this type of certificate. 0x80094012 
    (-2146877422 CERTSRV_E_TEMPLATE_DENIED). This may be the result of user credentials being required on the remote 
    machine. See Enable-WSManCredSSP Cmdlet help on how to enable and use CredSSP for delegation with PowerShell remoting.
        + CategoryInfo          : NotSpecified: (:) [Get-Certificate], Exception
        + FullyQualifiedErrorId : RemotingFailure,Microsoft.CertificateServices.Commands.GetCertificateCommand
        + PSComputerName        : localhost
    CertEnroll::CX509Enrollment::Enroll: You do not have permission to request this type of certificate.: The permissions
    on the certificate template do not allow the current user to enroll for this type of certificate. 0x80094012
    (-2146877422 CERTSRV_E_TEMPLATE_DENIED). This may be the result of user credentials being required on the remote
    machine. See Enable-WSManCredSSP Cmdlet help on how to enable and use CredSSP for delegation with PowerShell remoting.
        + CategoryInfo          : NotSpecified: (:) [Get-Certificate], Exception
        + FullyQualifiedErrorId : RemotingFailure,Microsoft.CertificateServices.Commands.GetCertificateCommand
        + PSComputerName        : localhost
    Object reference not set to an instance of an object.
        + CategoryInfo          : NotSpecified: (:) [Export-PfxCertificate], NullReferenceException
        + FullyQualifiedErrorId : System.NullReferenceException,Microsoft.CertificateServices.Commands.ExportPfxCertificate
        + PSComputerName        : localhost
    Object reference not set to an instance of an object.
        + CategoryInfo          : NotSpecified: (:) [Export-PfxCertificate], NullReferenceException
        + FullyQualifiedErrorId : System.NullReferenceException,Microsoft.CertificateServices.Commands.ExportPfxCertificat
       e
        + PSComputerName        : localhost
    VERBOSE: Unregister ScheduledTask
    VERBOSE: Unregister ScheduledJob
    **********************
    Windows PowerShell transcript end
    End time: 20190115173723
    


    There's no place like 127.0.0.1

    Tuesday, January 15, 2019 11:50 PM
  • Scheduled jobs are stored in the user profile.  Be sure the account running the job has a complete profile.  Here is where the jobs are stored.

    $env:USERPROFILE\AppData\Local\Microsoft\Windows\PowerShell\ScheduledJobs


    \_(ツ)_/

    • Marked as answer by Matt5150 Monday, February 11, 2019 6:20 PM
    Tuesday, January 15, 2019 11:58 PM
  • Thanks, jrv.  That reminder got me to a working solution (if not ideal).

    What I ended up having to do in total from my MDT solution, was:

    • Add TS step to add domain\ServiceAccount (SMSTemp) to the local administrator group (since GPO did not apply).

    • Add TS step to run a PS script to add a local service account, add to local administrators group.
    • Add TS step to create a TSvar "TmpAcct" for the new local account "%ComputerName%\SMSTemp".
      * Could not use "%_SMSTSMachineName%\SMSTemp", that TSVar using the "MINNT-?????" name.
      * Could not use "%ComputerName%\Administrator", "The password is incorrect."
    • Move Register-ScheduledJob script from a PS TS, to a "Run Command" TS, and set to run as %TmpAcct%
    • Add TS step to remove domain\SMSTemp from local administrator group.

    This process does work and if this is how I have to run it, I will.

    My remaining question, is why can't I use %ComputerName%\Administrator? 

    Is the password being changed by SCCM during the Task Sequence, then changed back at the end? 

    If so, is there a way around this to use the local\Administrator account / profile to run a Task?

    Thank you jrv / Matthijs for your help so far. ;)


    There's no place like 127.0.0.1



    • Edited by Matt5150 Thursday, January 17, 2019 9:32 PM
    Thursday, January 17, 2019 9:30 PM
  • Depends on where you use "%ComputerName%\Administrator". It will not work in PowerShell.

    Password changed?  Why would you say that?

    If you use the local admin account to run the task then it will have correct access to the folders in its profile. 

    I suggest using a ScheduledTask in a build as the PS components may not be stable yet. 

    Consider using AD to deploy user certificates.  Why waste time reinventing the wheel for a one-time task?


    \_(ツ)_/

    Thursday, January 17, 2019 9:37 PM
  • "%ComputerName%\Administrator" is set as a SCCM Task Sequence Variable "ex: SMSTemp" and then the "Run Command Line" step that runs the PowerShell script is configured to "Run this step as the following account" and use "%SMSTemp%", along with the Administrator password the image and task sequence are configured with.

    I don't have the log in front of me now, but when I ran it that the SMSTS.log reported that the credentials failed.  I'm going to retest this method in the morning to make sure I didn't have any typos anywhere during previous attempts.

    (In my previous post I said it worked when creating a new local account in the Task Sequence. This turns out not to be true, as it doesn't have a local profile either, just like the domain service account.  I found out I still had a couple variables pointed at the local account that was added to the test WIM before capture.)

    When I ran the same setup, but with the other local account I added to the image before capturing (Test WIM) using "%ComputerName%\SMSTemp", it worked.  But if I don't have to, I'd rather not recreate the images with another local account that I would then need to manage the password for (LAPS limited to managing one local account).

    The reason I'm doing it like this, is due to the way SCCM uses the certificates for Distribution Points.  They need to be enrolled on target computer, but not required to remain installed in the local store.

    Then they must be exported to a share for use when installing the Distribution Point role on the target computer.   And it must be done for each DP (few hundred).  This was working great in MDT, but I hit a wall when migrating all of it to SCCM.


    There's no place like 127.0.0.1

    Friday, January 18, 2019 2:39 AM
  • It seems like you may have some issues with the script and configuration.  Some sharp SCCM tech will likely be able to give you some better info.  I am not really expert in SCCM. 


    \_(ツ)_/

    Friday, January 18, 2019 2:53 AM
  • Thanks, jrv.

    This is the error that is generated when "%ComputerName%\Administrator" is used:

    Start executing the command line: tsenv.exe "SMSAdmin=%ComputerName%\Administrator" /hiddenflag:False	TSManager	1/17/2019 9:44:46 PM	4452 (0x1164)
    !--------------------------------------------------------------------------------------------!	TSManager	1/17/2019 9:44:46 PM	4452 (0x1164)
    Expand a string: WinPEandFullOS	TSManager	1/17/2019 9:44:46 PM	4452 (0x1164)
    Executing command line: tsenv.exe "SMSAdmin=%ComputerName%\Administrator" /hiddenflag:False	TSManager	1/17/2019 9:44:46 PM	4452 (0x1164)
    Finished with error code 0	TSEnv	1/17/2019 9:44:46 PM	4864 (0x1300)
    Process completed with exit code 0	TSManager	1/17/2019 9:44:47 PM	4452 (0x1164)
    !--------------------------------------------------------------------------------------------!	TSManager	1/17/2019 9:44:47 PM	4452 (0x1164)
    Successfully completed the action (Set Local User Administrator) with the exit win32 code 0	TSManager	1/17/2019 9:44:47 PM	4452 (0x1164)
    
    <Noise Removed>
    
    Start executing an instruction. Instruction name: Configure DP Certificate using CMD - SMSAdmin. Instruction pointer: 206	TSManager	1/17/2019 9:45:33 PM	4452 (0x1164)
    Set a global environment variable _SMSTSCurrentActionName=Configure DP Certificate using CMD - SMSAdmin	TSManager	1/17/2019 9:45:33 PM	4452 (0x1164)
    Set a global environment variable _SMSTSNextInstructionPointer=206	TSManager	1/17/2019 9:45:33 PM	4452 (0x1164)
    Set a local default variable SMSTSDisableWow64Redirection	TSManager	1/17/2019 9:45:33 PM	4452 (0x1164)
    Set a local default variable _SMSTSRunCommandLineAsUser	TSManager	1/17/2019 9:45:33 PM	4452 (0x1164)
    Set a local default variable SMSTSRunCommandLineUserName	TSManager	1/17/2019 9:45:33 PM	4452 (0x1164)
    Set a local default variable SMSTSRunCommandLineUserPassword	TSManager	1/17/2019 9:45:33 PM	4452 (0x1164)
    Set a global environment variable _SMSTSLogPath=C:\WINDOWS\CCM\Logs\SMSTSLog	TSManager	1/17/2019 9:45:33 PM	4452 (0x1164)
    Expand a string: smsswd.exe /run:001002A5 cmd /c powershell.exe -ExecutionPolicy Bypass -Command .\SCCM-MDT-ProvisionDPCert.ps1	TSManager	1/17/2019 9:45:33 PM	4452 (0x1164)
    Expand a string: 	TSManager	1/17/2019 9:45:33 PM	4452 (0x1164)
    Start executing the command line: smsswd.exe /run:001002A5 cmd /c powershell.exe -ExecutionPolicy Bypass -Command .\SCCM-MDT-ProvisionDPCert.ps1	TSManager	1/17/2019 9:45:33 PM	4452 (0x1164)
    !--------------------------------------------------------------------------------------------!	TSManager	1/17/2019 9:45:33 PM	4452 (0x1164)
    Expand a string: WinPEandFullOS	TSManager	1/17/2019 9:45:33 PM	4452 (0x1164)
    Executing command line: smsswd.exe /run:001002A5 cmd /c powershell.exe -ExecutionPolicy Bypass -Command .\SCCM-MDT-ProvisionDPCert.ps1	TSManager	1/17/2019 9:45:33 PM	4452 (0x1164)
     ================================ [ smsswd.exe ] ================================ 	InstallSoftware	1/17/2019 9:45:33 PM	4324 (0x10E4)
    PackageID = '001002A5'	InstallSoftware	1/17/2019 9:45:33 PM	4324 (0x10E4)
    BaseVar = '', ContinueOnError=''	InstallSoftware	1/17/2019 9:45:33 PM	4324 (0x10E4)
    ProgramName is logged, to ensure it not shown in log set 'OSDDoNotLogCommand' task sequence variable to 'True'	InstallSoftware	1/17/2019 9:45:33 PM	4324 (0x10E4)
    ProgramName = 'cmd /c powershell.exe -ExecutionPolicy Bypass -Command .\SCCM-MDT-ProvisionDPCert.ps1'	InstallSoftware	1/17/2019 9:45:33 PM	4324 (0x10E4)
    SwdAction = '0001'	InstallSoftware	1/17/2019 9:45:33 PM	4324 (0x10E4)
    ::LogonUser(sUserAccountName, sUserDomainName, sUserPassword, LOGON32_LOGON_INTERACTIVE, LOGON32_PROVIDER_DEFAULT, &hUserToken), HRESULT=8007052e (runcommandline.cpp,331)	InstallSoftware	1/17/2019 9:45:33 PM	4324 (0x10E4)
    LogonUser failed with the error 0x8007052e	InstallSoftware	1/17/2019 9:45:33 PM	4324 (0x10E4)
    cmd.Execute(pszPkgID, sProgramName, dwCmdLineExitCode), HRESULT=8007052e (main.cpp,389)	InstallSoftware	1/17/2019 9:45:33 PM	4324 (0x10E4)
    Install Software failed to run command line, hr=0x8007052e	InstallSoftware	1/17/2019 9:45:33 PM	4324 (0x10E4)
    Process completed with exit code 2147943726	TSManager	1/17/2019 9:45:33 PM	4452 (0x1164)
    !--------------------------------------------------------------------------------------------!	TSManager	1/17/2019 9:45:33 PM	4452 (0x1164)
    Failed to run the action: Configure DP Certificate using CMD - SMSAdmin. 
    The user name or password is incorrect. (Error: 8007052E; Source: Windows)	TSManager	1/17/2019 9:45:33 PM	4452 (0x1164)
    


    There's no place like 127.0.0.1

    Friday, January 18, 2019 3:59 AM
  • That only works if the execution environment supports system environment variables.  Obviously wher eyou are using it does not support this.

    SCCM has its own method of handling "replacement" variables.


    \_(ツ)_/

    Friday, January 18, 2019 4:11 AM
  • Unless otherwise specifically set or modified, the .\administrator password is set during the "Apply Windows Settings" step. The default is that the password is generated by ConfigMgr and the account disabled.

    If you want to use a Task Sequence variable to add credentials, you can use the "Set Task Sequence Variable" step. You can name the variable anything you want. In my case, i called it 'DomainJoinAccount'. You'd set that up like this:



    Then call the variable within any other step in the Task Sequence by using %DomainJoinAccount%. In this example i used it for the various domain join steps i have in my TS but you could use it in Run Command Line step in the same way too:



    I don't know what the %ComputerName% variable is that you reference. It is not a ConfigMgr variable. The one you can set is called OSDComputerName, the builtin one is called _SMSTSMachineName. See also:
    https://docs.microsoft.com/en-us/sccm/osd/understand/task-sequence-variables


    Friday, January 18, 2019 7:08 AM
  • That only works if the execution environment supports system environment variables.  Obviously wher eyou are using it does not support this.

    SCCM has its own method of handling "replacement" variables.


    \_(ツ)_/

    But it works, when I use the other local account I added to this image, %ComputerName%\SMSTemp.

    There's no place like 127.0.0.1

    Friday, January 18, 2019 5:34 PM
  • When the image is captured, the the Administrator password is "A".

    When the image is applied, the password is still "A".

    But when the Task Sequence doesn't complete (Like when it errors out on the situation above) the password "A" doesn't work to log on as the local administrator.  That's why I was asking if the TS temporary changed the administrator password. 

    I remember something like this occurred in MDT at a certain point.  Something to do with the way it security sets the auto-login.

    If I log in as another user, the account is enabled.

    %ComputerName% is the built in Windows variable.  I used it because it tested correctly when I tried it while trouble shooting.  I will probably use OSDComputerName for the production TS.

    Start executing the command line: tsenv.exe "SMSAdmin=%ComputerName%\Administrator" /hiddenflag:False	TSManager	1/17/2019 9:17:32 PM	4512 (0x11A0)
    !--------------------------------------------------------------------------------------------!	TSManager	1/17/2019 9:17:32 PM	4512 (0x11A0)
    Expand a string: WinPEandFullOS	TSManager	1/17/2019 9:17:32 PM	4512 (0x11A0)
    Executing command line: tsenv.exe "SMSTemp=%ComputerName%\Administrator" /hiddenflag:False	TSManager	1/17/2019 9:17:32 PM	4512 (0x11A0)
    Finished with error code 0	TSEnv	1/17/2019 9:17:32 PM	4976 (0x1370)
    Process completed with exit code 0	TSManager	1/17/2019 9:17:32 PM	4512 (0x11A0)
    !--------------------------------------------------------------------------------------------!	TSManager	1/17/2019 9:17:32 PM	4512 (0x11A0)
    Successfully completed the action (Set Local User Administrator) with the exit win32 code 0	TSManager	1/17/2019 9:17:32 PM	4512 (0x11A0)

    From a variable dump just before the failed step:

    OSDComputerName = TEST-KP-TEST01
    _SMSTSMachineName = MININT-2CTTS2U
    SMSTemp = TEST-KP-TEST01\Administrator


    There's no place like 127.0.0.1


    • Edited by Matt5150 Friday, January 18, 2019 6:05 PM
    Friday, January 18, 2019 6:04 PM
  • FYI: there is a new version of Invoke-CommandAs in the gallery!
    Tuesday, February 5, 2019 8:51 PM
  • I was eventually able to figure this all out. 

    The reason why it wasn't working with "local\Administrator" account / profile was because the password wasn't what I thought it was during the task sequence.  Apparently it had been fat fingered when the task was created, but one of the finish scripts was correcting it so it was working when you tried to log on with it.  After correcting that I'm now able to use that account to execute the scripts which need to run with an existing user profile.

    The main issue was the need for an existing user profile and running as "local\SYSTEM" as opposed to "local\Network System".  Both of you helped me get that cleared up earlier on, and I thank you.


    There's no place like 127.0.0.1

    Monday, February 11, 2019 6:20 PM