powershell – 无法找到[System.IO.Compression.CompressionLevel]类型,确保装载了此类型的程序集

前端之家收集整理的这篇文章主要介绍了powershell – 无法找到[System.IO.Compression.CompressionLevel]类型,确保装载了此类型的程序集前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我写了这个Power Shell脚本,该脚本应该在特定日期范围内对所有日志文件进行归档.
$currentDate = Get-Date;
$currentDate | Get-Member -Membertype Method Add;
$daysBefore = -1;
$archiveTillDate = $currentDate.AddDays($daysBefore);

$sourcePath = 'C:\LOGS';
$destPath='C:\LogArchieve\'+$archiveTillDate.Day+$archiveTillDate.Month+$archiveTillDate.Year+'.zip';

foreach( $item in (Get-ChildItem $sourcePath | Where-Object { $_.CreationTime -le $archiveTillDate }) )
{
    [Reflection.Assembly]::LoadWithPartialName("System.IO.Compression.FileSystem");
    $compressionLevel = [System.IO.Compression.CompressionLevel]::Optimal;
    [System.IO.Compression.ZipFile]::CreateFromDirectory($sourcePath,$destPath,$compressionLevel,$false);
}

它工作直到foreach循环,但一旦循环它给出这些错误

Unable to find type [System.IO.Compression.CompressionLevel]: make sure that the assembly containing this type is loaded.
At line:4 char:65
+ $compressionLevel = [System.IO.Compression.CompressionLevel] <<<< ::Optimal;
+ CategoryInfo          : InvalidOperation: (System.IO.Compression.CompressionLevel:String) [],RuntimeException
+ FullyQualifiedErrorId : TypeNotFound

由于System.IO.Compression是.NET 4.5的一部分,我已经将其安装在系统上,但是我仍然收到这些错误.

我在Windows Server 2008 R2和PowerShell v2.0.

我该如何让它工作?

您可以手动将 .NET添加到PowerShell会话.

删除[Reflection.Assembly] :: LoadWithPartialName(“System.IO.Compression.FileSystem”);从您的脚本,并添加以下在顶部:

Add-Type -Path "C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.5\System.IO.Compression.FileSystem.dll"

或在一个32位盒子上:

Add-Type -Path "C:\Program Files\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.5\System.IO.Compression.FileSystem.dll"

这假定您的系统上的.NET 4.5安装OK,System.IO.Compression.FileSystem.dll实际上存在.

原文链接:https://www.f2er.com/windows/371428.html

猜你在找的Windows相关文章