2016-05-30 16 views
0

我試圖按照this example來將圖像附加到使用PowerShell的電子郵件。下面是代碼行爲很奇怪的部分:如何解決後來在代碼中導致錯誤的powershell表達式

if ($DirectoryInfo) { 
    foreach ($element in $DirectoryInfo) { 
     $failedTest = $element| Select-Object -Expand name   
     $failedTests += $failedTest 
     $failedTestLog = "$PathLog\$failedTest.log" 
     $logContent = [IO.File]::ReadAllText($failedTestLog) 

     $imageDir = "$PathLog\$element\Firefox\*" 
     $imageSearch = Get-ChildItem -Path $imageDir -Include *.png -Recurse -Force 
     $imageFullname = $imageSearch | select FullName | Select-Object -Expand Fullname 
     $imageFilename = $imageSearch | Select-Object -Expand name 
     $imageFilename 
     $imageFullname 

     # *** THE FOLLOWING LINE CAUSES THE ERROR *** 
     $attachment = New-Object System.Net.Mail.Attachment –ArgumentList $imageFullname.ToString() # *** CAUSING ERROR *** 
     #$attachment.ContentDisposition.Inline = $True 
     #$attachment.ContentDisposition.DispositionType = "Inline" 
     #$attachment.ContentType.MediaType = "image/jpg" 
     #$attachment.ContentId = '$imageFilename' 
     #$msg.Attachments.Add($attachment) 

     $outputLog += "  

******************************************** 
$failedTest 
******************************************** 
$logContent  
" 
    } 

} else { 
    $outputLog = '** No failed tests **' 
} 



# Create the Overview report 
$outputSummary = "" 
foreach ($element in $scenarioInfo) { 
    if (CheckTest $failedTests $element) { 
     $outputSummary += " 
$element : FAILED"     # *** ERROR LINE *** 
    } Else { 
     $outputSummary += " 
$element : Passed" 
    } 
} 

如果我註釋掉定義附件的那一行,代碼就可以正常工作。如果我使用的代碼,因爲它是,我得到以下錯誤:

Unexpected token ':' in expression or statement. 
At D:\Testing\Data\Powershell\LoadRunner\LRmain.ps1:112 char:11 
+ $element : <<<< FAILED" 
    + CategoryInfo   : ParserError: (::String) [], ParseException 
    + FullyQualifiedErrorId : UnexpectedToken 

是指在它說:「錯誤行」的劇本底部的線。到底他媽發生了什麼?這種行爲對我來說完全不合邏輯!我不明白,一個沒有任何效果的陳述可能會導致其他地方的錯誤!什麼是問題,以及如何解決這個問題......?

另外,如果我在違規行中使用$imageFullname$imageFullname.ToString()並不重要。

+0

'$ element'的輸出是什麼?你確定$ element和分號之間有空格嗎? –

+0

是的,我確定。此外,問題是由'System.Net.Mail.Attachment'行引起的。如果我註釋掉這一行,代碼「有效」並且不會產生錯誤。我也找不到任何有關使用帶有'Attachment'對象的'ArgumentList'的文檔... – Alex

+0

您的代碼示例似乎存在與該問題無關的問題。 「ERROR LINE」中的引用跨越多行,在PowerShell中不允許使用這裏的字符串。 – TravisEz13

回答

0

定義$outputSummary作爲陣列:

$outputSummary = @() 

代替

$outputSummary = "" 
+0

不改變任何東西,我得到完全相同的錯誤。 – Alex

1

嘗試通過

"$element` : FAILED" 

反向報價替換"$element : FAILED"將逸出的分號;在PowerShell中具有特定的含義。 (它允許輸出子屬性:例如$env:username

+0

但是,在該代碼行之前的循環中如何使用'System.Net.Mail.Attachment'來解決這個問題呢? – Alex

+1

避免這種情況的另一種語法是 '「$ {element}:FAILED」' – TravisEz13

相關問題