我们如何使用PowerShell脚本获取KB文件的大小?

时间:2016-06-27 11:45:52

标签: powershell

我试过$filesize=(($fileXP).length/1KB)  但是这不能找到正确的答案。 至于我的理解,它只是将文件中的字符数除以KB并给出错误的答案。

必须有一些函数或属性来直接定义大小,并根据需要以KB或MB或GB显示。

3 个答案:

答案 0 :(得分:2)

以KB为单位获取文件大小:

Get-ChildItem | % {[int]($_.length / 1kb)}

或者向上舍入到最近的KB:

Get-ChildItem | % {[math]::ceiling($_.length / 1kb)}

获取数字字符:

Get-ChildItem | % {(Get-Content $_.FullName).length}

比较输出,您会看到Get-Childitem的长度以KB为单位。

答案 1 :(得分:0)

首先:

Get-Item -Path 'C:\Windows\notepad.exe' | Select -Property Name, Length | Foreach {
    #if($_.('Name').Trim() -eq "notepad.exe") {
        $FileSize = $_.Length
    #}
};

哇...直接显示为我们想要的 KB、MB 或 GB?我还没有见过提供如此深入信息的 COM 函数。这是我看到的限制,运行这个:

<#The word 'Properties'/'Сво&йства'(ru) should be here, for the English version of#> 
<#Windows with "&" somewere. What is shown when the right mouse button#> 
<#to file/folder is pressed#>
$itemName = 'Сво&йства';
$fullPath='C:\Windows';
$o = new-object -com Shell.Application;
$folder = $o.NameSpace((Split-Path -Path $fullPath));
$file = $folder.ParseName((Split-Path -Leaf $fullPath));
$file.Verbs() | foreach ({
    if($_.Name -eq $itemName){$_.DoIt()}
});

由于Powershell和WMIC一样的来源,数据都是以字节为单位发送的,所以我认为解决的办法可能是破解一些dll文件,嗯……或者完全重复微软获取信息的逻辑这种类型?

如果我错了,我真的很喜欢。这将简化我过去的一些可执行代码决策。

答案 2 :(得分:-2)

CLS

$filenames=Get-Content "C:\temp\files\files-to-watch-size.txt" **#Reading the names of the files to test the existance and size of the file, name of fles with full path in each line e.g. C:\test.txt**
foreach ($filename in $filenames) 
{

if (Test-Path $filename) { (Get-Item $filename).length -gt 0kb **#Returns TRUE if size is greater than zero KB**
$size=(Get-Item $filename).length/1024  **#Getting the File size in KB**
Write-Host "$filename is $size KB" } **# display the name of the file and its size in KB**
}