2013-05-19 6 views
0

Powershell에는 파일 내용을 가져 와서 CSV 파일에 입력 할 수있는 필드가 있습니다. 나는 링크에서 값을 얻고 링크 열을 손상시키지 않으면 서 CSV 파일로 전송되는 열에 추가하는 방법이 있는지 궁금합니다.Powershell의 링크에서 추출한 값

function Convert2CSV { 
(Get-Content $input_path) -match "href" | % { 
$data = ($_ -replace '(?:.*)href="(.*?)">Date:\s*([\w\.]+)\s*([\w\:]+)\s*Item:\s*(.*)</a>(?:.*)' , '$1;$2;$3;$4').Split(";") 
New-Object psobject -Property @{ 
    "Link" = $data[0] 
    "Date" = $data[1] 
    "Time" = $data[2] 
    "Item" = $data[3] 
    } 
} #| Export-Csv $output_file -NoTypeInformation 
} 

내가 찾고 값은 다음 중 하나입니다

FeedDefault_.*?(&) or _Feed.*?(&) 

내가 '링크'= $ 데이터 [0] 부분에 if 문의 일종을 추가 할 수 있다는 생각에 수정이 있습니까?

요청한대로 샘플 출력.

Value in Link | Link                 | Date  | Time | Item   | 
--------------------------------------------------------------------------------------------------------------------------------------------| 
bluepebbles  | http://www.domain.com/page.html?FeedDefault_bluepebbles&something  | 2013-05-19 | 13:30 | Blue Pebbles  | 
--------------------------------------------------------------------------------------------------------------------------------------------| 
redpebbles  | http://www.domain.com/page.html?Feed_redpebbles&something    | 2013-05-19 | 13:31 | Red Pebbles  | 
--------------------------------------------------------------------------------------------------------------------------------------------| 

CSV 서식이

Value in Link,Link,Date,Time,Item 
"bluepebbles","http://www.domain.com/page.html?FeedDefault_bluepebbles&something","2013-05-19","13:30","Blue Pebbles" 
"redpebbles","http://www.domain.com/page.html?Feed_redpebbles&something","2013-05-19","13:31","Red Pebbles" 

그래서

$input_path = 'f:\mockup\area51\files\link.html' 
$output_file = 'f:\mockup\area51\files\db_csv.csv' 

$tstampCulture = [Globalization.cultureinfo]::GetCultureInfo("en-GB") 

$ie = New-Object -COM "InternetExplorer.Application" 
$ie.Visible = $false 

$ie.Navigate("file:///$input_path") 

$ie.document.getElementsByTagName("a") | % { 
    $_.innerText -match 'Date:\s*([\w\.]+)\s*([\w\:]+)\s*Item:\s*(.*)' 
    $obj = New-Object psobject -Property @{ 
    "Link" = $_.href 
    "Date" = $matches[1] 
    "Time" = $matches[2] 
    "Item" = $matches[3] 
    } 
    if ($obj.Link -match '\?Feed(?:Default)?_(.*?)&') { 
    $obj | Add-Member –Type "NoteProperty" –Name "LinkValue" –Value $matches[1] 
    } 
    $obj 
} #| Export-Csv $output_file -NoTypeInformation 

에 입력하면 오류가 반환

You cannot call a method on a null-valued expression. 
At line:12 char:38 
+  $ie.document.getElementsByTagName <<<< ("a") | % { 
+ CategoryInfo   : InvalidOperation: (getElementsByTagName:String) [], RuntimeException 
+ FullyQualifiedErrorId : InvokeMethodOnNull 

그래서 나는 아마 뭔가를 엉망 것을 확신합니다. :)

+0

더 구체적으로 설명해야합니다. 두 값은 가계가 맞습니까? 정규식 - 와일드 카드 등으로 구성되어 있으므로 원하는 것을 이해하기가 어렵습니다. url에'FeedDefault _. *? (&)'또는'_Feed. *? (&)'가 정확히 포함되어 있는지 확인하고 일치하는 경우 ex라는 열에 추가하십시오. '경기'? 어떤 결과가 나타나야하는지 몇 가지 샘플 출력을 포함합니다. –

+0

링크에있는 경우 'FeedDefault_와 &'사이의 내용을 추출하고 링크에있는 경우에는 '_Feed와 &'사이에있는 내용을 추출하고 싶습니다. 그런 다음 링크 열을 손상시키지 않고 CSV 파일로 누출되는 열에 해당 값을 추가하십시오. – gjettison

답변

1

먼저 -replace 대신 -match을 사용하는 것이 좋습니다. 결과로 $matches 배열에 관심있는 부분합이 이미 포함되어 있으므로이 배열을 수동으로 만들 필요가 없습니다.

Get-Content $input_path | ? { $_.contains("href") } | % { 
    $_ -match 'href="(.*?)">Date:\s*([\w\.]+)\s*([\w\:]+)\s*Item:\s*(.*)</a>' 
    $obj = New-Object psobject -Property @{ 
    "Link" = $matches[1] 
    "Date" = $matches[2] 
    "Time" = $matches[3] 
    "Item" = $matches[4] 
    } 
    $obj 
} #| Export-Csv $output_file -NoTypeInformation 

추가 정보는 두 번째 -match$obj.Link에서 추출 할 수 있으며, 다음 Add-Member를 통해 사용자 정의 개체에 추가 : 당신의 입력 파일을 HTML 파일이 아마 때문에

if ($obj.Link -match '\?Feed(?:Default)?_(.*?)&') { 
    $obj | Add-Member –Type "NoteProperty" –Name "LinkValue" –Value $matches[1] 
} 

또한, 당신이 사용하는 것이 좋습니다 InternetExplorer COM 개체를 사용하면 파일을 한 줄씩 처리하는 것보다 추출 된 태그를 훨씬 잘 제어 할 수 있습니다.

$ie = New-Object -COM "InternetExplorer.Application" 
$ie.Visible = $false 

$ie.Navigate("file:///$input_path") 
while ($ie.Busy) { Start-Sleep -Milliseconds 100 } 

$ie.document.getElementsByTagName("a") | % { 
    $_.innerText -match 'Date:\s*([\w\.]+)\s*([\w\:]+)\s*Item:\s*(.*)' 
    $obj = New-Object psobject -Property @{ 
    "Link" = $_.href 
    "Date" = $matches[1] 
    "Time" = $matches[2] 
    "Item" = $matches[3] 
    } 
    if ($obj.Link -match '\?Feed(?:Default)?_(.*?)&') { 
    $obj | Add-Member –Type "NoteProperty" –Name "LinkValue" –Value $matches[1] 
    } 
    $obj 
} 
+0

훌륭한 아이디어에 감사드립니다! 유일한 문제는 코드에 입력 할 때 오류가 발생합니다. 'null 값을 갖는 식에서는 메서드를 호출 할 수 없습니다. 줄에서 : 12 문자 : 38 + $ ie.document.getElementsByTagName <<<< ("a") | % { + CategoryInfo : InvalidOperation : (getElementsByTagName : String) [], RuntimeException + FullyQualifiedErrorId : InvokeMethodOnNull' – gjettison

+0

나쁘지. 'Navigate()'는 즉시 반환하지만 IE가 페이지로드를 마칠 때까지 기다려야합니다. 내 대답을 쓸 때 wait-loop를 추가하는 것을 잊어 버렸기 때문에, 페이지가 완전히로드되기 전에 테스트가'document' 객체에 액세스하려했을 것입니다. 결정된. –

+0

그게 의미가 있지만, 나는 여전히 새 코드와 함께 오류 메시지가 나타납니다. 나는 주변에서 놀고, 내가 일하는 것을 얻을 수 없는지 지켜 볼 것입니다. 올바른 방향의 포인터에 다시 한번 감사드립니다 !! – gjettison