Nic*_*tes 6 sql-server powershell
产品版本 10.0.2531.0 产品级别 SP1 版本 企业版(64 位) 引擎版本 3
$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)
对此的任何帮助将不胜感激!
在 INSERT 查询的以下部分中:
('"+ $Name + "', " + $FreeSpace + ", " + $Size + ")"
Run Code Online (Sandbox Code Playgroud)
如果 $FreeSpace 或 $Size -eq $null,则它将无法正确完成查询字符串。要么像在 .NET 中一样使用命令参数(最佳方法),要么在插入之前检查 $null。
归档时间: |
|
查看次数: |
2325 次 |
最近记录: |