Sql-server – SQL Agent doesn’t have perms to run a PowerShell script

permissionspowershellsql serversql server 2014sql-server-agent

I recently upgraded SQL Server from Windows 2008 R2 & SQL Server 2008 R2 to Windows 2012 R2 & SQL Server 2014 SP1. One of the sql agent jobs fails to run. The job runs a PowerShell script to script sql agent jobs to disk. The job fails with an error:

SSPI handshake failed with error code 0x8009030c

If I RDP to the server and run the PS script in ISE with the SQL Server Agent service creds, it works.

Any ideas?

Here's the PS script:

param([String]$ServerName)

$OutputFolder = "\\backupfolder\sqlbackups\sqlservername\SQLAgentJobs"

#Load the SQL Server SMO Assembly
[System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SqlServer.Smo") | Out-Null

#Create a new SqlConnection object
$objSQLConnection = New-Object System.Data.SqlClient.SqlConnection

Try
{
    $objSQLConnection.ConnectionString = "Server=$ServerName;Integrated Security=SSPI;"
    $objSQLConnection.Open() | Out-Null
    $objSQLConnection.Close()
}
Catch
{
    $errText =  $Error[0].ToString()
    Write-Host $errText
}

$DoesFolderExist = Test-Path $OutputFolder
$null = if (!$DoesFolderExist){MKDIR "$OutputFolder"}

$srv = New-Object "Microsoft.SqlServer.Management.Smo.Server" $ServerName

foreach($job in $srv.JobServer.Jobs)
{
    $job_name = $job.Name
    $job.Script() | out-file "$OutputFolder\$job_name.sql"
}

Best Answer

I had a similar problem when running powershell scripts from a sql server job.

If you do not have remote PowerShell enabled on both servers and firewall access between the servers configured properly it will have issues.

Run a PowerShell script on a different server - from inside a SQL Server job

the way I have solved this problem is through a proxy account.

I have created a proxy account in sql server, that had all the relevat permissions to the remote server, folders and files that I needed and run the sql job as that account.

a proxy account in my case was a domain account, and I have granted this account the privileges on the remote server.

this might help with proxy: How to get the AD account associated to a Proxy?

From this link below you can see:

powershell problem when running on a remote server - access is denied

As far as workarounds, there is this answer on SU. you can read the article in detail that the answer points to fully understand, but this is the main command to adjust permissions:

If you decide you want to allow others, what you do is run the command:

Set-PSSessionConfiguration -Name Microsoft.PowerShell -showSecurityDescriptorUI 

Notice that this action could have a serious impact on your system so we ask you to confirm that you really want to do this.