繁体   English   中英

Powershell使用调用命令会话来获取远程计算机上的子代大小

[英]Powershell Use Invoke-Command Session to Get-Childitem sizes on a remote computer

我正在尝试使用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的步骤。

先谢谢您的帮助!

需要将变量$startFolder传递到$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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM