Powershell script fails to connect to SQL Server when run from an SQL Server job step.

Hi,

I am trying to run the below PowerShell script from a job step:

$erroractionpreference = "Stop"
$DBName = 'MyDB'
$ServerName = Invoke-Sqlcmd -query "SELECT @@ServerName"
$Srv = $ServerName[0]
SL SQLSERVER:\SQL\"$Srv"\Databases\"$DBName"\Tables
It give me an error:
A job step received an error at line 10 in a PowerShell script. The corresponding line is '$ServerName = Invoke-Sqlcmd -query "SELECT @@ServerName" '. Correct the script and reschedule the job. The error information returned by PowerShell is: 'A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: Named Pipes Provider, error: 40 - Could not open a connection to SQL Server)  '.  Process Exit Code -1.  The step failed.
If I run the same script interactively from the PowerShell window, which was started from Management Studio, everything works.
Any ideas?
 
Thanks.
  • It is not duplicate, the other one is about using environment variable in the same script.  This one is about connecting to sql server without it.

  • I imagine that this is because SQL Agent is running on an instance, but because you didn't specify it, it's trying to connect to the hostname.

    I have a Windows server with two instances, Default (sql2008) and the R2 instance (sql2008\sql2k8r2)

    When I run my job that just consists of $ServerName = Invoke-Sqlcmd -query "SELECT @@ServerName" on sql2008\sql2k8r2's agent, the job is a success, but returns sql2008. When I turned off the sql2008 instance, the job failed.

    Please see my answer to your previous question. All in all, the approach you tried above is not recommended. I don't do much with PowerShell in SQL Agent (this was actually just the second time I've worked with it, I don't like how it takes so long to initiate), so I'm not sure what's the best way to get your server name. I did just do some digging and it apparently uses sqlps.exe, so you can try running sqlps.exe on the server itself as the SQL Agent service account, and you'll have an interactive shell to test with.

     

  • I found a beautiful way to solve this problem for SQL jobs, you just need to use this command to extract the instance name:

    $Srv = '$(ESCAPE_SQUOTE(SRVR))'

    This won't work from Powershell window, only in a job step.