ashish g
ashish g

Reputation: 291

How to read a string from text file using powershell

I want to read a specific string from a text file and output the string into another text file.

My text file (Sample.txt) looks like below:

@{AssemblyName=Microsoft.Office.Excel, Version=1.0.0.0, Culture=neutral,     PublicKeyToken=1y08bdf1111e0105c; Path=C:\Tes\app1\cc\application; ProjectPath=C:\test\application\Application.vbproj; Name=Microsoft.Office.Excel}

@{AssemblyName=System; Path=C:\Tes\app2\ser\application; ProjectPath=C:\test\application2\Application.vbproj; Name=System}

I do not want to include anything except the assemblyname.. i.e, the script should not consider version, culture etc.

The text file has lot of such assembly information. I would like to read only the AssemblyName and write that to another text file in powersehll. For Ex: The output.txt should contain only Microsoft.Office.Excel.

Also, I want to exclude few assembly names that start with a specific string like for eg: System. How can I do that?

I tried below, but it's not writing anything to the output.txt.

$workdir = "C:\Test"
$Txt = "$workdir\Sample.txt"

Function GetAsmName($rTxt)
{

Get-Content $Txt

$regex = '@{AssemblyName="(\w*?)"[,|;]'
$matches = (select-string  -Path $Txt -Pattern $regex)
$matches | Select -Expandproperty Matches | Select @{n="Name";e={$_.Groups[1].Value}}
Set-Content -path $workdir\Output.txt -value $matches
}

Any help would be greatly appreciated.

Thanks

Upvotes: 1

Views: 10364

Answers (1)

CB.
CB.

Reputation: 60910

Try:

$workdir = "C:\Test"
$Txt = "$workdir\Sample.txt"    
Function GetAsmName($rTxt)
{    
$captures = gc $rTxt | 
            select-string -Pattern '(?<=AssemblyName=)([^;|,]*)' -allmatches |
            select -expa matches | select -expa value    
Set-Content -path $workdir\Output.txt -value $captures
}

GetAsmName $Txt

Upvotes: 2

Related Questions