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.
Parents
No Data
Reply
  • 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.

     

     

Children
No Data