2

Below PowerShell script should measure folder sizes on remote computers but apparently my $Desktop variable value is somehow ignored by Get-ChildItem and I get 0.00 MB. But when I replace $Desktop with explicit string i.e. "C:\Users\user1\Desktop" it works alright and I get e.g. 10.MB. Am I doing something wrong?

$file1="C:\computers_users.csv"
import-csv $file1 | ForEach-Object{
  $Desktop = "C:\Users\$($_.user)\Desktop"      
  Invoke-Command -ComputerName $_.computer -ScriptBlock {
    $FldSize =(Get-ChildItem $Desktop -recurse | Measure-Object -property length -sum)
    "{0:N2}" -f ($FldSize.sum / 1MB) + " MB"}
}

2 Answers 2

2

try this:

Invoke-Command -ComputerName $_.computer -ScriptBlock {
    $FldSize =(Get-ChildItem $args[0] -recurse | Measure-Object -property length -sum)
    "{0:N2}" -f ($FldSize.sum / 1MB) + " MB"} -argumentlist $desktop

You need to pass the argument with -argumentlist because the invoke-command create a new powershell session not aware of calling session variables.

Sign up to request clarification or add additional context in comments.

1 Comment

Worked! Thanks for explaining that to me. Now, it's gonna resolve other dilemma as well. Much appreciated.
2

On a side note, in PowerShell 3.0 you'll be can use $using to pass local variables and to the remote machine:

Invoke-Command ... -ScriptBlock { $FldSize =(Get-ChildItem $using:Desktop ...

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.