r.piesnikowski
r.piesnikowski

Reputation: 2961

Powershell variable initialization affect function return?

Today I've found very strange behaviour which for me doesn't have any logic. In my one machine this code works as I expected but in two more machines I reproduce

function Set-XXX {param([String] $variableName) 
    [string]$vw;
    $vw = $variableName;
    return $vw;
}

When I execute this function I've strange result as Object[] not as I expected like string.

PS C:\Users\Robert> $ve = Set-XXX -variableName "eeee"
PS C:\Users\Robert> $ve.GetType()
IsPublic IsSerial Name                                     BaseType
-------- -------- ----                                     --------
True     True     Object[]                                 System.Array
PS C:\Users\Robert> $ve[0]
PS C:\Users\Robert> $ve[1]
eeee

When I set $vw with empty string: [string]$vw = '' resulting type is string and there is no problem. Can anybody explain me why this happen?

PS C:\Users\Robert> function Set-XXX {param([String] $variableName)
>>     [string]$vw= '';
>>     $vw = $variableName;
>>     return $vw;
>> }
PS C:\Users\Robert> $vex = Set-XXX -variableName "eeee"
PS C:\Users\Robert> $vex
eeee
PS C:\Users\Robert> $vex.GetType()

IsPublic IsSerial Name                                     BaseType
-------- -------- ----                                     --------
True     True     String                                   System.Object


PS C:\Users\Robert> $PSVersionTable

Name                           Value
----                           -----
PSVersion                      5.1.19041.546
PSEdition                      Desktop
PSCompatibleVersions           {1.0, 2.0, 3.0, 4.0...}
BuildVersion                   10.0.19041.546
CLRVersion                     4.0.30319.42000
WSManStackVersion              3.0
PSRemotingProtocolVersion      2.3
SerializationVersion           1.1.0.1

Why Powershell doesn't respect variable declaration [string] and is trying to return Object[] ?

Upvotes: 0

Views: 146

Answers (1)

PMental
PMental

Reputation: 1179

The return keyword is reduntant in PowerShell, anything inside a function that gives output will be returned by the function.

Thus in your function two things are returned, first $vw which at that time is an empty string, then $vw again which by now has a value.

Basically you're getting an array because your function is returning two objects/values.

Try running ([string]$null).GetType() and you'll see a null variable cast as a string will return an empty string.

Just remove

[string]$vw;

which has no real point in the function.

Upvotes: 1

Related Questions