Cómo obtener capacidad de disco y espacio libre de la computadora remota
Tengo esta línea:
get-WmiObject win32_logicaldisk -Computername remotecomputer
Y la salida es la siguiente:
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 :
¿Cómo obtengo Freespace
y Size
de DeviceID
C:
? Necesito extraer solo estos dos valores sin otras informaciones. Lo he probado con cmdlet Select
, pero sin ningún efecto.
Editar: Necesito extraer los valores numéricos solamente y almacenarlos en variables.
13 answers
$disk = Get-WmiObject Win32_LogicalDisk -ComputerName remotecomputer -Filter "DeviceID='C:'" |
Select-Object Size,FreeSpace
$disk.Size
$disk.FreeSpace
Para extraer solo los valores y asignarlos a una variable:
$disk = Get-WmiObject Win32_LogicalDisk -ComputerName remotecomputer -Filter "DeviceID='C:'" |
Foreach-Object {$_.Size,$_.FreeSpace}
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-08-28 12:56:35
Solución mucho más simple:
Get-PSDrive C | Select-Object Used,Free
Y para ordenadores remotos (necesidades Powershell Remoting
)
Invoke-Command -ComputerName SRV2 {Get-PSDrive C} | Select-Object PSComputerName,Used,Free
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-06-14 12:29:46
Hace un tiempo creé una función avanzada de PowerShell (cmdlet script) que permite consultar varios equipos.
El código de la función tiene un poco más de 100 líneas, así que lo puedes encontrar aquí: Versión de PowerShell del comando df
Echa un vistazo a la sección Usage para ver ejemplos. El siguiente ejemplo de uso consulta un conjunto de equipos remotos (entrada de la canalización de PowerShell) y muestra la salida en un formato de tabla con valores numéricos en forma legible por humanos:
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
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-08-10 05:14:49
Solo un comando simple dulce y limpio, pero esto solo funciona para discos locales
Get-PSDrive
Todavía podría usar este comando en un servidor remoto haciendo un Enter-PSSession-Computername ServerName y luego ejecutar el Get-PSDrive obtendrá los datos como si los ejecutara desde el servidor.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-06-22 19:51:06
Otra forma es lanzar una cadena a un objeto WMI:
$size = ([wmi]"\\remotecomputer\root\cimv2:Win32_logicalDisk.DeviceID='c:'").Size
$free = ([wmi]"\\remotecomputer\root\cimv2:Win32_logicalDisk.DeviceID='c:'").FreeSpace
También puedes dividir los resultados por 1GB o 1MB si quieres diferentes unidades:
$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
La salida es: Remotecomputer C: has 252.7 GB free of 298.0 GB Total
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-09-17 21:19:03
Hay dos problemas que encontré con las otras sugerencias
-
1) Las asignaciones de unidades no son compatibles si ejecuta powershell en el programador de tareas
-
2) Puede obtener Acceso denegado errores errores al intentar usar "get-WmiObject" en equipos remotos (dependiendo de la configuración de la infraestructura, por supuesto)
La alternativa que no sufre de estos problemas es usar GetDiskFreeSpaceEx con una ruta 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
}
}
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-02-02 16:24:47
Línea de comandos:
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
Salida:
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
Línea de comandos:
wmic logicaldisk where DriveType="3" get caption, VolumeName, VolumeSerialNumber, Size, FileSystem, FreeSpace
Fuera:
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
Línea de comandos:
wmic logicaldisk where Caption="C:" get caption, VolumeName, VolumeSerialNumber, Size, FileSystem, FreeSpace
Fuera:
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
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-03-04 22:24:47
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>
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-05-08 01:45:35
Conozco herramientas PsExec que puedes descargar desde aquí
Viene un psinfo.exe del paquete de herramientas. El uso básico se realiza de la siguiente manera en powershell/cmd.
Sin embargo, usted podría tener un montón de opciones con él
Uso: psinfo [[\computer [, computer [,..] / @ file [- u usuario [-p psswd]]] [- h] [- s] [- d] [- c [- t delimiter]] [filter]
\ computer Ejecute el comando en el equipo o equipos remotos indicado. Si omite el nombre del equipo, el comando se ejecuta en el sistema local y si especifica un comodín (\*), el comando se ejecuta en todos los equipos del dominio actual.
@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.
Filter Psinfo solo mostrará los datos del campo que coincida con el filtro. por ejemplo, "psinfo service" solo muestra el campo service pack.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-10-04 05:46:24
Get-PSDrive C | Select-Object @{ E={$_.Used/1GB}; L='Used' }, @{ E={$_.Free/1GB}; L='Free' }
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-12-14 19:34:35
I remote into the computer using Enter-PSSession pcName entonces escribo Get-PSDrive
Que enumerará todas las unidades y el espacio utilizado y restante. Si necesita ver toda la información formateada, pipe it to FL de esta manera: Get-PSDrive / FL *
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-06-15 13:58:57
He creado esta sencilla función para ayudarme. Esto hace que mis llamadas sean mucho más fáciles de leer que tener en línea un Get-WmiObject, Instrucciones Where-Object , etc.
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
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-03-04 22:26:47
En caso de que desee comprobar varias letras de unidad y/o filtrar entre unidades locales y de red, puede utilizar PowerShell para aprovechar la clase Win32_LogicalDisk WMI. He aquí un ejemplo rápido:
$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");
}
}
Utilicé la técnica anterior para crear un script de Powershell que comprueba todas las unidades y envía una alerta de correo electrónico cada vez que van por debajo de una cuota definida por el usuario. Puedes obtenerlo de aquí .
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-08-31 14:19:44