我的SQL存储过程:
CREATE PROCEDURE [dbo].[sp_RemoveEmptyFiles]
@filePath varchar(260)
AS
DECLARE @sql as varchar(4000)
DECLARE @powershellFileLocation varchar(260)
SET @powershellFileLocation = '\\MyComputerName\Files\Powershell\cleandirectory.ps1'
SET @sql = 'powershell -c "& { . ' + @powershellFileLocation + '; clean-directory ' + @filePath + ' }"'
EXEC master..xp_cmdshell @sql
function clean-directory {
param ([string]$path)
try
{
if ($path.Length -le 0 -or -not (test-path -literalPath $path)) {
throw [System.IO.FileNotFoundException] """$path"" not a valid file path."
}
}
catch
{
write-host $error
}
}
现在,如果脚本成功,它将返回
NULL
返回值为0。目标是用将这些错误保存到SQL表的内容替换catch块。
$commandText = "INSERT INTO ErrorLogTable (TimeStamp, ErrorMessage) VALUES ($(Get-Date), $error)"
$command = $conn.CreateCommand()
$command.CommandText = $commandText
$command.ExecuteNonQuery()
但这似乎不是最好的方法--连接回调用存储过程的SQL server并创建新命令等。应该注意的是,powershell脚本、存储过程的文件路径参数和SQL server位于不同的位置,因此我确实需要记住权限问题(以及为什么我试图避免调用
Invoke-Sqlcmd
有没有办法在存储过程中获取powershell文件的输出,然后将错误消息保存到表中?