원격 컴퓨터의 디스크 용량 및 여유 공간을 얻는 방법
다음과 같은 라인이 있습니다.
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
.
편집 : 수치만 추출해서 변수에 저장하면 됩니다.
훨씬 간단한 솔루션:
Get-PSDrive C | Select-Object Used,Free
컴퓨터의 경우 원격 컴퓨터의 경우)Powershell Remoting
)
Invoke-Command -ComputerName SRV2 {Get-PSDrive C} | Select-Object PSComputerName,Used,Free
$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
Enter-PSession-Computername ServerName을 수행하여 원격 서버에서 이 명령을 사용한 다음 Get-PSDrive를 실행하면 서버에서 실행한 것처럼 데이터가 풀립니다.
제가 얼마 전에 여러 컴퓨터를 쿼리할 수 있는 PowerShell 고급 함수(스크립트 cmdlet)를 만들었습니다.
이 함수의 코드는 100줄이 조금 넘으므로 여기에서 찾을 수 있습니다: PowerShell 버전의 df 명령
예를 보려면 사용 섹션을 확인하십시오.다음 사용 예에서는 원격 시스템 집합(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
다른 제안과 관련하여 두 가지 문제가 발생했습니다.
-
작업 스케줄러에서 전원 셸을 실행하는 경우 드라이브 매핑이 지원되지 않습니다.
-
받을 수 있습니다.원격 컴퓨터에서 "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
}
}
Get-PSDrive C | Select-Object @{ E={$_.Used/1GB}; L='Used' }, @{ E={$_.Free/1GB}; L='Free' }
명령줄:
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-Volume 명령을 찾았습니다. 이 명령은SizeRemaining
그니까 뭐그거 런러 거런 ▁like그▁so 같은 것.(Get-Volume -DriveLetter C).SizeRemaining / (1e+9)
디스크 C의 남은 GB를 확인하는 데 사용할 수 있습니다.보다 빠르게 작동하는 것 같습니다.Get-WmiObject Win32_LogicalDisk
.
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>
PowerShell의 경우:
"FreeSpace C: " + [math]::Round((Get-Volume -DriveLetter C).SizeRemaining / 1Gb) + " GB"
여기서 다운로드할 수 있는 psExec 도구에 대해 알고 있습니다.
도구 패키지에서 psinfo.exe가 나옵니다.기본적인 용도는 powershell/cmd에서 다음과 같습니다.
하지만 당신은 그것과 함께 많은 선택권을 가질 수 있습니다.
용도: psinfo [\computer[, computer[, computer] | @file [-u user [-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.
filter Psinfo는 필터와 일치하는 필드에 대한 데이터만 표시합니다. 예를 들어 "psinfo service"는 서비스 팩 필드만 나열합니다.
Enter-PSession pcName을 사용하여 컴퓨터에 원격으로 들어간 다음 Get-PSDrive를 입력합니다.
사용된 드라이브와 남은 공간이 모두 나열됩니다.모든 정보를 확인해야 할 경우 다음과 같이 FL에 파이프로 연결합니다. Get-PS drive | FL *
저는 저를 돕기 위해 이 간단한 기능을 만들었습니다.이를 통해 인라인 Get-WmiObject, Where-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
로컬 드라이브와 네트워크 드라이브 간에 여러 드라이브 문자를 확인하거나 필터링하려는 경우 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 스크립트를 만들었습니다.당신은 제 블로그에 있는 이 게시물에서 그것을 얻을 수 있습니다.
PowerShell 재미
Get-WmiObject win32_logicaldisk -Computername <ServerName> -Credential $(get-credential) | Select DeviceID,VolumeName,FreeSpace,Size | where {$_.DeviceID -eq "C:"}
"FreeSpace C: {0:n3} GB" -f ((Get-Volume -DriveLetter C).SizeRemaining / 1Gb)
언급URL : https://stackoverflow.com/questions/12159341/how-to-get-disk-capacity-and-free-space-of-remote-computer
'programing' 카테고리의 다른 글
os.path.join에 대한 Pathlib 대안이 있습니까? (0) | 2023.05.14 |
---|---|
wpf에서 사용자 지정 윈도우 크롬을 만드는 방법은 무엇입니까? (0) | 2023.05.14 |
.Net이 잘못된 참조 어셈블리 버전을 선택합니다. (0) | 2023.05.09 |
Excel에서 셀 참조가 있는 테이블을 정렬하려면 어떻게 해야 합니까? (0) | 2023.05.09 |
Azure Container 인스턴스와 Web App for Container의 차이점은 무엇입니까? (0) | 2023.05.09 |