C# 从进程运行powershell的行为不同于powershell ISE

C# 从进程运行powershell的行为不同于powershell ISE,c#,powershell,process,outlook,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.Mar

我有一个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()
该过程最终会结束执行,并且在这两种情况下(outlook是否运行)都会删除该文件

当从C#进程启动脚本时(即使Outlook正在运行),为了让脚本正确执行,我需要做哪些更改


提前感谢。

为了回答脚本和进程之间的区别,我创建了运行脚本的进程日志。创建我使用的日志

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

@Knuckle Dragger in C#我使用包含powershell脚本的文件,并将其作为一个参数传递到这一行:startInfo.Arguments=string.Format(@“&{0}”,全名);
Exception calling "GetActiveObject" with "1" argument(s): "Operation unavailabl
e (Exception from HRESULT: 0x800401E3 (MK_E_UNAVAILABLE))"