0

我正在尝试使用 powershell 远程访问计算机并获取文件夹的每个子目录的大小。

我正在使用脚本来获取每个文件夹大小,并且它可以成功运行:

$log = "F:\logfile.txt" 
$startFolder = "C:\"
$colItems = Get-ChildItem $startFolder  | Where-Object {$_.PSIsContainer -eq $True} | Sort-Object
foreach ($i in $colItems){
   $itemSum = Get-ChildItem ("$startFolder\" + $i.Name) -recurse | Measure-Object -property length -sum
   "$startFolder\$i -- " + "{0:N2}" -f ($itemSum.sum / 1MB) + " MB" >> $log
   }

这就是我尝试使用 Invoke-Command 合并它的方式,但它没有产生任何结果。

#login info
$username = "domain\user"
$password = 'password'

$log = "C:\logfile.txt" 
$startFolder = "comp-name\e"

#setup login credentials
$secstr = New-Object -TypeName System.Security.SecureString
$password.ToCharArray() | ForEach-Object {$secstr.AppendChar($_)}
$cred = new-object -typename System.Management.Automation.PSCredential -argumentlist $username, $secstr

$session = new-pssession "comp-name" -Credential $cred

Invoke-Command -Session $session -ScriptBlock {$colItems = Get-ChildItem $startFolder  | Where-Object {$_.PSIsContainer -eq $True} | Sort-Object
foreach ($i in $colItems){
   $itemSum = Get-ChildItem ("$startFolder\" + $i.Name) -recurse | Measure-Object -property length -sum
   "$startFolder\$i -- " + "{0:N2}" -f ($itemSum.sum / 1GB) + " GB" >> $log
   }
   }

我已经完成了在两台计算机上启用 ps-remoting 的步骤。

在此先感谢您的帮助!

4

1 回答 1

0

该变量$startFolder需要传递到脚本块中,例如:

Invoke-Command -Session $session -ScriptBlock {param($path,$log) 
    $colItems = Get-ChildItem $path | Where-Object {$_.PSIsContainer} | Sort-Object
    foreach ($i in $colItems) {
        $itemSum = Get-ChildItem "$path\$($i.Name)" -recurse | Measure-Object -property length -sum
        "$startFolder\$i -- " + "{0:N2}" -f ($itemSum.sum / 1GB) + " GB" >> $log
    }
} -Arg $startFolder,$logFilePath

我能够得到这个工作(没有重定向到日志文件):

23# Invoke-Command acme -ScriptBlock {param($path)
>>>     $colItems = Get-ChildItem $path | Where-Object {$_.PSIsContainer} | Sort-Object
>>>     foreach ($i in $colItems) {
>>>         $itemSum = Get-ChildItem $i.FullName -recurse | Measure-Object -property length -sum
>>>         "$startFolder\$i -- " + "{0:N2}" -f ($itemSum.sum / 1MB) + " MB"
>>>     }
>>> } -Arg c:\bin
>>>
\Orca -- 3.63 MB
\Reg -- 0.06 MB
\Src -- 0.25 MB
\sym -- 19.09 MB
\x64 -- 0.71 MB
于 2014-05-16T04:06:00.480 回答