Link to home
Start Free TrialLog in
Avatar of motioneye
motioneyeFlag for Singapore

asked on

Powershell to truncate string in text

Guys,
I have a powershell script below use to truncate the string in the string_output2.txt however the script below doesn't work, what I would need to output is something like
this JJR3345-s-54007.maxis.kd.com save in string_output22.txt
Get-Content (Get-ChildItem F:\Powershell\string_output2.txt) | % {$_.Split(':')[1]} | Out-File F:\Powershell\string_output22.txt


Here is contain in string_output2.txt


JJR3345-bs-54007:dbxsinstnace:JJR3345-s-54007.maxis.kd.com
JJR3345-bs-54008:dbxsinstnace:JJR3345-s-54008.maxis.kd.com
JJR3345-bs-54009:dbxsinstnace:JJR3345-s-54009.maxis.kd.com
JJR3345-s-54025:dbxsinstnace:JJR3345-s-54025.maxis.kd.com
JJR3345-s-54001:dbxsinstnace:JJR3345-s-54001.maxis.kd.com
Avatar of oBdA
oBdA

You don't need the "Get-ChildItem" since you're only addressing a single file, you need to use $_.Split(':')[2], and if you want to to overwrite the source file, you need to put Get-Content in parenthesis, so that PS will read the whole file before continuing with the pipeline.
(Get-Content F:\Powershell\string_output2.txt) | % {$_.Split(':')[2]} | Out-File F:\Powershell\string_output22.txt

Open in new window

Avatar of motioneye

ASKER

The ouput return me with null, its strange though to see teh output like this.

User generated image
That's a Unicode; use Out-File's -Encoding argument:
(Get-Content F:\Powershell\string_output2.txt) | % {$_.Split(':')[2]} | Out-File F:\Powershell\string_output22.txt -Encoding ASCII

Open in new window

Hi oBdA
Yes I have tried that, still I have the same error as per screenshot
ASKER CERTIFIED SOLUTION
Avatar of oBdA
oBdA

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Hi oBdA,
Thanks for help, I have to copy the text from one file and move to another new file, then the scripts worked with no flaw. thanks again for the assistance and the opinion