10

I have folder c:\test where I have three files: “file1”, “file2”, “file3”

Following script:

$remoteSession = New-PSSession -ComputerName localhost
$folder = "c:\test"
$exclude =@("c:\test\file1","c:\test\file2")

Invoke-Command -Session $remoteSession -ScriptBlock {    
    #$Using:exclude
    Get-ChildItem -Path $Using:folder -recurse | Where {$Using:exclude -notcontains $_.FullName}
}

Remove-PSSession $remoteSession 

Gives the result: Picture 1

However, if I uncomment “$Using:exclude” I get the result: enter image description here

Suddenly exclude list starts working properly

2
  • I get: New-PSSession : [localhost] Beim Verbinden mit dem Remoteserver "localhost" ist folgender Fehler aufgetreten: Zugriff verweigert Commented May 14, 2020 at 5:17
  • ok, I have to be Administrator to start a pssession. Another issue: where do you uncomment, it is already uncommented. Commented May 14, 2020 at 5:28

1 Answer 1

21

Just specifying $Using:exclude in the Where-Object cmdlet doesn't work because it is in a nested scriptblock.

In your case , the Using:folder works because it is a local variable directly passed to the Invoke-Command scriptblock.

But "Using:exclude is passed to a scriptblock for Where-Object, which is itself nested inside the scriptblock for Invoke-Command.

$Using allows to pass local variables to scriptblocks only one level deep, not to scriptblocks nested any further. This behaviour is not specific to the Where-Object scriptblock, any cmdlet which has a parameter taking a scriptblock behaves like this when it is inside a Invoke-Command scriptblock.

Unfortunately, I don't think this behaviour is documented.

By uncommenting $Using:exclude at the beginning of the Invoke-Command scriptblock, you are effectively declaring the variable $exclude inside the remote session. So, in this case, $exclude becomes a local variable inside the Invoke-Command scriptblock and can be passed one level further, to the nested Where-Object scriptblock.

That's why it works when you uncomment $Using:exclude at the beginning of the Invoke-Command scriptblock, it's a workaround for the behaviour of $Using.

For the official help information about this run :

Get-Help about_remote_variables -Full
Sign up to request clarification or add additional context in comments.

3 Comments

see my answer to this post :)
In your answer you "$using:" the two variables in the outermost scope of the remoted scriptblock, which allows them to be passed into the & scriptblocks. @Mathieu explained this well, I think.
In my case I get all three files when uncommenting $Using:exclude

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.