2013-08-05 1 views
1

일부 개발 로그 파일의 백업 자동화의 일부로 PowerShell 스크립트를 사용하고 있으며 방금 작성한 7zip 파일의 이름을 첫 번째 파일 이름의 마지막 부분과 일치 시키려합니다 파일과 아카이브의 마지막 파일의 마지막 부분.PowerShell을 사용하여 내용을 일치시키기 위해 zip 이름 바꾸기

예 : 나는 3 개의 파일, 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

이것은 당신이 여기에 귀하의 요구 사항에 따라 zip 파일의 이름을 얻을 수있는 기능입니다 도움이 될 것입니다, 당신의 로그 파일의 그것의 위치를 ​​전달합니다

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를 사용하여 결국 다음과 같은 완성 된 스크립트를 만들었습니다. 앞으로의 도전에 도움이되기를 바랍니다.

완성 된 스크립트에 대한 의견이나 질문이 있으면 알려주십시오.

#============================================= 
# 
# 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 
    } 
}