6

I'm wondering if there is a way to use do a substring when using powershell's select-object cmdlet

Here is an example of what i'm trying to do

$sapFile = "C:\MyFile*.XML"

# Get the newest xml file
$newestFile = Get-ChildItem -Path $sapFile | Sort CreationTime | Select -Last 1

# get the contents of the xml file
[XML]$sapContent = Get-Content -Path $newestFile.FullName

$sapContent.DATA.CP | Select -Property CP_NO,MEN.Substring(0,4)

This however doesn't work.

Thanks

2 Answers 2

9

You can create a property on the fly using Select that has a calculated value by using a hashtable. In the following example I select the 'CP_NO' property, and create the 'MENSubString' property with a hashtable.

Select -Property CP_NO,@{label='MENSubString';expression={$_.MEN.Substring(0,4)}}

Label can be shortened to just 'l' and Expression can be shortened to just 'e', which would look like:

Select -Property CP_NO,@{l='MENSubString';e={$_.MEN.Substring(0,4)}}
Sign up to request clarification or add additional context in comments.

Comments

1

other method :

$sapContent.DATA.CP | foreach {
       [pscustomobject]@{
        CP_NO=$_.CP_NO
        PartOfMen=MEN.Substring(0,4)           
       }
      }

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.