gpt4 book ai didi

tsql - 无法使用 Transact SQL 脚本中的函数调用执行 powershell 文件

转载 作者:行者123 更新时间:2023-12-04 18:31:41 24 4
gpt4 key购买 nike

我的 Transact SQL 脚本有问题,我在 Transact SQL 中创建了一个过程,它必须执行一个带有函数的 powershell 脚本。当我在命令提示符中执行文件和方法时,它可以工作,但如果我将命令放在 Transact SQL 中,它会给我一个错误,提示它无法识别该命令。我希望有人能帮助我。

命令提示符命令

powershell -command "& { . C:\Users\mslaats\Desktop\Databasescripts\Powershell\GmailLibrary.ps1; SendGmail "<email address>" "subject" "body" }"

事务 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

事务 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

最佳答案

遇到同样的问题后,我发现我需要检查两台机器上的 ExecutionPolicy。我知道我的 ExecutionPolicy 在我的机器上没有问题,但我通过以下方式检查了 SQL Server 机器:

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 已经可以访问的共享网络位置。

关于tsql - 无法使用 Transact SQL 脚本中的函数调用执行 powershell 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41017630/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com