我编写了这个PowerShell脚本来归档在特定日期范围内创建的所有日志文件。
$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 的一部分,我已在系统上安装了它,但我仍然遇到这些错误。我正在使用 PowerShell v2.0,且我的操作系统是 Windows Server 2008 R2。
我该如何使它工作?
C:/Program Files/WindowsPowerShell/Modules/
下的任何内容,例如Microsoft.PowerShell.PSReadline
。这些必须使用Add-Type -Path
来加载。 - MultiplyByZer0