2

For some reason when I try to use the $scanpath variable after the Get-ChildItem in the below code, it doesnt work. But if I put the actual path in place of $scanpath, it works. What am I doing wrong? Both the $computer and $savepath variables work fine.

$computer = 'Server'
$scanpath = 'P$\Directory\Directory\Z'
$savepath = 'C:\Z-Media.csv'
Invoke-Command -ComputerName $computer -scriptblock {Get-ChildItem $scanpath -recurse -include *.mp3,*.wma,*.wmv,*.mov,*.mpg,*.ogg,*.jpg -force | select FullName, Length | Sort-Object { [long]$_.Length } -descending} | Export-Csv $savepath -NoTypeInformation
2
  • What do you mean by "it doesnt work"? Do you get an error message in PowerShell, can you share what that message is? Commented Feb 6, 2015 at 20:21
  • It just came back with an empty file and no error. Commented Feb 6, 2015 at 20:38

1 Answer 1

3

$scanpath is not in the same scope as the script block. You have 2 ways to fix this:

PowerShell 3+ - The Using Scope Modifier

Invoke-Command -ComputerName $computer -scriptblock {Get-ChildItem $Using:scanpath -recurse}

See about_Scopes for more information.

Using is a special scope modifier that identifies a local variable in a remote command. By default, variables in remote commands are assumed to be defined in the remote session.

Any Version - Parameters

Invoke-Command -ComputerName $computer -scriptblock {param($thisPath) Get-ChildItem $thisPath -recurse} -ArgumentList $scanpath

You can give a script block parameters, just like a function. Invoke-Command takes an -ArgumentList parameter which passes the values into the scriptblock's parameters.

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

1 Comment

$Using:scanpath is what I needed. Thank you!

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.