Powershell驱动器计算器



所以我有下面的代码,它运行得很好,但由于某种原因,它只计算我的 D: 驱动器,而不是我的 C: 驱动器?

$computerName = Get-Wmiobject Win32_ComputerSystem
$computerOS = Get-Wmiobject Win32_OperatingSystem
$computerHDD = Get-Wmiobject Win32_LogicalDisk -Filter drivetype=3
ForEach($HDD in $computerHDD){
$txtObject = New-Object PSObject -property @{
    'ComputerName' = $computerName.Name
    'ComputerModel' = $computerName.Model
    'SerialNumber' = $computerName.SerialNumber
    'HDDSize' = "{0:N2}" -f ($HDD.Size/1GB)
    'HDDFree' = "{0:P2}" -f ($HDD.FreeSpace/$HDD.Size)
    'OS' = $computerOS.caption
    'OS_type' = $computerOS.OSArchitecture
    'User' = $computerName.UserName
    } 
}
$txtObject | Select-Object ComputerName, ComputerModel, SerialNumber, HDDSize, HDDFree, OS, Os_type, User | Out-File "$PSSCriptRootcomputer_info.txt" -Append
似乎

你需要创建一个数组。试试这个...

$computerName = Get-Wmiobject Win32_ComputerSystem
$computerOS = Get-Wmiobject Win32_OperatingSystem
$computerHDD = Get-Wmiobject Win32_LogicalDisk -Filter drivetype=3
$output = @()
ForEach($HDD in $computerHDD){
$txtObject = New-Object PSObject -property @{
    'ComputerName' = $computerName.Name
    'ComputerModel' = $computerName.Model
    'SerialNumber' = $computerName.SerialNumber
    'HDDSize' = "{0:N2}" -f ($HDD.Size/1GB)
    'HDDFree' = "{0:P2}" -f ($HDD.FreeSpace/$HDD.Size)
    'OS' = $computerOS.caption
    'OS_type' = $computerOS.OSArchitecture
    'User' = $computerName.UserName
    } 
    $output += $txtObject
}
$output | Select-Object ComputerName, ComputerModel, SerialNumber, HDDSize, HDDFree, OS, Os_type, User | Out-File "$PSSCriptRootcomputer_info.txt" -Append

您在循环的每次迭代中都会覆盖$txtObject,因此您的输出仅包含最终迭代中的驱动器。 相反,您应该将$txtObject初始化为阵列,然后将每个驱动器的信息附加到该阵列中:

$computerHDD = Get-Wmiobject Win32_LogicalDisk -Filter drivetype=3
$txtObject = @()
ForEach($HDD in $computerHDD){
    $txtObject += New-Object PSObject -property @{
        # ...
    } 
}
$txtObject | Select-Object ... | Out-File "$PSSCriptRootcomputer_info.txt" -Append

更好的是,您可以消除循环和变量,只使用管道:

$computerName = Get-WmiObject Win32_ComputerSystem
$computerOS = Get-WmiObject Win32_OperatingSystem
Get-WmiObject Win32_LogicalDisk -Filter drivetype=3 `
    | ForEach-Object -Process {
        New-Object PSObject -Property @{
            'ComputerName'  = $computerName.Name
            'ComputerModel' = $computerName.Model
            'SerialNumber'  = $computerName.SerialNumber
            'HDDSize'       = "{0:N2}" -f ($_.Size/1GB)
            'HDDFree'       = "{0:P2}" -f ($_.FreeSpace/$_.Size)
            'OS'            = $computerOS.caption
            'OS_type'       = $computerOS.OSArchitecture
            'User'          = $computerName.UserName
        };
    } | Out-File "$PSSCriptRootcomputer_info.txt" -Append

请注意,上面的New-Object几乎与您的原始代码相同,只是必须使用$_而不是$HDD

相关内容

  • 没有找到相关文章

最新更新