Windows下powershell获取指定文件夹和文件大小

Sela ·
更新时间:2024-09-20
· 756 次阅读

将以下脚本命名为test.ps1, 并在powershell下运行.\test.ps1即可。

#list all folder and file size of specific filepath folder
function filesize ([string]$filepath)
{
    if ($filepath -eq $null)
    {
        throw "file path cannot be blank"
    }
    $_.name + "file	size(MB)" -f $l | Out-File ($filepath+"test.txt")
    dir -Path $filepath |
    ForEach-Object -Process {
        if ($_.psiscontainer -eq $true)
        {#folder size
            $length = 0
            dir -Path $_.fullname -Recurse | ForEach-Object{
                $length += $_.Length
            }
            $l = $length/1MB
            # output to the console
            $_.name + "folder size is: {0:n2} MB" -f $l
            # save to test.txt file
            $_.name + "	{0:n2}" -f $l | Out-File -Append ($filepath+"_test.txt")
        }else
        {#file size
            $length = 0
            dir -Path $_.fullname -Recurse | ForEach-Object{
                $length += $_.Length
            }
            $l = $length
            $_.name + " file size is: {0:n2} B" -f $l
            $_.name + "	{0:n2}" -f $l | Out-File -Append ($filepath+"_test.txt")
        }
    }
}
filesize -filepath "C:\Program File"

如果是第一次运行需要开启执行脚本权限。
在powershell中运行如下命令,然后 Y 确认。
开启:set-executionpolicy remotesigned
关闭:Set-ExecutionPolicy Restricted


作者:ShoneX98



windows PowerShell

需要 登录 后方可回复, 如果你还没有账号请 注册新账号
相关文章