#requires -version 2.0 <# ----------------------------------------------------------------------------- Script: Convert-TexttoObject.ps1 Version: 1.0 Author: Jeffery Hicks http://jdhitsolutions.com/blog http://twitter.com/JeffHicks http://www.ScriptingGeek.com Date: 10/24/2011 Keywords: Comments: "Those who forget to script are doomed to repeat their work." **************************************************************** * DO NOT USE IN A PRODUCTION ENVIRONMENT UNTIL YOU HAVE TESTED * * THOROUGHLY IN A LAB ENVIRONMENT. USE AT YOUR OWN RISK. IF * * YOU DO NOT UNDERSTAND WHAT THIS SCRIPT DOES OR HOW IT WORKS, * * DO NOT USE IT OUTSIDE OF A SECURE, TEST SETTING. * **************************************************************** ----------------------------------------------------------------------------- #> Function Convert-TextToObject { <# This function takes a collection of simple delimited lines and turns them into an object. The function assumes a single delimiter. The default delimiter is the colon (:). The item to the left will be the property and the item on the left will be the property value. Use $GroupCount to keep track of items that come in groups and write a new object when the count has been reached. For example, this allows you to pipe in a long collection of strings and turn every 5 into an object. tasklist /s server01 /fo list | where {$_} | convert-texttoobject -group 5 #> [cmdletbinding(SupportsShouldProcess=$True)] param ( [Parameter(Position=0,Mandatory=$True,HelpMessage="Enter a string to be parsed into an object", ValueFromPipeline=$True)] [ValidateNotNullorEmpty()] [string[]]$Text, [string]$Delimiter=":", [int]$GroupCount ) Begin { Write-Verbose "Starting $($myinvocation.mycommand)" #define a hashtable $myHash=@{} if ($GroupCount) { Write-Verbose "Grouping every $GroupCount items as an object" } #start an internal counter $i=0 } Process { Foreach ($item in $text) { if ($i -lt $GroupCount) { $i++ } else { #reset $i=1 } #split each line at the delimiter $data=$item.Split($delimiter) #remove spaces from "property" name $prop=$data[0].Replace(" ","") #trim $prop=$prop.Trim() $val=$data[1].Trim() #add to hash table Write-Verbose "Adding $prop to hash table with a value of $val" $myHash.Add($prop,$val) #if internal counter is equal to the group count #write the object and reset the hash table if ($i -eq $groupCount) { New-Object -TypeName PSObject -Property $myHash $myHash.Clear() } } #foreach } End { #create new object from hash table if ($myHash.count -gt 0) { New-Object -TypeName PSObject -Property $myHash Write-Verbose "Ending $($myinvocation.mycommand)" } } } #end function