Powershell 类型的 SQL 代理作业在尝试通过 WMI 查询获取服务器上的磁盘空间时间歇性失败

Nic*_*tes 6 sql-server powershell

  • Microsoft SQL Server 2008 (SP1) - 10.0.2531.0 (X64) 2009 年 3 月 29 日 10:11:52 版权所有 (c) 1988-2008 Microsoft Corporation Enterprise Edition(64 位),Windows NT 6.1(内部版本 7600:)(VM)
  • Microsoft Server 2008 R2 标准版
产品版本 10.0.2531.0
产品级别 SP1
版本 企业版(64 位)
引擎版本 3

在尝试执行以下 powershell 脚本时...

$conn = New-Object System.Data.SqlClient.SqlConnection("Data Source=localhost\myServer; Initial Catalog=SysAdmin; Integrated Security=SSPI")

$conn.Open()

$cmd = $conn.CreateCommand()

gwmi -query "select * from Win32_LogicalDisk where DriveType=3" | select Name, FreeSpace, Size | foreach {
   $Name      = $_.Name.substring(0,1)
   $FreeSpace = $_.FreeSpace
   $Size      = $_.Size

   $cmd.CommandText = "INSERT dbo.DiskSpace (drive, [free(bytes)], [total(bytes)]) VALUES ('"+ $Name + "', " + $FreeSpace + ", " + $Size + ")"
   $cmd.ExecuteNonQuery()

   $cmd.CommandText = "EXEC dbo.sp_diskspace @performAggregation=1"
   $cmd.ExecuteNonQuery()
}

$conn.Close()
Run Code Online (Sandbox Code Playgroud)

...我收到以下错误

消息以用户身份执行:Domain\SqlSrvAgentSer。

作业步骤在 PowerShell 脚本的第 7 行收到错误。对应的行是'gwmi -query "select * from Win32_LogicalDisk where DriveType=3" | 选择名称、自由空间、大小 | foreach{'。更正脚本并重新安排作业。PowerShell 返回的错误信息是:“使用“0”参数调用“ExecuteNonQuery”的异常:“','附近的语法不正确。” ',' 附近的语法不正确。'。进程退出代码 -1。步骤失败。

附加信息

CREATE PROCEDURE dbo.sp_diskspace
   @performAggregation BIT = 0
AS

SET NOCOUNT ON;

DECLARE @aggregrateDate DATETIME

BEGIN
  SET @aggregrateDate = DATEADD(month, -1, GETDATE())
  SET @aggregrateDate = DATEADD(dd, DATEDIFF(dd, 0, @aggregrateDate), 0)

  INSERT INTO dbo.diskspace (
     drive,
     MeasurementDate,
     [free(bytes)],
     [total(bytes)],
     isAggregated)
  SELECT 
      drive,
      DATEADD(dd, DATEDIFF(dd, 0, MeasurementDate), 0), 
      AVG([free(bytes)]),
      AVG([total(bytes)]),
      1
  FROM 
      dbo.diskspace
  WHERE
      MeasurementDate < @aggregrateDate
      AND isAggregated <> 1
  GROUP BY
      drive,
      DATEADD(dd, DATEDIFF(dd, 0, MeasurementDate), 0)

  IF @@ERROR = 0 and @@ROWCOUNT > 0
     BEGIN
        DELETE FROM dbo.diskspace 
        WHERE MeasurementDate < @aggregrateDate 
        AND isAggregated <> 1

        IF @@ERROR = 0
           BEGIN
              RAISERROR('sp_diskspace : aggregation complete', 0, 1)
           END
     END
END
Run Code Online (Sandbox Code Playgroud)

对此的任何帮助将不胜感激!

Eri*_*elp 1

在 INSERT 查询的以下部分中:

('"+ $Name + "', " + $FreeSpace + ", " + $Size + ")"
Run Code Online (Sandbox Code Playgroud)

如果 $FreeSpace 或 $Size -eq $null,则它将无法正确完成查询字符串。要么像在 .NET 中一样使用命令参数(最佳方法),要么在插入之前检查 $null。