Home > Enterprise >  Powershell Get-Childitem in ISE
Powershell Get-Childitem in ISE

Time:11-03

please can you help me. I'm missing some information.

Why when I execute the code:

Invoke-Command -ComputerName domainpc -ScriptBlock {Get-ChildItem -path C:\Users -Filter "username1"} 

the result is: username1

And when I execute this script:

    $user = Read-Host "Please enter username"
Invoke-Command -ComputerName domainpc -ScriptBlock {Get-ChildItem -path C:\Users -Filter "$user"} 

the result is a list of folder contained in C:\Users

I don't understand why executing script get different results than execute code without variable. Seems that the problem is the variable. Please can you explain this?

Thanks.

CodePudding user response:

You are hitting scope "problems".
The variable $user inside your script block -ScriptBlock is not known.
Take a look here: https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_remote_variables?view=powershell-7.1#using-local-variables

Use $Using:user to get around.

  • Related