2013-08-05 2 views
1

В качестве части автоматизации резервного копирования некоторых наших лог-файлов разработки я использую скрипт Powershell и хотел бы переименовать файл 7zip, который я только что создал, чтобы соответствовать последней части имени первого файл и последнюю часть последнего файла в архиве.Переименование zip для соответствия его содержимому с помощью PowerShell

Например, У меня есть три файла: file1-03082013.log, file2-04082013.log и file3-05082013.log, они сжаты с использованием автоматического сценария Powershell и 7zip для создания log.zip. Теперь я хочу переименовать log.zip в log-03082013 - 05082013 (сопоставляя последнюю часть первого файла и последнюю часть последнего файла в только что созданном архиве).

Вот полный сценарий, который я создал таким образом. (Я довольно новичок в написании сценариев в Powershell, поэтому любые комментарии о том, как улучшить мой существующий скрипт, также приветствуются) Надеюсь, вы, ребята, можете хоть как-то помочь! Заранее спасибо!

#Variables 

$Source = "C:\Path\" 
$Destination = "C:\ZIP" 
$Temp = "C:\Templog\" 
$Previous = "C:\Templog\" 
$programma = "C:\Program Files\7-Zip\7z.exe" 

#Copy files to TempFolder 

Function CopyFile 
{ 
Copy-Item -Recurse -Filter "*.svclog" -path $Source -Destination $Temp 
} 
CopyFile 

#Delete Old Log Files on server 

Function DelOldFile 
{ 
if (Test-Path $Source) 
{ 
$Days = "7" 
$Now = Get-Date 
$LastWrite = $Now.AddDays(-$days) 
$Files = get-childitem $Source -include *.svclog -recurse |Where {$_.LastWriteTime -le "$LastWrite"} 
foreach ($File in $Files) 
{write-host "Deleting file $File" -foregroundcolor "Red"; Remove-Item $File | out-null} 
} 
Else 
{Write-Host "The folder $Source doesn't exist! Check the folder path!" -foregroundcolor "red"} 
} 
DelOldFile 

#Create .zip archive from files and folders in Temp folder and copy to destination folder using 7zip. 

Function ZipFile 
{ 
Start-Process $programma -ArgumentList "a $Destination\Log.zip $Temp" -Wait -PassThru 
} 
ZipFile 

#Delete Temp Folder 

Function GetPrevious 
{ 
if (Test-Path $Previous){ 
    Remove-Item $Previous -Recurse -Force 
    } 
} 
GetPrevious 

ответ

0

Это должно помочь вам здесь функция, чтобы получить имя файла почтового индекса на основе ваших требований, просто передать его местоположение ваших файлов журналов:

function Get-ZipFileName 
{ 
    param 
    ($logPath) 

    # Get a list of files, remove the extension and split on the hyphen, # 
    # then take the second part of the array 
    $filenames = gci -Path $logPath -Filter "*.log" | % { $($_.Basename -split "-")[1] } 

    # Get the first item in the now sorted list 
    $first = $filenames | Sort-Object | Select-Object -First 1 

    # Get the first item in the sorted list, now descending to get the last 
    $last = $filenames | Sort-Object -descending | Select-Object -First 1 

    # return the filename 
    "log-{0} - {1}" -f $first, $last 
} 

Я хотел бы предложить вам посмотреть на используя немного другой формат даты, который будет сортироваться лучше, yyyymmdd будет сортироваться лучше, чем ddmmyyyy.

+0

Это сделало трюк. Большое спасибо. Я отредактировал и подстроил скрипт в соответствии с нашими потребностями. Огромное спасибо! Есть ли способ поделиться моим завершенным скриптом, чтобы он был доступен для всех? – RoelofW

+0

Рад помочь, вы могли бы добавить свой заполненный скрипт в качестве ответа, если считаете, что это поможет другим. –

+0

Ах да, конечно. Еще раз спасибо. – RoelofW

1

Использование Davids help В конце концов я придумал следующий завершенный скрипт. Надеюсь, это поможет вам, ребята, в будущих проблемах.

Пожалуйста, дайте мне знать, если у вас есть какие-либо комментарии или вопросы по этому готовому сценарию.

#============================================= 
# 
# Recursive Log Search, Archive & Del Script 
# Ver. 1.0.0 06/08/2013 
# Roelof Wijnholds 
# 
#============================================= 

#Enter parentfolder 
$sPath = "Path\to\parent\folder" 

#Folder where the archive will be created (if it doesn't exist, folder will be created) 
$tPath = "archive" 

#Path to 7zip executable 
$7z = "C:\Program Files\7-Zip\7z.exe" 


checkForWebservices $sPath 5 

#Check for bin & log folder & *.extension file 
function checkValidWebservice($path) 
{ 
    If((Test-Path $path\bin) -and (Test-Path $path\log) -and (Test-Path $path\*.svc)){ 
     write-host "Valid webservice structure found: " $path 
     return $true 
    }else{ 
     return $false 
    } 
} 

function checkForWebservices($path, $max, $level = 0) 
{ 
    $path = (Resolve-Path $path).ProviderPath 
    foreach ($item in @(Get-ChildItem $path)) 
    { 
     if ($item.Attributes -eq "Directory") 
     { 
      if(checkValidWebservice $path) 
      { 
       #Create name for compressed file 
       $fileName = CreateCompressFileName $path 
       if($fileName -ne $null) 
       { 
        #Compress files in folder 
        CompressAndRemoveLogFiles $fileName $path 
        Write-Host "Compressing and removing files" 
       } 
       return 
      }else{ 
       checkForWebservices $item.PSPath $max ($level + 1) 
      } 

      #Break if recursive goes to DEEP 
      if ($level -eq $max) 
      { 
       Write-Host "Max depth" $path\$item - $level 
       return 
      } 
     } 
    } 
} 

function CreateCompressFileName($path) 
{ 
    #Get startingdate from file 
    $fileNameFrom = Get-ChildItem $path\log | Where {$_.Extension -eq ".svclog"} | Sort-Object name | Select-Object -first 1 
    if($fileNameFrom -ne $null) 
    { 
     #Get first file 
     if($fileBaseName -eq $null) 
     { 
      #File is supposed to be servicename_20130508.svclog 
      $fileBaseName = $fileNameFrom.BaseName.SubString(0,$fileNameFrom.BaseName.length - 9) 
     } 
     $fileNameFrom = $fileNameFrom.BaseName.SubString($fileNameFrom.BaseName.length - 8,8) 
     #Get last file 
     $fileNameTo = Get-ChildItem $path\log | Where {$_.LastWriteTime -lt ((Get-Date).Date) -and $_.Extension -eq ".svclog" } | Sort-Object name -descending | Select-Object -first 1 

     if($fileNameTo -ne $null) 
     { 
      $fileNameTo = $fileNameTo.BaseName.SubString($fileNameTo.BaseName.length - 8,8) 
      #Compile the name 
      return $fileBaseName+"_"+$fileNameFrom+"_"+$fileNameTo 
     } 
    } 
    return $null  
} 

function CompressAndRemoveLogFiles($fileName, $path) 
{ 
    $cFiles = Get-ChildItem $path\log | Where {$_.LastWriteTime -lt ((Get-Date).Date) -and $_.Extension -eq ".svclog" } 

    Foreach ($item in $cFiles) 
    { 
     #Add file to archive 
     $endPath = $path.TrimStart($sPath) 
     $target = "{0}\{1}\{2}\{3}" -f $sPath,$tPath,$endPath,$fileName 

     $result = & $7z a -mx5 -mmt $target $item.FullName 
     #Cleanup files 
     Remove-Item $path\log\$item 
    } 
} 
Смежные вопросы