Размер диска PowerShell - PullRequest
       6

Размер диска PowerShell

0 голосов
/ 26 апреля 2018

Я нашел эту идею, как получить размер диска

У меня проблема с включением его в мой скрипт, так как я не знаю, куда вставить код. Кроме того, идея состоит в том, чтобы на каждом компьютере выводилась только одна строка, даже если существует система с несколькими жесткими дисками.

Это код, с которым я работаю, включает код "Get Drive Data"

# Output file location to be changed as needed
$file="C:\scripts\reports\InentoryTest_$((Get-Date).ToString('MM-dd-yyyy')).csv"
$txt="c:\scripts\reports\InentoryTest-error_$((Get-Date).ToString('MM-dd-yyyy')).txt"

# Getting computers from Active Directory
$Computers = Get-ADComputer -Filter {Name -like 'M416*'} | select -expand name

  Foreach($Computer in $Computers){

if(!(Test-Connection -ComputerName $Computer -BufferSize 16 -Count 1 -ea 0 -quiet))
 {
 write-host "Cannot reach $Computer is offline" -ForegroundColor red
 }
 else
 {

$Output = @()

    Try
    {
       # Get Drive Data 
       $disk   = Get-WmiObject -ComputerName $Computer Win32_LogicalDisk | Where-Object { ( $_.DriveType ) -eq 3 -and ( ( $_.freespace / $_.size ) -lt .1  ) } | ForEach-Object -Process {
                   [pscustomobject] @{
        Drive        = $_.DeviceID
        Size         = '{0:N1}' -f ( $_.Size / 1GB )
        Free         = '{0:N1}' -f ( $_.freespace / 1GB )
        PercentFree  = '{0:N1}' -f ( $_.freespace / $_.size * 100 )
                        }
                    } 
        $domain = Get-WmiObject Win32_ComputerSystem -ComputerName $Computer -ErrorAction Stop
        $os   = Get-WmiObject Win32_OperatingSystem -ComputerName $Computer -ErrorAction Stop
        $mac  = Get-WmiObject -class Win32_NetworkAdapterConfiguration -Filter "IPEnabled='True'" -ComputerName $Computer -ErrorAction Stop
        $bios = Get-WmiObject win32_bios -ComputerName $Computer -ErrorAction Stop
        $cpu  = Get-WmiObject –class Win32_processor -ComputerName $Computer -ErrorAction Stop
        $AD   = Get-ADComputer $Computer -properties Name,Lastlogondate,ipv4Address,enabled,description,DistinguishedName -ErrorAction Stop
        $ram  = "{0} GB" -f ((Get-WmiObject Win32_PhysicalMemory -ComputerName $Computer -ErrorAction Stop | Measure-Object Capacity  -Sum).Sum / 1GB)
        $pc   = Get-WmiObject win32_computersystem -ComputerName $Computer -ErrorAction Stop | select @{Name = "Type";Expression = {if (($_.pcsystemtype -eq '2')  )
                {'Laptop'} Else {'Desktop Or Other'}}
        },Manufacturer,@{Name = "Model";Expression = {if (($_.model -eq "$null")  ) {'Virtual'} Else {$_.model}}},username

        # Create Output
        $data = New-Object PSObject -Property @{
            SerialNumber              = $bios.serialnumber -replace "-.*"
            Computername              = $AD.name
            IPaddress                 = $AD.ipv4Address
            MACaddress                = $mac.MACAddress
            Enabled                   = $AD.Enabled
            Description               = $AD.description
            OU                        = $AD.DistinguishedName.split(',')[1].split('=')[1] 
            DC                        = $domain.domain
            Type                      = $pc.type
            Manufacturer              = $pc.Manufacturer
            Model                     = $pc.Model
            RAM                       = $ram
            Disk                      = $disk #Get Drive Data
            ProcessorName             = ($cpu.name | Out-String).Trim()
            NumberOfCores             = ($cpu.NumberOfCores | Out-String).Trim()
            NumberOfLogicalProcessors = ($cpu.NumberOfLogicalProcessors | Out-String).Trim()
            Addresswidth              = ($cpu.Addresswidth | Out-String).Trim()
            OperatingSystem           = $os.caption
            InstallDate               = ([WMI] '').ConvertToDateTime($os.installDate)
            LastLogonDate             = $ld.lastlogondate
            LoggedinUser              = $pc.username
        }

        # Only do this kind of update if it hasn't failed yet
        $Output += $data
        $desc="$($mac.MACAddress) ( $($bios.serialnumber -replace "-.*") ) $($pc.Model) | $((Get-Date).ToString('MM-dd-yyyy'))"
        #Set-ADComputer $Computer -Description $desc -verbose
        $Output | select Computername,Enabled,Description,IPaddress,MACaddress,OU,DC,Type,SerialNumber,Manufacturer,Model,RAM,Disk,ProcessorName,NumberOfCores,NumberOfLogicalProcessors,Addresswidth,OperatingSystem,InstallDate,LoggedinUser,LastLogonDate | export-csv -Append $file -NoTypeInformation 

    }
    Catch [Exception]
    {
    # Only do this kind of update if create output has failed
        $ErrorMessage = $_.Exception.Message
        Add-Content -value "$Computer, $ErrorMessage, skipping to next" $txt
        #Set-ADComputer $Computer -Description $ErrorMessage
            continue
      }
     }
    }

1 Ответ

0 голосов
/ 26 апреля 2018

Вы строите сложный иерархический объект, поэтому вам лучше собрать все объекты, а затем вывести результат в виде файла JSON или XML. Но если вам нужна плоская строка, вам придется явно отформатировать данные на диске в строку, прежде чем добавлять их к объекту, который вы выгружаете в CSV. Что-то вроде:

$diskData = $disk | foreach {
  "[Drive: $($_.DeviceID), Size: $([int]($_.Size/1GB)), FreeSpace: $([int]($_.freespace/1GB)), PercentFree: $([int]($_.freespace/$_.size *100))]"
}
$diskdata = $diskdata -join " "
...