2017-02-10 41 views
0

使用EWS試圖執行下面的代碼得到了一個錯誤:從PowerShell的2.0

$dll = "C:\Program Files\Microsoft\Exchange\Web Services\2.0\Microsoft.Exchange.WebServices.dll" 

import-module -Name $dll 

$exc = new-object Microsoft.Exchange.WebServices.Data.ExchangeService 

錯誤:

New-Object : Could not load file or assembly 'System.Core, Version=3.5.0.0, Cul 
ture=neutral, PublicKeyToken=b77a5c561934e089' or one of its dependencies. The 
system cannot find the file specified. 
At D:\scripts\get_mails.ps1:5 char:18 
+ $exc = new-object <<<< Microsoft.Exchange.WebServices.Data.ExchangeService 
    + CategoryInfo   : NotSpecified: (:) [New-Object], FileNotFoundExce 
    ption 
    + FullyQualifiedErrorId : System.IO.FileNotFoundException,Microsoft.PowerS 
    hell.Commands.NewObjectCommand 

我們跑這在Windows Server 2008 R2具有.NET上框架4.5.2(現在升級到4.6.1)安裝。正在使用的PowerShell版本是v2.0

我們應該可以通過powershell 2.0使用託管api嗎?

回答

0

我認爲問題在於您正在嘗試加載需要.net運行時> = 3.5的程序集。如果您在PowerShell中運行2.0 $PSVersionTable,你會得到這樣的事情:

Name       Value 
----       ----- 
CLRVersion      2.0.50727.5485 
BuildVersion     6.1.7601.17514 
PSVersion      2.0 
WSManStackVersion    2.0 
PSCompatibleVersions   {1.0, 2.0} 
SerializationVersion   1.1.0.1 
PSRemotingProtocolVersion  2.1 

這是造成的EWS組件失敗加載CLR版本。

要解決這個問題,您可以創建一個批處理文件,該文件反過來會創建一個調用PowerShell 2.0並使用更新的CLR運行時的配置文件。

這裏的批處理文件:

@echo off 
:: https://stackoverflow.com/questions/7308586/using-batch-echo-with-special-characters 
if exist %~dp0powershell.exe.activation_config goto :run 
echo.^<?xml version="1.0" encoding="utf-8" ?^>     > %~dp0powershell.exe.activation_config 
echo.^<configuration^>          >> %~dp0powershell.exe.activation_config 
echo. ^<startup useLegacyV2RuntimeActivationPolicy="true"^> >> %~dp0powershell.exe.activation_config 
echo. ^<supportedRuntime version="v4.0"/^>     >> %~dp0powershell.exe.activation_config 
echo. ^</startup^>           >> %~dp0powershell.exe.activation_config 
echo.^</configuration^>          >> %~dp0powershell.exe.activation_config 
:run 
:: point COMPLUS_ApplicationMigrationRuntimeActivationConfigPath to the directory that this cmd file lives in 
:: and the directory contains a powershell.exe.activation_config file which matches the executable name powershell.exe 
set COMPLUS_ApplicationMigrationRuntimeActivationConfigPath=%~dp0 
%SystemRoot%\System32\WindowsPowerShell\v1.0\powershell.exe %* 
set COMPLUS_ApplicationMigrationRuntimeActivationConfigPath= 

變化powershell.exepowershell_ise.exe與.NET CLR 4運行時推出ISE。

也看到我SO answer在PowerShell中

+0

你接近使用EWS ......但是爲什麼'powershell.exe.activation_config'? – deostroll

+0

關閉,怎麼樣?少了什麼東西?回覆:配置文件,看到這樣回答:http://stackoverflow.com/a/31279372/1368849 – TechSpud

+0

我其實與最高upvoted答案那裏...然而,請告訴我爲什麼你推薦這種方式? – deostroll

0

它似乎需要.net 3.5。 程序集版本「Version = 3.5.0.0」說。