【问题标题】:How to get disk capacity and free space of remote computer如何获取远程计算机的磁盘容量和可用空间
【发布时间】:2012-08-22 23:10:47
【问题描述】:

我有这个单行:

get-WmiObject win32_logicaldisk -Computername remotecomputer

输出如下:

DeviceID     : A:
DriveType    : 2
ProviderName :
FreeSpace    :
Size         :
VolumeName   :

DeviceID     : C:
DriveType    : 3
ProviderName :
FreeSpace    : 20116508672
Size         : 42842714112
VolumeName   :

DeviceID     : D:
DriveType    : 5
ProviderName :
FreeSpace    :
Size         :
VolumeName   :

如何获得DeviceID C:FreespaceSize?我只需要提取这两个值而不需要其他信息。我用Select cmdlet 试过了,但是没有效果。

编辑: 我只需要提取数值并将它们存储在变量中。

【问题讨论】:

  • PS C:\> icm remotecomputer {gdr C |选择免费,@{Name='Size';表达式={$_.Free+$_.Used}}}

标签: powershell scripting powershell-2.0


【解决方案1】:

更简单的解决方案:

Get-PSDrive C | Select-Object Used,Free

对于远程计算机(需要Powershell Remoting

Invoke-Command -ComputerName SRV2 {Get-PSDrive C} | Select-Object PSComputerName,Used,Free

【讨论】:

  • 安装PSTools并执行psexec -u administrator \\[computer name or IP] powershell "get-psdrive C"
  • 如果需要进行身份验证,这需要在远程机器中启用“Kerberos 身份验证机制”。
  • 如果您想要这个更具可读性,请尝试:'Get-PSDrive |选择对象@{Expression={$_.Free/1TB}}'
  • 在许多企业环境中,PowerShell Remoting 可能不可用。
【解决方案2】:
$disk = Get-WmiObject Win32_LogicalDisk -ComputerName remotecomputer -Filter "DeviceID='C:'" |
Select-Object Size,FreeSpace

$disk.Size
$disk.FreeSpace

仅提取值并将它们分配给变量:

$disk = Get-WmiObject Win32_LogicalDisk -ComputerName remotecomputer -Filter "DeviceID='C:'" |
Foreach-Object {$_.Size,$_.FreeSpace}

【讨论】:

  • 只需添加 $disk.Size / 1GB 也使结果更具可读性。
  • 如果你想四舍五入只显示整数,使用[Math]::Round($Disk.Freespace / 1GB)
  • 在powershell中为什么1mb返回值1048576而不是1000000 ????
  • @oldboy 因为它使用 2 的幂:2^20 与 10^6。它确实应该写成1MiB(使用正确的大小写),但通常以小写形式显示,没有“i”。见Mebibyte
  • @oldboy 为什么 mb,这个时间已经过去了,我们在记忆力方面是 000。
【解决方案3】:

只有一个简单又干净的命令,但这仅适用于本地磁盘

Get-PSDrive

您仍然可以通过执行 Enter-PSSession -Computername ServerName 在远程服务器上使用此命令,然后运行 ​​Get-PSDrive,它会像从服务器运行数据一样提取数据。

【讨论】:

  • 仅获取文件系统驱动器:Get-PSDrive | ? { $_.Provider.Name -eq 'FileSystem' }
【解决方案4】:

不久前我创建了一个 PowerShell 高级函数(脚本 cmdlet),它允许您查询多台计算机。

该函数的代码有 100 多行,所以你可以在这里找到它:PowerShell version of the df command

查看使用部分的示例。以下使用示例查询一组远程计算机(来自 PowerShell 管道的输入)并以表格格式显示输出,并以人类可读的形式显示数值:

PS> $cred = Get-Credential -Credential 'example\administrator'
PS> 'db01','dc01','sp01' | Get-DiskFree -Credential $cred -Format | Format-Table -GroupBy Name -AutoSize

   Name: DB01

Name Vol Size  Used  Avail Use% FS   Type
---- --- ----  ----  ----- ---- --   ----
DB01 C:  39.9G 15.6G 24.3G   39 NTFS Local Fixed Disk
DB01 D:  4.1G  4.1G  0B     100 CDFS CD-ROM Disc


   Name: DC01

Name Vol Size  Used  Avail Use% FS   Type
---- --- ----  ----  ----- ---- --   ----
DC01 C:  39.9G 16.9G 23G     42 NTFS Local Fixed Disk
DC01 D:  3.3G  3.3G  0B     100 CDFS CD-ROM Disc
DC01 Z:  59.7G 16.3G 43.4G   27 NTFS Network Connection


   Name: SP01

Name Vol Size   Used   Avail Use% FS   Type
---- --- ----   ----   ----- ---- --   ----
SP01 C:  39.9G  20G    19.9G   50 NTFS Local Fixed Disk
SP01 D:  722.8M 722.8M 0B     100 UDF  CD-ROM Disc

【讨论】:

  • 我想使用这个功能,但是我的 blogspot 域被屏蔽了。您能否在此处包含该功能?
  • 网页存档上的相同链接:web.archive.org/web/20150614115736/http://…
  • Get-DiskFree 在 PowerShell 2.0 中似乎不可用
  • @MarcelloMiorelli 当然,但至少解释一下代码的作用和工作原理。我看到太多的答案给出了一个最终死掉的链接,使整个答案毫无用处。
  • @Matthieu 是的,你说得对,我也看到过,真的太频繁了
【解决方案5】:

另一种方法是将字符串转换为 WMI 对象:

$size = ([wmi]"\\remotecomputer\root\cimv2:Win32_logicalDisk.DeviceID='c:'").Size
$free = ([wmi]"\\remotecomputer\root\cimv2:Win32_logicalDisk.DeviceID='c:'").FreeSpace

如果您想要不同的单位,也可以将结果除以 1GB 或 1MB:

$disk = ([wmi]"\\remotecomputer\root\cimv2:Win32_logicalDisk.DeviceID='c:'")
"Remotecomputer C: has {0:#.0} GB free of {1:#.0} GB Total" -f ($disk.FreeSpace/1GB),($disk.Size/1GB) | write-output

输出为:Remotecomputer C: has 252.7 GB free of 298.0 GB Total

【讨论】:

【解决方案6】:

我在其他建议中遇到了两个问题

    1) 如果您在任务计划程序下运行 powershell,则不支持驱动器映射
    2) 尝试在远程计算机上使用“get-WmiObject”时可能会遇到 Access is denied 错误(当然取决于您的基础设施设置)

不存在这些问题的替代方法是使用 GetDiskFreeSpaceEx 和 UNC 路径:

function getDiskSpaceInfoUNC($p_UNCpath, $p_unit = 1tb, $p_format = '{0:N1}')
{
    # unit, one of --> 1kb, 1mb, 1gb, 1tb, 1pb
    $l_typeDefinition = @' 
        [DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)] 
        [return: MarshalAs(UnmanagedType.Bool)] 
        public static extern bool GetDiskFreeSpaceEx(string lpDirectoryName, 
            out ulong lpFreeBytesAvailable, 
            out ulong lpTotalNumberOfBytes, 
            out ulong lpTotalNumberOfFreeBytes); 
'@
    $l_type = Add-Type -MemberDefinition $l_typeDefinition -Name Win32Utils -Namespace GetDiskFreeSpaceEx -PassThru

    $freeBytesAvailable     = New-Object System.UInt64 # differs from totalNumberOfFreeBytes when per-user disk quotas are in place
    $totalNumberOfBytes     = New-Object System.UInt64
    $totalNumberOfFreeBytes = New-Object System.UInt64

    $l_result = $l_type::GetDiskFreeSpaceEx($p_UNCpath,([ref]$freeBytesAvailable),([ref]$totalNumberOfBytes),([ref]$totalNumberOfFreeBytes)) 

    $totalBytes     = if($l_result) { $totalNumberOfBytes    /$p_unit } else { '' }
    $totalFreeBytes = if($l_result) { $totalNumberOfFreeBytes/$p_unit } else { '' }

    New-Object PSObject -Property @{
        Success   = $l_result
        Path      = $p_UNCpath
        Total     = $p_format -f $totalBytes
        Free      = $p_format -f $totalFreeBytes
    } 
}

【讨论】:

  • 谢谢,很好的解决方案,但我们有类似的功能来为所有用户获取 UNCpath
  • TaskScheduler 不使用映射驱动器的 PowerShell 方法吗?
【解决方案7】:

命令行:

powershell gwmi Win32_LogicalDisk -ComputerName remotecomputer -Filter "DriveType=3" ^|
select Name, FileSystem,FreeSpace,BlockSize,Size ^| % {$_.BlockSize=
(($_.FreeSpace)/($_.Size))*100;$_.FreeSpace=($_.FreeSpace/1GB);$_.Size=($_.Size/1GB);$_}
^| Format-Table Name, @{n='FS';e={$_.FileSystem}},@{n='Free, Gb';e={'{0:N2}'-f
$_.FreeSpace}}, @{n='Free,%';e={'{0:N2}'-f $_.BlockSize}},@{n='Capacity ,Gb';e={'{0:N3}'
-f $_.Size}} -AutoSize

输出:

Name FS   Free, Gb Free,% Capacity ,Gb

---- --   -------- ------ ------------

C:   NTFS 16,64    3,57   465,752

D:   NTFS 43,63    9,37   465,759

I:   NTFS 437,59   94,02  465,418

N:   NTFS 5,59     0,40   1 397,263

O:   NTFS 8,55     0,96   886,453

P:   NTFS 5,72     0,59   976,562

命令行:

wmic logicaldisk where DriveType="3" get caption, VolumeName, VolumeSerialNumber, Size, FileSystem, FreeSpace

出来:

Caption  FileSystem  FreeSpace     Size           VolumeName  VolumeSerialNumber

C:       NTFS        17864343552   500096991232   S01         EC641C36

D:       NTFS        46842589184   500104687616   VM1         CAF2C258

I:       NTFS        469853536256  499738734592   V8          6267CDCC

N:       NTFS        5998840832    1500299264512  Vm-1500     003169D1

O:       NTFS        9182349312    951821143552   DT01        A8FC194C

P:       NTFS        6147043840    1048575144448  DT02        B80A0F40

命令行:

wmic logicaldisk where Caption="C:" get caption, VolumeName, VolumeSerialNumber, Size, FileSystem, FreeSpace

出来:

Caption  FileSystem  FreeSpace    Size          VolumeName  VolumeSerialNumber

C:       NTFS        17864327168  500096991232  S01         EC641C36

command-line:

dir C:\ /A:DS | find "free"

out:
               4 Dir(s)  17 864 318 976 bytes free

dir C:\ /A:DS /-C | find "free"

out:
               4 Dir(s)     17864318976 bytes free

【讨论】:

  • 这太荒谬了。
  • 为什么要@AlexanderTrauzzi?
  • wmic logicaldisk get size 不考虑保留空间...在 powershell get-volume 返回实际总大小(即减去保留空间),但是当我尝试 get-volume | format-list size 它说总大小加上保留空间......我如何得到总大小减去每个带有powershell的驱动器的保留空间???
【解决方案8】:
Get-PSDrive C | Select-Object @{ E={$_.Used/1GB}; L='Used' }, @{ E={$_.Free/1GB}; L='Free' }

【讨论】:

    【解决方案9】:

    刚刚找到Get-Volume 命令,该命令返回SizeRemaining,因此可以使用(Get-Volume -DriveLetter C).SizeRemaining / (1e+9) 之类的命令查看磁盘C 的剩余Gb。似乎比Get-WmiObject Win32_LogicalDisk 运行得更快。

    【讨论】:

      【解决方案10】:
      PS> Get-CimInstance -ComputerName bobPC win32_logicaldisk | where caption -eq "C:" | foreach-object {write " $($_.caption) $('{0:N2}' -f ($_.Size/1gb)) GB total, $('{0:N2}' -f ($_.FreeSpace/1gb)) GB free "}  
      C: 117.99 GB total, 16.72 GB free 
      
      PS> 
      

      【讨论】:

      • 内森,我回滚了你的编辑。这显示了给定的输出,这对于那些为其结果选择答案的人很有价值。只需一行即可复制和粘贴。
      【解决方案11】:

      我知道psExec工具,你可以从here下载

      工具包中有一个 psinfo.exe。 powershell/cmd中基本用法如下。

      但是你可以有很多选择

      用法:psinfo [[\computer[,computer[,..] | @file [-u 用户 [-p psswd]]] [-h] [-s] [-d] [-c [-t 分隔符]] [过滤器]

      \computer 在远程计算机或指定的计算机上执行命令。如果省略计算机名,则命令在本地系统上运行,如果指定通配符 (\*),则命令在当前域中的所有计算机上运行。

      @file   Run the command on each computer listed in the text file specified.
      -u  Specifies optional user name for login to remote computer.
      -p  Specifies optional password for user name. If you omit this you will be prompted to enter a hidden password.
      -h  Show list of installed hotfixes.
      -s  Show list of installed applications.
      -d  Show disk volume information.
      -c  Print in CSV format.
      -t  The default delimiter for the -c option is a comma, but can be overriden with the specified character.
      

      过滤器 Psinfo 将只显示与过滤器匹配的字段的数据。例如“psinfo service”仅列出服务包字段。

      【讨论】:

        【解决方案12】:

        在 PowerShell 上:

        "FreeSpace C:  " + [math]::Round((Get-Volume -DriveLetter C).SizeRemaining / 1Gb) + " GB"
        

        【讨论】:

          【解决方案13】:

          我使用 Enter-PSsession pcName 远程访问计算机 然后我输入 Get-PSDrive

          这将列出所有已使用和剩余的驱动器和空间。如果您需要查看所有格式化的信息,请将其通过管道传输到 FL,如下所示:Get-PSdrive |佛罗里达州 *

          【讨论】:

            【解决方案14】:

            我创建了这个简单的函数来帮助我。内联 Get-WmiObjectWhere-Object 语句等让我的调用更容易阅读。

            function GetDiskSizeInfo($drive) {
                $diskReport = Get-WmiObject Win32_logicaldisk
                $drive = $diskReport | Where-Object { $_.DeviceID -eq $drive}
            
                $result = @{
                    Size = $drive.Size
                    FreeSpace = $drive.Freespace
                }
                return $result
            }
            
            $diskspace = GetDiskSizeInfo "C:"
            write-host $diskspace.FreeSpace " " $diskspace.Size
            

            【讨论】:

            • OP 是“远程计算机”。这在安装驱动器上对我不起作用,但这可能是我的目的......
            【解决方案15】:

            如果您想要检查多个驱动器号和/或在本地和网络驱动器之间进行过滤,您可以使用 PowerShell 来利用 Win32_LogicalDisk WMI 类。这是一个简单的例子:

            $localVolumes = Get-WMIObject win32_volume;
            
            foreach ($vol in $localVolumes) {
              if ($vol.DriveLetter -ne $null ) {
                $d = $vol.DriveLetter[0];
                if ($vol.DriveType -eq 3) {
                  Write-Host ("Drive " + $d + " is a Local Drive");
                }
                elseif ($vol.DriveType -eq 4) {
                  Write-Host ("Drive" + $d + " is a Network Drive");
                }
                else {
                  // ... and so on
                }
            
                $drive = Get-PSDrive $d;
                Write-Host ("Used space on drive " + $d + ": " + $drive.Used + " bytes. `r`n");
                Write-Host ("Free space on drive " + $d + ": " + $drive.Free + " bytes. `r`n");
              }
            }
            

            我使用上述技术创建了一个 Powershell 脚本,该脚本检查所有驱动器并在它们低于用户定义的配额时发送电子邮件警报。您可以通过我的博客上的this post 获得它。

            【讨论】:

              【解决方案16】:

              PowerShell 乐趣

              Get-WmiObject win32_logicaldisk -Computername <ServerName> -Credential $(get-credential) | Select DeviceID,VolumeName,FreeSpace,Size | where {$_.DeviceID -eq "C:"}
              

              【讨论】:

                猜你喜欢
                • 1970-01-01
                • 2020-05-03
                • 2011-03-13
                • 2011-02-19
                • 2019-12-12
                • 2011-03-28
                • 2010-11-26
                • 1970-01-01
                • 1970-01-01
                相关资源
                最近更新 更多