我正在尝试使用DefragAnalysis方法打印(到文本文件)Win32_Volume类提供的碎片信息,并提出以下VB.NET代码:
Dim objReader As StreamWriter
objReader = New StreamWriter(FolderBrowserDialog.SelectedPath + "\FragInfo" + "_" + CreationDate + ".txt")
Dim colItemsFragInfo As New ManagementObjectSearcher("root\CIMV2", "Select * from Win32_Volume where DriveType = 3")
For Each queryObj As ManagementObject In colItemsFragInfo.Get()
objReader.WriteLine("Analyzing volume " + queryObj("DriveLetter"))
Dim InParams As ManagementBaseObject = queryObj.GetMethodParameters("DefragAnalysis")
Dim OutParams As ManagementBaseObject = queryObj.InvokeMethod("DefragAnalysis", InParams, Nothing)
MsgBox(OutParams("VolumeSize"))
objReader.WriteLine(" Volume size: " + OutParams("VolumeSize"))
Next
objReader.Close()
Catch err As ManagementException
MessageBox.Show("An error occurred while trying to execute the WMI method: " & err.Message)
End Try
我无法理解的是如何从“DefragAnalysis”方法获取参数信息(即“VolumeSize”)。上面的代码返回“Method not found error”。
谢谢
- 编辑 这是当前在WMI代码创建器中执行时的工作原理:
Imports System
Imports System.Management
Imports System.Windows.Forms
Namespace WMISample
Public Class MyWMIQuery
Public Overloads Shared Function Main() As Integer
Try
Dim colItemsVolInfo As New ManagementObjectSearcher("root\CIMV2", "Select * from Win32_Volume where DriveType = '3'")
For Each queryObj As ManagementObject In colItemsVolInfo.Get()
Dim OutParams As ManagementBaseObject = queryObj.InvokeMethod("DefragAnalysis", Nothing, Nothing)
Console.WriteLine(" Volume size: {0}MB", Math.Round(OutParams("DefragAnalysis")("VolumeSize")) * (9.53674316 * 10 ^ -7))
Console.WriteLine(" Cluster size: {0}MB", Math.Round(OutParams("DefragAnalysis")("ClusterSize")) * (9.53674316 * 10 ^ -7))
If OutParams("DefragRecommended") = True Then
Console.WriteLine("You should defragment this volume.")
Else
Console.WriteLine("You do not need to defragment this volume.")
End If
Next
Catch err As ManagementException
MessageBox.Show("An error occurred while trying to execute the WMI method: " & err.Message)
End Try
End Function
End Class
End Namespace
WMI输出: 卷大小:40857.9960763451MB 簇大小:0.003906249998336MB 您无需对此卷进行碎片整理。
但是在Visual Studio中执行此操作会返回以下内容: 卷大小:MB 群集大小:MB 您无需对此卷进行碎片整理。
这里的重点是它在Windows Server 2008 R2下不起作用,但在Windows Server 2003下工作(在Visual Studio中执行时),无论平台如何,WMI代码都能正常工作。
注意:我玩过“Console.WriteLine”并将其更改为“Debug.WriteLine”以将值输出到即时窗口。
答案 0 :(得分:0)
没有VolumeSize
属性。
当您致电DefragAnalysis()时,它会返回功能状态并输出参数boolean DefragRecommended
和object DefragAnalysis
。
DefragAnalysis Class包含属性VolumeSize
。
Console.WriteLine("DefragRecommended: {0}", outParams("DefragRecommended"))
Console.WriteLine("VolumeSize: {0}", outParams("DefragAnalysis")("VolumeSize"))
Console.WriteLine("ReturnValue: {0}", outParams("ReturnValue"))
您应该始终阅读documentation而不是猜测。
我想建议一个名为WMI Code Creator v1.0的好工具。此工具工具允许您生成VBScript,C#和VB .NET代码,这些代码使用WMI完成管理任务,例如查询管理数据,从WMI类执行方法或使用WMI接收事件通知。
我希望这会有所帮助。 :)