使用Perl,如何从Windows上的WMIC获取本地磁盘上的可用空间量?

时间:2017-03-03 14:22:16

标签: perl batch-file

我使用bat和perl脚本获取服务器的磁盘使用率。 Bat命令在文件中返回正确的输出,但它是以字节为单位,我试图在perl脚本中将其转换为GB,这在在线IDE上提供正确的输出但在我的服务器上运行时没有,你能告诉我是什么我可能需要检查的其他先决条件,以及下面代码中的其他任何问题。

BAT:

wmic /OUTPUT:D:\advapp\PSMAG\Scripts\DailyOps\result.txt logicaldisk where "DeviceID='C:'" get FreeSpace /format:value

C:\Perl\bin\perl.exe  %PSMAGSCRIPTS%\DailyOps\dailyDiskCheck.pl

的Perl:

# File generated by bat
my $soutput_file = "$sPSMAGSCRIPTS\\DailyOps\\result.txt";
open(SPACEFILE, "$soutput_file") or die "Can't open $soutput_file\n";
my $sLines;
{
    local $/ = undef;
    $sLines = <SPACEFILE>;
    print "file reaD\n";
}
if ( $sLines =~ m/(FreeSpace=.*)/i ) {
    print "" . $1 . "\n"; 
    if ($1 =~ m/FreeSpace=(\d+)/) {
        my $var = $1;
        $var /= 1073741824;
        print "FreeSpace is:$var GBs \n";
    }
    close(SPACEFILE);
}
else {
    print "no match";
}

我得到的输出:

文件记录

不匹配

3 个答案:

答案 0 :(得分:1)

问题是Windows经常以自己的UTF-16变体编写文本文件,并且在将数据用作字符之前需要对其进行解码。如果您使用

open SPACEFILE, '<:encoding(UTF-16)', $soutput_file

然后你会看到你期望的字符

我建议从Perl程序运行wmic命令。 如果让wmic将其输出发送到STDOUT,那么它将在ISO-8859-1中,并且大部分都不需要解码。您可以使用open

通过管道读取命令的输出

这样您只需要运行Perl程序,也不需要批处理文件

喜欢这个

use strict;
use warnings 'all';

use constant GB => 1024 * 1024 * 1024;

my $sLines = do {
    open my $fh, '-|', q{wmic logicaldisk where "DeviceID='C:'" get FreeSpace /format:value};
    local $/;
    <$fh>;
};
print "File read\n";

if ( $sLines =~ /(FreeSpace=(\d+))/i ) {

    print "$1\n";

    my $bytes = $2;
    printf "FreeSpace is: %.2fGB\n", $bytes / GB;
}
else {
    print "no match";
}

输出

File read
FreeSpace=10210951168
FreeSpace is: 9.51GB

答案 1 :(得分:1)

我会绕过批处理文件:

#!/usr/bin/env perl

use strict;
use warnings;

use Number::Bytes::Human qw( format_bytes );

my $bytes_free = (split ' ', `wmic logicaldisk where "DeviceID='C:'" get FreeSpace`)[1];

# Pretty print it (not really necessary)
print format_bytes( $bytes_free ), "\n";

输出:

C:\> perl tt.pl
1.5T

答案 2 :(得分:0)

你不需要Perl这样做;您可以在批处理文件中完成所有操作。

@echo off
setlocal EnableDelayedExpansion

wmic /OUTPUT:result.txt logicaldisk where "DeviceID='C:'" get FreeSpace /format:value
for /F %%a in ('type result.txt') do set "%%a"

echo FreeSpace = %FreeSpace% Bytes

set "group[1]=00000000%FreeSpace:~-9%"
set /A n=1, group[1]=1%FreeSpace:~-9% %% 1000000000
set "group[2]=%FreeSpace:~0,-9%"
if defined group[2] set "n=2"
set /A bin10=0, carry=0, bitPos=0
:nextBit
   for /L %%i in (%n%,-1,1) do set /A term=carry*1000000000+group[%%i], group[%%i]=term/2, carry=term%%2
   set /A "bin10[%bin10%]+=carry<<bitPos, carry=0, bitPos+=1"
   if %bitPos% equ 10 set /A bin10+=1, bitPos=0
   if !group[%n%]! equ 0 set /A n-=1
if %n% gtr 0 goto nextBit
set /A Int=bin10[3], Frac=100+bin10[2]*100/1024

echo FreeSpace = %Int%.%Frac:~-2% GigaBytes

输出示例:

FreeSpace = 405032046592 Bytes
FreeSpace = 377.21 GigaBytes