我的Transact SQL脚本有问题,我在Transact SQL中创建了一个过程,该过程必须使用函数执行powershell脚本。当我在命令提示符中执行文件和方法时,它可以工作,但是如果我将命令放在Transact SQL中,它会给我一个错误,说它不能识别命令。我希望有人可以帮助我。
命令提示符命令
powershell -command "& { . C:\Users\mslaats\Desktop\Databasescripts\Powershell\GmailLibrary.ps1; SendGmail "<email address>" "subject" "body" }"
Transact SQL脚本
PRINT 'Use the Divestar database'
USE [Divestar]
GO
PRINT 'Grant access to execute through a kind of cmd'
EXEC sp_configure 'show advanced options', 1
GO
RECONFIGURE
GO
EXEC sp_configure 'xp_cmdshell', 1
GO
RECONFIGURE
GO
-- Delete the old procedure
PRINT 'Drop procedure'
DROP PROCEDURE IF EXISTS [dbo].[SendEmail]
GO
-- Procedure --
PRINT 'Create procedure to send an email'
GO
CREATE PROCEDURE [dbo].[SendEmail]
@To VARCHAR(1024),
@Subject VARCHAR(1024),
@Content VARCHAR(1024)
AS
BEGIN
DECLARE @CMD VARCHAR(1024)
SET @CMD = 'powershell -command "& { . "C:\Users\mslaats\Desktop\Databasescripts\Powershell\GmailLibrary.ps1"; SendGmail "<email address>" "onderwerp" "bodytje" }"'
PRINT @CMD
EXEC xp_cmdshell @CMD
END
GO
Transact SQL脚本错误
. : The term
'C:\Users\mslaats\Desktop\Databasescripts\Powershell\GmailLibrary.ps1' is not
recognized as the name of a cmdlet, function, script file, or operable
program. Check the spelling of the name, or if a path was included, verify
that the path is correct and try again.
At line:1 char:7
+ & { . C:\Users\mslaats\Desktop\Databasescripts\Powershell\GmailLibrary.ps1;
Send ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : ObjectNotFound: (C:\Users\mslaat...mailLibrary.p
s1:String) [], CommandNotFoundException
+ FullyQualifiedErrorId : CommandNotFoundException
SendGmail : The term 'SendGmail' is not recognized as the name of a cmdlet,
function, script file, or operable program. Check the spelling of the name, or
if a path was included, verify that the path is correct and try again.
At line:1 char:77
+ & { . C:\Users\mslaats\Desktop\Databasescripts\Powershell\GmailLibrary.ps1;
Send ...
+
~~~~
+ CategoryInfo : ObjectNotFound: (SendGmail:String) [], CommandNo
tFoundException
+ FullyQualifiedErrorId : CommandNotFoundException
NULL
答案 0 :(得分:0)
遇到同样的问题后,我发现我需要检查两台机器上的ExecutionPolicy。我知道我的ExecutionPolicy在我的机器上很好,但是我通过以下方式检查了SQL服务器机器:
EXEC master..xp_cmdshell 'powershell -command "& { Get-ExecutionPolicy }" '
返回Restricted
(这意味着没有Powershell脚本可以运行,因此我遇到了与您相同的错误消息)。
此外,我还确保我的脚本存储在SQL Server有权访问的位置。您可以使用如下命令检查此情况:
EXEC master..xp_cmdshell 'powershell -command "& { dir C:\Users\mslaats\Desktop\Databasescripts\Powershell }" '
该命令将告诉您SQL是否可以看到您的脚本。就我而言,我将脚本放在一个我知道SQL可以访问的共享网络位置。