Hello Stack Overflow社区,
目前我正在努力使用这段代码(它并不那么漂亮):
$filepath = "C:\inetpub\logs\LogFiles"
$filearchivepath = "C:\inetpub\logs"
$daystoarchive = 1
$_ = "";
function create-7zip([String] $aDirectory, [String] $aZipfile){
#change the path where you downloaded the 7z exe
[string]$pathToZipExe = "C:\Users\kschweiger\Downloads\7za.exe";
[Array]$arguments = "a", "-tzip", "$aZipfile", "$aDirectory";
& $pathToZipExe $arguments;
}
#Create a new folder with the specific date
$ArchiveFolder = (Get-Date -Format dd.MM.yyyy) + " - Logs-Archive"
if(Test-Path "$filearchivepath\$ArchiveFolder"){
Write-Host "Folder already exists!"
}else{
New-Item -Path $filearchivepath -Name $ArchiveFolder -ItemType directory
}
#Save alle files older than X days into $Files
$Files = Get-ChildItem -Path $filepath -Recurse | where {$_.LastWriteTime -lt (Get-Date).AddDays(-$daystoarchive)}
#Copy/Move files and keep folder structure
foreach ($File in $Files){
$NewPath = $File.DirectoryName.Replace($filepath,"")
if (!(Test-Path "$filearchivepath\$ArchiveFolder\$NewPath"))
{
New-Item -Path "$filearchivepath\$ArchiveFolder\$NewPath" -ItemType Directory
}
$File | Copy-Item -Destination "$filearchivepath\$ArchiveFolder\$NewPath"
}
#Compress folder
if(Test-Path "$filearchivepath\$ArchiveFolder.zip"){
Write-Host "Archive-File already exists!"
}else{
#[IO.Compression.ZipFile]::CreateFromDirectory("$filearchivepath\$ArchiveFolder","$filearchivepath\$ArchiveFolder.zip")
create-7zip "$filearchivepath\$ArchiveFolder" "$filearchivepath\$ArchiveFolder.zip"
#Delete Folder
Remove-Item -Path "$filearchivepath\$ArchiveFolder" -Recurse -Force
}
代码有效。但我也收到一条错误消息:
您不能调用空值表达式
我该如何解决这个问题?
Get-ChildItem
默认返回文件和文件夹。如果您只需要文件,则应使用-File
。否则,您的$Files
也将包含文件夹(因为它们具有LastWriteTime
属性)。
如果您尝试在文件夹上运行.DirectoryName.Replace($filepath,"")
,它将返回此类错误,因为您无法在$null
上运行替换。
更新:对于PowerShell 2.0,您可以使用| where { ! $_.PSIsContainer }
(source)
在您的错误中,您可以看到哪条线被破坏:
$NewPath = $File.DirectoryName.Replace($filepath,"")
要解决此类问题,您只需列出所有涉及的变量并检查其值即可。你可以这样做:
$File
$File.DirectoryName
Pause
$NewPath = $File.DirectoryName.Replace($filepath,"")
使用Pause
非常有用,因为在继续之前它会等待你按Enter键。