원격 컴퓨터의 디스크 용량과 여유 공간을 얻는 방법
이 한 줄짜리가 있습니다.
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 :
어떻게받을 수 있나요 Freespace
과 Size
의 DeviceID
C:
? 다른 정보없이이 두 값만 추출해야합니다. Select
cmdlet으로 시도했지만 효과가 없습니다.
편집 : 숫자 값만 추출하여 변수에 저장해야합니다.
$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}
훨씬 더 간단한 솔루션 :
Get-PSDrive C | Select-Object Used,Free
및 원격 컴퓨터 용 (필요 Powershell Remoting
)
Invoke-Command -ComputerName SRV2 {Get-PSDrive C} | Select-Object PSComputerName,Used,Free
단 하나의 명령으로 간단하고 깔끔하지만 이것은 로컬 디스크에서만 작동합니다.
Get-PSDrive
Enter-PSSession -Computername ServerName을 수행하여 원격 서버에서이 명령을 계속 사용할 수 있으며 Get-PSDrive를 실행하면 마치 서버에서 실행 한 것처럼 데이터를 가져옵니다.
이전에 여러 컴퓨터를 쿼리 할 수있는 PowerShell 고급 기능 (스크립트 cmdlet)을 만들었습니다.
함수의 코드는 100 줄이 조금 넘으므로 여기에서 찾을 수 있습니다. df 명령의 PowerShell 버전
예제 는 사용법 섹션을 확인하십시오 . 다음 사용 예제는 원격 컴퓨터 집합 (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
또 다른 방법은 문자열을 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
다른 제안과 함께 두 가지 문제가 발생했습니다.
-
1) 작업 스케줄러에서 powershell을 실행하면 드라이브 매핑이 지원되지 않습니다.
-
2) 원격 컴퓨터에서 "get-WmiObject"를 사용하려고 하면
액세스 거부 오류가 발생할 수 있습니다 (물론 인프라 설정에 따라 다름).
이러한 문제가 발생하지 않는 대안 은 UNC 경로와 함께 GetDiskFreeSpaceEx 를 사용 하는 것입니다.
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
}
}
명령 줄 :
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
Get-PSDrive C | Select-Object @{ E={$_.Used/1GB}; L='Used' }, @{ E={$_.Free/1GB}; L='Free' }
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>
여기 에서 다운로드 할 수있는 psExec 도구를 알고 있습니다.
도구 패키지에서 psinfo.exe가 제공됩니다. powershell / cmd에서 기본적인 사용법은 다음과 같습니다.
그러나 당신은 그것으로 많은 옵션을 가질 수 있습니다
사용법 : psinfo [[\ computer [, computer [, ..] | @file [-u 사용자 [-p psswd]]] [-h] [-s] [-d] [-c [-t 구분 기호]] [필터]
\computer Perform the command on the remote computer or computers specified. If you omit the computer name the command runs on the local system, and if you specify a wildcard (\*), the command runs on all computers in the current domain.
@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 will only show data for the field matching the filter. e.g. "psinfo service" lists only the service pack field.
I remote into the computer using Enter-PSsession pcName then I type Get-PSDrive
That will list all drives and space used and remaining. If you need to see all the info formated, pipe it to FL like this: Get-PSdrive | FL *
I created this simple function to help me. This makes my calls a lot easier to read that having inline an Get-WmiObject, Where-Object statements, 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
In case you want to check multiple drive letters and/or filter between local and network drives, you can use PowerShell to take advantage of the Win32_LogicalDisk WMI class. Here's a quick example:
$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");
}
}
I used the above technique to create a Powershell script that checks all drives and send an e-mail alert whenever they go below a user-defined quota. You can get it from this post on my blog.
'developer tip' 카테고리의 다른 글
NestedScrollView의 ViewPager (0) | 2020.08.21 |
---|---|
jquery.validate.unobtrusive가 동적 주입 요소와 함께 작동하지 않습니다. (0) | 2020.08.21 |
Intellij IDEA가 충돌하여 이제 오류가 발생합니다. (0) | 2020.08.21 |
자바에서 부울 배열 초기화 (0) | 2020.08.21 |
Android에서 현재 요일을 가져 오는 가장 쉬운 방법은 무엇입니까? (0) | 2020.08.21 |