[enter-pssession + get-childitem] Difference in behaviour when run in script vs run in terminal.

Question

In the terminal if I do the following:

enter-pssession $server -credential $creds
$folderList = get-childitem "C:\Users" -directory | select name

I get a list of folders in "C:\Users" on the remote machine

However if I put the above in a script, $folderList contains a list of folders on the local machine.

So it seems enter-pssession doesn't work in a script. How does one go about doing the above in a script?

Posted Aug 24, 2020, 11:15 PM UTC

72
jborean93•

Enter-PSSession is designed for an interactive console and won't work in a script. You should be using Invoke-Command if you want to run something remotely. In your case it would be

$folderList = Invoke-Command $server -Credential $creds -ScriptBlock {
    get-childitem "C:\Users" -directory | select name
}

Also it seems like you want to do | Select-Object -ExpandProperty Name after your Get-ChildItem call. When you use -ExpandProperty you are getting that property value and not a PSCustomObject with the property(ies) that you have specified.

7
Sys_manOP•

Awesome thanks!

2