Reputation: 627
Word Doc content: [(7)]/[(8)] [ Security Agent 1] as security trustee for the Secured Parties (the "Security Agent") ; and
Value to extract is "Security Agent 1"
It extracts 7 as thats the first within bracket.
Below code works fine, but will give only first occurence/value within brackets. Need to loop it through multiple values within bracket and give me the 3rd value in bracket
$FinalTable = Get-Content $SourceFile|
select-string -pattern $SearchKeyword |
Select -Property @{Name = 'Name'; Expression = {$_.Line}}, @{Name = 'LineNo'; Expression = {$_.LineNumber}}, @{Name='Criteria';Expression = {$_.Category}} |
ForEach-Object {
$str = $_.Name
$LineNumber = $_.LineNo
$Criteria = $_.Criteria
$start = $str.indexOf("[") + 1
$end = $str.indexOf("]", $start)
$length = $end - $start
$result = ($str.substring($start, $length)).trim()
#Creating a custom object to display in table format
$Obj = New-Object -TypeName PSCustomObject
Add-Member -InputObject $Obj -MemberType NoteProperty -Name Category -Value $Category
Add-Member -InputObject $Obj -MemberType NoteProperty -Name Description -Value $result
$obj
}
$FinalTable | Export-Csv -Path $DestinationFile -NoTypeInformation -Encoding ASCII
Trying this as theo suggested but didn't worked
$FinalTable = Get-Content $SourceFile|
select-string -pattern $SearchKeyword |
Select -Property @{Name = 'Name'; Expression = {$_.Line}}, @{Name = 'LineNo'; Expression = {$_.LineNumber}}, @{Name='Criteria';Expression = {$_.Category}} |
ForEach-Object {
$str = $_.Name
$LineNumber = $_.LineNo
$Criteria = $_.Criteria
#$start = $str.indexOf("[") + 1
#$end = $str.indexOf("]", $start)
#$length = $end - $start
#$result = ($str.substring($start, $length)).trim()
#Write-host $str
if ($str -match '(\[[^\]]+])\/(\[[^\]]+])\s*\[\s*([^\]]+)]') {
# $matches[1] --> "(7)"
# $matches[2] --> "(8)"
$result = $matches[3] # --> "Security Agent 1"
}
Write-Host $result
#Creating a custom object to display in table format
$Obj = New-Object -TypeName PSCustomObject
Add-Member -InputObject $Obj -MemberType NoteProperty -Name Category -Value $Category
Add-Member -InputObject $Obj -MemberType NoteProperty -Name Description -Value $result
$obj
}
$FinalTable | Export-Csv -Path $DestinationFile -NoTypeInformation -Encoding ASCII
Upvotes: 0
Views: 54
Reputation: 61048
You could use Regular Expression to get the parts between the brackets in a string like [(7)]/[(8)] [ Security Agent 1] as security trustee for the Secured Parties (the "Security Agent")
.
Instead of
$start = $str.indexOf("[") + 1
$end = $str.indexOf("]", $start)
$length = $end - $start
$result = ($str.substring($start, $length)).trim()
do
if ($str -match '\[([^\]]+)\]\/\[([^\]]+)\]\s*\[\s*([^\]]+)]') {
# $matches[1] --> "(7)"
# $matches[2] --> "(8)"
$result = $matches[3] # --> "Security Agent 1"
}
else {
$result = '' # should not happen..
}
Upvotes: 1