Получение информации о дисках и вывод в одну строку - PullRequest
0 голосов
/ 26 мая 2019

Я пытаюсь прочитать информацию на накопителях и хочу вывести результаты в виде (в 1 строке):

1/2 - Samsung Evo - 500GB - 4 partitions - C :, D :, E :, F:
2/2 - USB Transcend - 16GB - 2 partitions - G :, H:
On Error Resume Next
' Create a FileSystemObject
Set FSO = CreateObject("Scripting.FileSystemObject")
' Provide file path
Dim result, strComputer, outFile, PropertyArr, ArrayItem
outFile = "C:\Users\MISS\Desktop\ok.txt"
' Sets computer name to the current computer name
strComputer = "."
' Setting up file to write
Set objFile = FSO.CreateTextFile(outFile, True)
' Connect to the WMI Service
Set CIMV2 = GetObject("winmgmts:" & "\\" & strComputer & "\root\CIMV2")
If Err Then
    WScript.StdOut.WriteLine "Unable to access WMI Service."
    WScript.Quit 32
End If
' Fetch all details from Win32_computersystem
Set Win32_DiskDrive = CIMV2.ExecQuery("Select * from Win32_DiskDrive")
PropertyArr = Array("Model","MediaType")
For Each item_PropertyArr In PropertyArr
    ArrayItem = item_PropertyArr
Next
For Each item In Win32_DiskDrive
    result = item.ArrayItem
    WScript.Echo "Result: " & result
Next

Set FSO = Nothing

Это пустой результат.

1 Ответ

0 голосов
/ 26 мая 2019

Чтобы получить строковый вывод в нужном формате, я бы предложил использовать строку шаблона и использовать Replace() для заполнения деталей.

Поскольку вам нужны также буклеты, связанные с каждым разделом,вам нужно сделать больше, чем просто запросить Win32_DiskDrive, потому что этот запрос не возвращает буклеты.См. здесь

Следующий код должен делать то, что вы хотите:

Option Explicit

Const ForAppending = 8
Dim objFso, objFile, objWMIService, colDiskDrives, objDiskDrive
Dim colPartitions, objDiskPartition, colLogicalDisks, objDriveLetters, objLogicalDisk
Dim outFile, strFormat, strResult, numCurrentDrive, strMediaType, strID, strQuery, strComputer

On Error Resume Next

' set up file to write
outFile = "C:\Users\MISS\Desktop\ok.txt"

Set objFso = CreateObject("Scripting.FileSystemObject")
If objFso.FileExists(outFile) Then objFso.DeleteFile outFile, True
Set objFile = objFso.OpenTextFile(outFile, ForAppending, True)

strComputer = "."
Set objWMIService = GetObject( "winmgmts:{ impersonationLevel=Impersonate }!//" & strComputer )
Set colDiskDrives = objWMIService.ExecQuery( "Select * FROM Win32_DiskDrive" )

'set up a string as template for the output
strFormat = "{0}/{1} - {2} - {3} - {4} partition(s)"
'create a variable for the current disk count
numCurrentDrive = 1
For Each objDiskDrive In colDiskDrives
    'start building the string to output
    strMediaType = objDiskDrive.MediaType
    If IsNull(strMediaType) Or Len(strMediaType) = 0 Then strMediaType = "Unknown"
    strResult = Replace(strFormat, "{0}", numCurrentDrive)
    strResult = Replace(strResult, "{1}", colDiskDrives.Count)
    strResult = Replace(strResult, "{2}", objDiskDrive.Model)
    strResult = Replace(strResult, "{3}", strMediaType)
    strResult = Replace(strResult, "{4}", objDiskDrive.Partitions)

    'increase the current drive counter
    numCurrentDrive = numCurrentDrive + 1
    'create an arraylist to capture the drive letters
    Set objDriveLetters = CreateObject("System.Collections.ArrayList")

    'escape the backslashes in objDiskDrive.DeviceID for the query
    strID = Replace( objDiskDrive.DeviceID, "\", "\\", 1, -1, vbTextCompare )
    strQuery = "Associators Of {Win32_DiskDrive.DeviceID=""" & strID & """} Where AssocClass = Win32_DiskDriveToDiskPartition"
    Set colPartitions = objWMIService.ExecQuery(strQuery)
    For Each objDiskPartition In colPartitions
        'get the drive letter for each partition
        strQuery = "Associators Of {Win32_DiskPartition.DeviceID=""" & objDiskPartition.DeviceID & """} Where AssocClass = Win32_LogicalDiskToPartition"
        Set colLogicalDisks = objWMIService.ExecQuery(strQuery)
        For Each objLogicalDisk In colLogicalDisks
            objDriveLetters.Add objLogicalDisk.DeviceID
            'objDriveLetters.Add objLogicalDisk.VolumeName
        Next

        Set colLogicalDisks = Nothing
    Next

    'add the driveletters to the output string
    strResult = strResult & " - " & Join(objDriveLetters.ToArray(), ", ")

    Set objDriveLetters = Nothing
    Set colPartitions = Nothing

    'output on screen
    WScript.Echo strResult
    'output to file
    objFile.WriteLine strResult
Next

'close the file
objFile.Close
Set objFile = Nothing
Set colDiskDrives = Nothing
Set objWMIService = Nothing


Обновление

Согласноваши комментарии, вы хотели бы не использовать .NET (ArrayList) в коде.Конечно, это можно сделать, но с немного большими усилиями:

Option Explicit

Const ForAppending = 8
Dim objFso, objFile, objWMIService, colDiskDrives, objDiskDrive
Dim colPartitions, objDiskPartition, colLogicalDisks, objLogicalDisk
Dim outFile, strFormat, strResult, strMediaType, strID, strQuery, strComputer
Dim arrDriveLetters, numCurrentDrive, numDriveLetters

On Error Resume Next

' set up file to write
outFile = "C:\Users\MISS\Desktop\ok.txt"

Set objFso = CreateObject("Scripting.FileSystemObject")
If objFso.FileExists(outFile) Then objFso.DeleteFile outFile, True
Set objFile = objFso.OpenTextFile(outFile, ForAppending, True)

strComputer = "."
Set objWMIService = GetObject( "winmgmts:{ impersonationLevel=Impersonate }!//" & strComputer )
Set colDiskDrives = objWMIService.ExecQuery( "Select * FROM Win32_DiskDrive" )

'set up a string as template for the output
strFormat = "{0}/{1} - {2} - {3} - {4} partition(s)"
'create a variable for the current disk count
numCurrentDrive = 1
For Each objDiskDrive In colDiskDrives
    'start building the string to output
    strMediaType = objDiskDrive.MediaType
    If IsNull(strMediaType) Or Len(strMediaType) = 0 Then strMediaType = "Unknown"
    strResult = Replace(strFormat, "{0}", numCurrentDrive)
    strResult = Replace(strResult, "{1}", colDiskDrives.Count)
    strResult = Replace(strResult, "{2}", objDiskDrive.Model)
    strResult = Replace(strResult, "{3}", strMediaType)
    strResult = Replace(strResult, "{4}", objDiskDrive.Partitions)

    'increase the current drive counter
    numCurrentDrive = numCurrentDrive + 1
    'reset the dynamic array to capture the drive letters
    numDriveLetters = 0
    ReDim arrDriveLetters(numDriveLetters)

    'escape the backslashes in objDiskDrive.DeviceID for the query
    strID = Replace( objDiskDrive.DeviceID, "\", "\\", 1, -1, vbTextCompare )
    strQuery = "Associators Of {Win32_DiskDrive.DeviceID=""" & strID & """} Where AssocClass = Win32_DiskDriveToDiskPartition"
    Set colPartitions = objWMIService.ExecQuery(strQuery)
    For Each objDiskPartition In colPartitions
        'get the drive letter for each partition
        strQuery = "Associators Of {Win32_DiskPartition.DeviceID=""" & objDiskPartition.DeviceID & """} Where AssocClass = Win32_LogicalDiskToPartition"
        Set colLogicalDisks = objWMIService.ExecQuery(strQuery)
        For Each objLogicalDisk In colLogicalDisks
            ReDim Preserve arrDriveLetters(numDriveLetters)
            arrDriveLetters(numDriveLetters) = objLogicalDisk.DeviceID
            numDriveLetters = numDriveLetters + 1
        Next

        Set colLogicalDisks = Nothing
    Next

    'add the driveletters to the output string
    strResult = strResult & " - " & Join(arrDriveLetters, ", ")

    Erase arrDriveLetters
    Set colPartitions = Nothing

    'output on screen
    WScript.Echo strResult
    'output to file
    objFile.WriteLine strResult
Next

'close the file
objFile.Close
Set objFile = Nothing
Set colDiskDrives = Nothing
Set objWMIService = Nothing

Вывод будет выглядеть примерно так:

1/4 - Samsung SSD 750 EVO 250GB ATA Device - Fixed hard disk media - 1 partition(s) - C:
2/4 - ST3500418AS ATA Device - Fixed hard disk media - 1 partition(s) - E:
3/4 - WDC WD7501AALS-00J7B0 ATA Device - Fixed hard disk media - 1 partition(s) - D:
4/4 - Generic Ultra HS-SD/MMC USB Device - Unknown - 0 partition(s)

Надежда, которая помогает

PS Лучше всего использовать CScript вместо WScript, чтобы избежать появления всплывающих сообщений по одной строке за раз

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...