Joey
Joey

Reputation: 511

Powershell using Invoke-Command and Get-Childitem not delivering content

I am using Powershell 4.0 on a remote computer (rem_comp) to access another one (loc_comp; Powershell 2.0 installed here) in order to get the number of files listed without folders:

$var1 = 'H:\scripts'
Invoke-Command -Computername loc_comp -scriptblock {(Get-Childitem $var1 -recurse | Where-Object {!$_.PSIsContainer}).count}

However when using $var1 inside -scriptblock, it does not deliver anything (neither any error message).

When using

$var1 = 'H:\scripts'
Invoke-Command -Computername loc_comp -scriptblock {(Get-Childitem $ -recurse | Where-Object {!$_.PSIsContainer}).count}

it works!

Note: Changing var1 from ' to " does not help.

Running the command without Invoke-Command locally faces the same problem.

How to fix this?

Upvotes: 1

Views: 6368

Answers (2)

mklement0
mklement0

Reputation: 438083

To complement CmdrTchort's helpful answer:

PS v3 introduced the special using: scope, which allows direct use of local variables in script blocks sent to remote machines (e.g., $using:var1).
This should work for you, because the machine you're running Invoke-Command on has v4.

$var1 = 'H:\scripts'
Invoke-Command -Computername loc_comp -scriptblock `
  { (Get-Childitem $using:var1 -recurse | Where-Object {!$_.PSIsContainer}).count }

Note that using: only works when Invoke-Command actually targets a remote machine.

Upvotes: 2

Harald F.
Harald F.

Reputation: 4773

When you're using Invoke-command and a script-block , the scriptblock cannot access your params from the outer scope (scoping rules).

You can however, define the params and pass them along with the -Argumentlist

Example:

 Invoke-Command -ComputerName "localhost" {param($Param1=$False, $Param2=$False) Write-host "$param1 $param2" } -ArgumentList $False,$True

The following should work for your example:

Invoke-Command -Computername loc_comp -scriptblock {param($var1)(Get-Childitem $var1 -recurse | Where-Object {!$_.PSIsContainer}).count} -ArgumentList $var1

Upvotes: 1

Related Questions