none
Method invocation failed because [System.Object[]] doesn't contain a method named 'split'

    Question

  • Hello,

    When I try to use the split method, it works in PowerShell v3 and not in v2! While I search this in forums, I found relevant posts but not sure why it generate error message in v2!

    Here is the code snippet. My intention is to read list of groups and separate them by comma. Any further help would be greatly appreciated. Thank you.

    $UserGroups = @(Read-Host " ").split(',') | % {$_.trim()}

    For example, if I enter: 123,456

    In PowerShell v3, it shows:

    123

    456

    In PowerShell v2, it shows:

    Method invocation failed because [System.Object[]] doesn't contain a method named 'split'.At C:\Scripts\test.ps1:20 char:41+

    $UserGroups = @(Read-Host " ").split <<<< (',') | % {$_.trim()}    + CategoryInfo

    : InvalidOperation: (split:String) [], RuntimeException    + FullyQualifiedErrorId : MethodNotFound

    Monday, October 29, 2012 4:03 PM

Answers

  • $UserGroups =  (Read-Host " ").split(',') | % {$_.trim()}
    • Proposed as answer by Bigteddy Monday, October 29, 2012 5:19 PM
    • Marked as answer by Sadda Monday, October 29, 2012 5:34 PM
    Monday, October 29, 2012 4:58 PM

All replies

  • $UserGroups = [array](Read-Host " ").split(',') | % {$_.trim()}


    Grant Ward, a.k.a. Bigteddy

    Monday, October 29, 2012 4:24 PM
  • $UserGroups =  (Read-Host " ").split(',') | % {$_.trim()}
    • Proposed as answer by Bigteddy Monday, October 29, 2012 5:19 PM
    • Marked as answer by Sadda Monday, October 29, 2012 5:34 PM
    Monday, October 29, 2012 4:58 PM
  • $UserGroups = [array](Read-Host " ").split(',') | % {$_.trim()}


    Grant Ward, a.k.a. Bigteddy


    It works! In earlier versions of PowerShell, I've to use [array] instead of @, right? Thank you!
    Monday, October 29, 2012 5:04 PM
  • I'd recommend against this approach, as it makes input verification more difficult. A better approach, and one more easy to debug, would be to store the string input by read-host in a variable, and process that.

    Al Dunbar -- remember to 'mark or propose as answer' or 'vote as helpful' as appropriate.

    Monday, October 29, 2012 5:06 PM
  • I'd recommend against this approach, as it makes input verification more difficult. A better approach, and one more easy to debug, would be to store the string input by read-host in a variable, and process that.

    Al Dunbar -- remember to 'mark or propose as answer' or 'vote as helpful' as appropriate.

    When I separate the Read-Host section, it gave me the same error (Method invocation) error message in v2!

    Monday, October 29, 2012 5:13 PM
  • Kazun is right.  We don't need to cast the results of Read-Host to an array.  This is the problem:  A simple string has a .split() method.

    Grant Ward, a.k.a. Bigteddy

    Monday, October 29, 2012 5:20 PM