使用PowerShell进行RoboCopy目录大小调整

时间:2017-05-31 20:50:52

标签: powershell directory size subdirectory robocopy

我正在尝试仅获取根文件夹中的子目录的报告。尝试这样做时,我收到两个错误。

You cannot call a method on a null-valued expression.
At line:5 char:1
+ $fldSize = (robocopy $DIR "NO" /e /l /r:0 /w:0 /nfl /ndl /nc /fp /np  ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (:) [], RuntimeException
    + FullyQualifiedErrorId : InvokeMethodOnNull

Method invocation failed because [System.IO.DirectoryInfo] does not contain a method named 'op_Addition'.
At line:6 char:1
+ $DIR + " = " + "{0:N2}" -f ($fldSize / 1MB) + " MB"
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (op_Addition:String) [], RuntimeException
    + FullyQualifiedErrorId : MethodNotFound

我已经做了一些寻找,我发现的似乎表明阵列问题,但是到目前为止我没有尝试过任何不同的结果。脚本在下面。

function get_dir ($SDIR){
$colItems = Get-ChildItem $SDIR -Directory
foreach ($DIR in $colItems)
{
$fldSize = (robocopy $DIR "NO" /e /l /r:0 /w:0 /nfl /ndl /nc /fp /np /njh /xj /bytes| ? {$_ -match "Bytes :"}).trim().split(" ")[2]
$DIR + " = " + "{0:N2}" -f ($fldSize / 1MB) + " MB"
}
}


get_dir C:\TEST\

1 个答案:

答案 0 :(得分:0)

问题是您需要使用$DIR.fullname因为$colitems中的每个元素都属于DirectoryInfo类型,并且您不能将其视为字符串来创建结果,就像您在robocopy之后的代码行。

这是一个固定版本

function get_dir ($SDIR)
{
    $colItems = Get-ChildItem $SDIR -Directory
    foreach ($DIR in $colItems)
    {
        $fldSize = (robocopy $DIR.fullname "NO" /e /l /r:0 /w:0 /nfl /ndl /nc /fp /np /njh /xj /bytes| ? {$_ -match "Bytes :"}).trim().split(" ")[2]
        $DIR.fullname + " = " + ("{0:N2}" -f ($fldSize / 1MB) + " MB")
    }
}