Invoke-SQLcmd在Invoke-command中不起作用

时间:2019-02-06 09:09:07

标签: sql powershell remote-access sqlcmd

我目前在Invoke-SQLcmd脚本块中运行Invoke-Command,并不断收到连接错误,Invoke-SQLcmd脚本在单独运行时有效,但没有被包裹在{{ 1}}。

Invoke-Command

然后我收到以下错误:

Invoke-Command -ComputerName "MyserverFQDN" -Credential $Serviceaccount -ScriptBlock {
Invoke-Sqlcmd -ServerInstance "SQLDBFQDN" -Database BizTalkMgmtDb -Query "
USE BizTalkMgmtDb
GO
SELECT        bts_sendport.nvcName, bts_sendport_transport.nvcAddress, nPortStatus, bts_sendport_transport.dtFromTime, 
              bts_sendport_transport.bIsServiceWindow, bts_sendport_transport.dtToTime,
              adm_Adapter.Name As TransportTypeID, bts_application.nvcName AS Application
FROM            bts_sendport With(NOLOCK) INNER JOIN
                         bts_sendport_transport ON bts_sendport.nID = bts_sendport_transport.nSendPortID 
                         INNER JOIN
                         bts_application ON bts_sendport.nApplicationID = bts_application.nID
                         INNER JOIN 
                         adm_Adapter ON bts_sendport_transport.nTransportTypeId = adm_Adapter.Id

WHERE 
nTransportTypeId IS NOT NULL

"
}

就像我说的那样,我可以从服务器作为服务帐户运行SQLcmd,它可以正常工作,但是如果我从PC调用此命令以调用服务器以使用服务帐户运行SQLcmd,则会收到该错误。任何想法发生了什么或如何解决这个问题?

1 个答案:

答案 0 :(得分:0)

我认为问题在于脚本块中的$SQLDBFQDN变量是在临时会话中定义的,与您的变量不同(因为它在远程计算机上的另一个PowerShell进程中运行)。

To use local variable in a remote session,尝试通过将$SQLDBFQDN替换为$Using:SQLDBFQDN来更改其范围:

Invoke-Command -ComputerName $MyserverFQDN -Credential $Serviceaccount -ScriptBlock {
Invoke-Sqlcmd -ServerInstance $Using:SQLDBFQDN -Database BizTalkMgmtDb -Query "
USE BizTalkMgmtDb
GO
SELECT        bts_sendport.nvcName, bts_sendport_transport.nvcAddress, nPortStatus, bts_sendport_transport.dtFromTime, 
              bts_sendport_transport.bIsServiceWindow, bts_sendport_transport.dtToTime,
              adm_Adapter.Name As TransportTypeID, bts_application.nvcName AS Application
FROM            bts_sendport With(NOLOCK) INNER JOIN
                         bts_sendport_transport ON bts_sendport.nID = bts_sendport_transport.nSendPortID 
                         INNER JOIN
                         bts_application ON bts_sendport.nApplicationID = bts_application.nID
                         INNER JOIN 
                         adm_Adapter ON bts_sendport_transport.nTransportTypeId = adm_Adapter.Id

WHERE 
nTransportTypeId IS NOT NULL

"
}