1

I'm new to the .Net World and Powershell. I have the following code:

$e = "A","A","A","B","A","B","A","A"

write-output $e.Replace("B", "C")

it works and prints

A
A
A
C
A
C
A
A

But I cannot find a Replace Method for system.array only for system.string. Why is it working?

0

2 Answers 2

3

The replacement is working because you're running PowerShell v3 or newer. In PowerShell v3 Microsoft added a feature called member enumeration, which makes PowerShell invoke a method or property on all elements of an array if the array object itself doesn't have such a method or property.

If you run PowerShell v2 (e.g. by invoking powershell.exe -version 2) and run your code in that instance you'll get the following error:

Replace : Method invocation failed because [System.Object[]] doesn't contain
a method named 'Replace'.
At line:1 char:24
+ write-output $e.Replace <<<< ("B", "C")
    + CategoryInfo          : InvalidOperation: (Replace:String) [], RuntimeException
    + FullyQualifiedErrorId : MethodNotFound
Sign up to request clarification or add additional context in comments.

Comments

0

First of all, you don't need the "Write-Output"-part. But it works because you replace strings within the array for other strings.

Let me demonstrate:

$e = "A","A","A","B","A","B","A","A"
foreach($obj in $e){
    $obj.GetType()
}

This outputs (only posted first 2 lines):

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

Comments

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.