2014-01-29 45 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已经运行,我现在可以打开一个新的电子邮件窗口。

相关问题