Powershell delete empty folder and files oldre then 14 days
Hej jeg har lavet dette script til at slette filer der ikke har været aktiv i 14 dage og den sletter også tomme mapper.Scriptet virker som det skal på windows 7 men når jeg køre det på den windows server 2008 R2 som det skal køre på så får jeg en fejl. Norgen der kan hjælpe med at finde ud af hvad der sker?.
Se script og fejl her under.
Script:
# Remember set HKLM\SYSTEM\CurrentControlSet\Control\FileSystem\NtfsDisableLastAccessUpdate REG_DWORD to 0 in regedit
# set delete folder path
$dump_path = "E:\Shares\Common\Temp_14_days"
# set max age of files
$max_days = "14"
# get the current date
$curr_date = Get-Date
# log file path
$LogFile = "E:\Tools\Log\14_days_log_{0:yyyy-MM-dd}.log" -f (Get-Date)
# determine how far back we go based on current date
$del_date = $curr_date.AddDays(-$max_days)
# delete the files
$Files = Get-ChildItem $dump_path -Recurse | Where-Object { $_.lastaccesstime -lt $del_date }
foreach ($File in $Files)
{
if($File -ne $NULL)
{
Remove-Item $File.FullName -ErrorVariable "RemoveErr" | out-null
If ($RemoveErr) {
"Error removing $SomeItem"
$RemoveErr >> $LogFile
}
else {
$Get_DaysOld = $curr_date - $File.lastaccesstime
$Days_Old = [System.Math]::Truncate($Get_DaysOld.TotalDays)
"$($File.FullName) | LastAccessDate = $($File.lastaccesstime) | RemovedDate = $curr_date | Days old = $Days_Old " >> $LogFile
}
}
else
{
"No Files deleted" >> $LogFile
}
}
$fso = New-Object -ComObject "Scripting.FileSystemObject"
$folder = $fso.GetFolder($dump_path)
remove-emptyfolder $folder
function remove-emptyfolder {
param ($folder)
foreach ($subfolder in $folder.SubFolders){
$notempty = $false
if (($subfolder.Files | Measure-Object).Count -gt 0){$notempty = $true}
if (($subFolders.SubFolders | Measure-Object).Count -gt 0){$notempty = $true}
if ($subfolder.Size -eq 0 -and !$notempty){
"Remove Folder = $($subfolder.Path) | RemovedDate = $curr_date" >> $LogFile
Remove-Item -Path $($subfolder.Path) -Recurse -Force
}
else {
remove-emptyfolder $subfolder
}
}
}
Fejl:
The term 'remove-emptyfolder' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again.
At E:\Tools\Del_older_then_14_days-Copy.ps1:51 char:19
+ remove-emptyfolder <<<< $folder
+ CategoryInfo : ObjectNotFound: (remove-emptyfolder:String) [], CommandNotFoundException
+ FullyQualifiedErrorId : CommandNotFoundException