使用Powershell ISE,我运行“Get-Volume”命令并生成以下结果。
标题:
Drive FileSystemLabel FileSystem DriveType HealthStatus SizeRemaining Size
详情:
C NTFS Fixed Healthy 18.88 GB 59.4 GB
现在我想从vb.net程序中提取SizeRemaining和Size。
在debug中运行以下代码并传入“Get-Volume”命令,集合变量cResults包含1个条目:
(New System.Collections.Generic.Mscorlib_CollectionDebugView(Of System.Management.Automation.PSObject)(cResults))。Items(0)
{MSFT_Volume(ObjectId =“\?\ Volume {8a68dbb9-122c-4890-a81e-bf70 ...)}
如何从中获取SizeRemaining和Size(18.88 GB 59.4 GB)?
注意:如果我运行传入“Get-Process”的代码,则集合变量cResults包含43个System.Diagnostics.Process条目:
(New System.Collections.Generic.Mscorlib_CollectionDebugView(Of System.Management.Automation.PSObject)(cResults))。Items(0)
{System.Diagnostics.Process(conhost)}
在这种情况下,我可以使用“myProcess”钻取到 BaseObject 并获取该命令的各个结果字段。代码行。
RunScript("Get-Volume", diskViewData, StrMessage)
Sub RunScript(ByVal scriptText As String, ByRef byRefDiskViewData As DiskViewData, ByRef byRefMessage As String)
Dim runspace As Runspace
Dim diskViewDataList As New DiskViewData
Dim myProcess As System.Diagnostics.Process
Try
runspace = RunspaceFactory.CreateRunspace()
Try
runspace.Open()
Dim pipeline As Pipeline = runspace.CreatePipeline()
pipeline.Commands.AddScript(scriptText)
' Execute the script and add put result in a collection.
Dim cResults As Collection(Of PSObject) = pipeline.Invoke()
runspace.Close()
If cResults.Count > 0 Then
For Each obj As PSObject In cResults
Dim diskViewData As New DiskViewData
myProcess = obj.BaseObject
'diskViewData.Total_Size = (myProcess.?)
'diskViewData.Remaining_Space = (myProcess.?)
Next
Else
byRefMessage = "Empty object returned after runnng the powershell command."
End If
Catch ex As Exception
byRefMessage = "Failing AFTER create of runspace. " & ex.Message
End Try
Catch ex As Exception
byRefMessage = "Failing at create of runspace. " & ex.Message
End Try
End Sub
答案 0 :(得分:0)
如果我正确理解了您的问题,可以使用Properties collection of the PSObject class轻松获取结果,如下所示:
' create PowerShell instance for the specified command
dim ps as PowerShell = PowerShell.Create().AddCommand("Get-Volume")
' iterate over the result
for each result as PSObject in ps.Invoke()
' results only for drive C
if (result.Properties("DriveLetter").Value = "C") then
' access property using the Property properties collection
Console.WriteLine("{0} - Total: {1}; Remaining: {2}", result.Properties("DriveLetter").Value, result.Properties("Size").Value, result.Properties("SizeRemaining").Value)
end if
next result
结果是(您可以使用除以1024的格式对其进行格式化以获得KB / MB / GB):
C - 总计:1057254976;剩余:38872832