简体   繁体   中英

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

I am trying to use powershell to remotely access a computer and get the size of each sub-directory of a folder.

I am using the script to get each of the folder sizes and it works successfully:

$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
   }

This is how I tried to incorporate it using the Invoke-Command and it is yielding no results.

#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
   }
   }

I have already done the step of enabling ps-remoting on both computers.

Thanks in advance for the help!

The variable $startFolder needs to be passed into the scriptblock eg:

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

I was able to get this working (no redirect to log file):

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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