Robo
Robo

Reputation: 23

PowerShell: string variable ignored by Get-ChildItem

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

Upvotes: 2

Views: 1061

Answers (2)

Shay Levy
Shay Levy

Reputation: 126722

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 ...

Upvotes: 2

CB.
CB.

Reputation: 60910

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.

Upvotes: 2

Related Questions