Codemeister
Codemeister

Reputation: 43

How to extract a value out of a file, and save it in a new file, using Powershell

I recently started using Powershell and I'm trying out some code. I have a .cfg file with several rules of code. The code is written like this:

ad.name=1
ad.virtual=active
ad.set=none
ad.partition=78

Now I want to export the value of ad.partition, which is 78, to a new file. I don't want to export ad.partition or = but only the number 78.

So far I got this:

Get-Content -Path C:\file.cfg | Where-Object {$_ -like 'ad.partition=78'}

But then I -obviously- just get the variable and the value. Not sure how to continue... I hope someone has a way of achieving what I want.

After saving the value in a new file, would it be possible to add spaces? For example, the value consists out of 9 digits, e.g. 123456789. The desired output result would be 123 456 789.

Upvotes: 0

Views: 75

Answers (2)

Paolo
Paolo

Reputation: 26220

Use ConvertFrom-StringData cmdlet to create a hash table from your file, then simply index the key you are after:

$h=(Get-Content -Path C:\file.cfg | ConvertFrom-StringData)
$h.("ad.partition") -replace ('^(\d{1,3})(\d{1,3})?(\d{1,3})?','$1 $2 $3') > C:\out.cfg

Upvotes: 2

Martin Brandl
Martin Brandl

Reputation: 59001

You can use the Select-String cmdlet to capture your desired value using a regex. Then just pipe the result to the Out-File cmdlet. To get your desired output with spaces, you can use a simple format string:

"{0:### ### ###}" -f [int](Select-string 'ad\.partition=(.*)' -Path C:\file.cfg).Matches.Groups[1].Value | 
    Out-File C:\result.cfg

Upvotes: 1

Related Questions