簡體   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