代码之家  ›  专栏  ›  技术社区  ›  C. Helling

如何将SQL存储过程调用的powershell脚本中的错误记录到SQL表中?

  •  0
  • C. Helling  · 技术社区  · 7 年前

    我的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."
            }
    
            #
            #
            # Clean directories here
            #
            #
        }
        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文件的输出,然后将错误消息保存到表中?

    1 回复  |  直到 7 年前
        1
  •  0
  •   C. Helling    7 年前

    因为我正在使用 xp_cmdshell ,我可以通过如下更改SQL脚本来捕获该输出:

    SET @sql = 'powershell -c "& { . ' + @powershellFileLocation + '; clean-directory ' + @filePath + ' }"'
    
    -- table to hold the output from the cmdshell
    CREATE TABLE #PowershellOutput ([Output] varchar(1000))
    
    -- execute actual powershell script
    INSERT INTO #PowershellOutput ([Output]) EXEC master..xp_cmdshell @sql