从进程运行powershell与PowerShell ISE不同

时间:2014-01-29 09:38:16

标签: c# powershell process outlook

我有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("test@test.nl") 
$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);
        }

该过程最终结束执行,并且在两种情况下都删除了文件(前景运行与否)。

为了让脚本在从C#进程启动时正常执行(即使Outlook正在运行),我需要更改什么?

提前致谢。

1 个答案:

答案 0 :(得分: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已经运行,我现在也可以打开一个新的电子邮件窗口。

相关问题