0

I am trying to run a piece of remote code using powershell remoting and getting some strange behavior which I am unable to explain. This is the sequence of commands I run.

$sb1 = {$r1 = 1; $r2 = 2; $r3 = Get-Culture; return $r3}
$sb2 = {1; 2; $r3 = Get-Culture; return $r3}

$session = New-PSSession -ComputerName $comp -Credential $creds

$ret1 = Invoke-Command -Session $Session -ScriptBlock $sb1
$ret2 = Invoke-Command -Session $Session -ScriptBlock $sb2

$ret1
>>> en-US
$ret2
>>> 1

Does anyone know a reason for this behavior? I find it very odd. The return statement is ignored, and the scriptblock is evaluated to the first 'uncaptured' expression. Hmmm?

Also, if I did want this block to always evaluate to the return statement, or even the last statement, does anyone know how I might accomplish that?

spervez
  • 33
  • 4

1 Answers1

0

The entire script block is executed and the results are returned. $ret2 will contain three answers. The first is "1", the second is "2" and the third is the output of Get-Culture. You can explore these by looking at $ret2[0], $ret2[1], and $ret[2]. You can find out how many results are returned with $ret2.count.

Below shows everything in $ret2 on my computer.

PS C:\Users\user\Documents\PowerShell> $ret2 | select * | fl
@{PSComputerName=MyComputer; RunspaceId=b9568f5d-88a0-4346-be1a-827b8ba2f29d; PSShowComputerName=True}
@{PSComputerName=MyComputer; RunspaceId=b9568f5d-88a0-4346-be1a-827b8ba2f29d; PSShowComputerName=True}


PSComputerName                 : MyComputer
RunspaceId                     : b9568f5d-88a0-4346-be1a-827b8ba2f29d
Parent                         : en
LCID                           : 1033
KeyboardLayoutId               : 1033
Name                           : en-US
IetfLanguageTag                : en-US
DisplayName                    : English (United States)
NativeName                     : English (United States)
EnglishName                    : English (United States)
TwoLetterISOLanguageName       : en
ThreeLetterISOLanguageName     : eng
ThreeLetterWindowsLanguageName : ENU
CompareInfo                    : CompareInfo - en-US
TextInfo                       : TextInfo - en-US
IsNeutralCulture               : False
CultureTypes                   : SpecificCultures, InstalledWin32Cultures, FrameworkCultures
NumberFormat                   : System.Globalization.NumberFormatInfo
DateTimeFormat                 : System.Globalization.DateTimeFormatInfo
Calendar                       : System.Globalization.GregorianCalendar
OptionalCalendars              : {System.Globalization.GregorianCalendar, System.Globalization.GregorianCalendar}
UseUserOverride                : True
IsReadOnly                     : False
stevlars
  • 96
  • 10