2014-01-29 43 views
0

我有PowerShell腳本,它如同預期,如果我從PowerShell ISE中運行它。從進程中運行PowerShell中的作用不同,那麼從PowerShell ISE中

$ol = @() 
$ProcessActive = Get-Process outlook -ErrorAction SilentlyContinue 
if($ProcessActive -eq $null) 
{ 
$ol = New-Object -comObject Outlook.Application 
} 
else 
{ 
$ol = [Runtime.InteropServices.Marshal]::GetActiveObject("Outlook.Application") 
} 
$file = "c:\testfile.pdf" 

$mail = $ol.CreateItem(0) 
$Mail.Recipients.Add("[email protected]") 
$mail.Subject = "This is a subject" 
$mail.HTMLBody = "<html><body><h3>Hello world</h3></body></html>" 
$mail.Attachments.Add($file) 
$inspector = $mail.GetInspector 
$inspector.Display() 

但是,如果我在C#中啓動一個進程來執行腳本,它只會在Outlook進程沒有運行的情況下起作用。

 var filename = "script.ps1"; 
     var fullname = path + filename; 

     if (System.IO.File.Exists(fullname)) 
     { 
      ProcessStartInfo startInfo = new ProcessStartInfo(); 
      startInfo.FileName = @"powershell.exe"; 
      startInfo.Arguments = string.Format(@"& '{0}'", fullname); 
      startInfo.RedirectStandardOutput = true; 
      startInfo.RedirectStandardError = true; 
      startInfo.UseShellExecute = false; 
      startInfo.CreateNoWindow = true; 
      Process process = new Process(); 
      process.StartInfo = startInfo; 
      process.Start(); 
      process.WaitForExit(); 
      System.IO.File.Delete(fullname); 
     } 

該過程最終會結束執行,並且在兩種情況下(Outlook運行或不運行)都會刪除文件。

我需要做什麼才能讓從C#程序(即使Outlook正在運行)啓動時的腳本正確執行改變?

在此先感謝。

+0

@肘牽引在C#我使用包含的powershell腳本,並通過它像在這條線的參數文件:startInfo.Arguments =的String.Format(@「&‘{0}’」,全名); – Gyocol

回答

0

爲了回答有什麼不同劇本,我已經創建了一個日誌是運行腳本的進程的進程之間。創建我用過的日誌

System.IO.File.WriteAllText(@"c:\log.txt",process.StandardError.ReadToEnd()) 

首先例外是:缺少引用。通過在PowerShell腳本的頂部添加固定丟失的引用後:

Add-Type -Path 'Dir\To\Dll' 

之後,我收到另一個錯誤:

Exception calling "GetActiveObject" with "1" argument(s): "Operation unavailabl 
e (Exception from HRESULT: 0x800401E3 (MK_E_UNAVAILABLE))" 

我讀過一些文章,這與Outlook對做不允許不同用戶'使用'正在運行的實例(當前用戶和管理員當前用戶運行腳本)。我現在使用Microsoft.Office.Interop.Outlook DLL打開一個新的電子郵件窗口,執行它的控制檯應用程序可以作爲當前用戶運行,而不需要管理員權限。這解決了我的問題:即使Outlook已經運行,我現在可以打開一個新的電子郵件窗口。

相關問題