How to Split a String Into Two Variables in PowerShell

Gareth Downes-PowellUpdated April 17, 2017

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.

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.

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.

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.

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!

Tip

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."

Resources

About the Author

Gareth Downes-Powell has been writing since 2000. He has contributed to a number of U.K. magazines, including "Web Designer," and has co-written four IT-related books published by Apress and Wrox. He has also worked as a technical editor on a number of titles for U.K. and U.S. publishers. Downes-Powell attended Thanet Technical College, achieving A-Levels in computer science, math and physics.