Reputation: 39
I'm trying to write a PowerShell script to get of 2 column of a csv file:
ProductName ProductCode
-----------------------------------------------------------
Java 7 Update 67 {26374892-xxxx-xxxx-xxxx-123456789012}
Java 8 Update 25 {26374892-xxxx-xxxx-xxxx-902341562789}
I want to get only ProductCode
column values to use in a foreach loop.
I tried in below way
$code1 = Get-Contect %path% | Foreach-Object {
$_ -split '\s+' | Select-object -skip 1 | Select-Object -Last 1
}
foreach($code in $code1){ write-host $code }
I'm getting below output
67,{232424-55567-8879-xxxxxxx}
25,{324356456-5674-xxxx-xxxxxx}
But I want output only product codes like
{3245345345-3454-56656757-xxxxx}
Upvotes: 2
Views: 1847
Reputation: 72171
This doesnt really look like CSV. I'd say the easiest way of doing this is something like this:
Get-Content %path% | Foreach-Object { $_ -split '\s+' | Select-Object -Last 1 }
This way you will get the last object after splitting string on multiple spaces
ps. if you need to skip the header you can add | Select-Object -Skip 1
after get-content
pps. if import-csv allows for regex in delimiter
import csv would be easier to use, but I doubt it allows for that.
ppps. works for me:
> cat .\Untitled-2.txt
ProductName ProductCode
Java 7 Update 67 {26374892-xxxx-xxxx-xxxx-123456789012}
Java 8 Update 25 {26374892-xxxx-xxxx-xxxx-902341562789}
> Get-Content .\Untitled-2.txt | select-object -skip 1 | Foreach-Object { $_ -split '\s+' | Select-Object -Last 1 }
{26374892-xxxx-xxxx-xxxx-123456789012}
{26374892-xxxx-xxxx-xxxx-902341562789}
Upvotes: 2
Reputation: 13227
You might want to look at how you are getting that information, as it will likely be easier to filter the information you want at source...
Using java as the example but the process could work with anything:
$java = Get-WMIObject Win32_Product | Where-Object { $_.Name -Like "java*" }
$java
will then contain the information about matching installations, you can then simply select the property you want and save that to file:
$java | Select-Object -ExpandProperty IdentifyingNumber | Out-File C:\folder\java.txt
Which will give you a file like:
{26374892-xxxx-xxxx-xxxx-123456789012} {26374892-xxxx-xxxx-xxxx-902341562789}
Upvotes: 0