How to Split a String Into Two Variables in PowerShell

Written by gareth downes-powell
  • Share
  • Tweet
  • Share
  • Pin
  • Email
How to Split a String Into Two Variables in PowerShell
( Images)

Microsoft PowerShell is a framework for running scripts and automating tasks using the Microsoft Windows operating system. PowerShell v2.0 is available for Windows 7 and can also be used with Windows XP if Service Pack 3 has been installed. Using the PowerShell "Split" function, a string can be broken up into parts using a custom delimiter. The result is returned in the form of an array, with each array element containing a part of the original string.

Skill level:

Other People Are Reading


  1. 1

    Start Windows PowerShell by clicking the Windows "Start" button and typing "powershell" into the "Search programs and files" text box. This will open the Windows PowerShell console.

  2. 2

    Type "notepad split.ps1" in the PowerShell console to open Microsoft Notepad and create a new script called "split.ps1." Click "Yes" when prompted by Notepad to allow the new file to be created.

  3. 3

    Type the following commands into the new file, then save the file:

    $text = "Windows PowerShell - Hello world!"

    $split = $text.split("-")

    echo $split[0]

    echo $split[1]

    First, a string is created named "$text" which holds the text to be split. The string is then split using the PowerShell "Split" function, passing in the character the string is to be split by. In the code above, the string is split at the location of the hyphen. This creates an array in "$split" with two elements. The first element contains all the text up to the hyphen and the second element contains all the text after the hyphen. The contents of the two elements are then displayed to verify the command has worked.

  4. 4

    Run the script in PowerShell by typing ".\split.ps1" and the display will show the output below, indicating the command was successful:

    Windows PowerShell

    Hello World!

Tips and warnings

  • If you get the error "File split.ps1 cannot be loaded because the
  • execution of scripts is disabled on this system" when you launch the script, it means that scripting is disabled on the system, which is done by default for security. To allow your own scripts to run, start PowerShell as an administrator and then run the following command: "Set-ExecutionPolicy RemoteSigned."

Don't Miss

  • All types
  • Articles
  • Slideshows
  • Videos
  • Most relevant
  • Most popular
  • Most recent

No articles available

No slideshows available

No videos available

By using the site, you consent to the use of cookies. For more information, please see our Cookie policy.