0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Windows VBS/PowerShell にて日付バックアップフォルダを削除するスクリプト

Posted at

日付バックアップフォルダ *1

とある現場で毎日”日付フォルダ”(Windows)が作成されていて容量の関係から4日以降は削除してほしいと。そんなんで手で消すのが面倒なのでスクリプトを作った次第です。
*1 自分が勝手に呼んでますw 

こんなフォルダ構成になっています

言葉だとピンとこないかもなのでこんな感じです。

image.png

VBScript で作ってみた

汎用的に使えるよう引数で対象フォルダを指定。日付フォルダの”日付”は実際の日であることを確認してから実際のフォルダを消すようにしてみます。

Windowsスケジューラで動かす予定なので上位はWindowsバッチファイルを用意しておきます。

sample1.bat
cscript sample1.vbs C:\tmp 1
sample1.vbs
Option Explicit

Dim arg1, arg2
Dim objFSO, dateBefore

arg1 = Wscript.Arguments(0)
arg2 = Wscript.Arguments(1)

Set objFSO = CreateObject("Scripting.FileSystemObject")

if objFSO.FolderExists(arg1) then
  dateBefore = DateAdd("d", -4, DATE())
  dateBefore = Replace(dateBefore, "/", "")
  'Wscript.Echo dateBefore

  Dim objFolder, objSubFolers, item

  Set objFolder = objFSO.GetFolder(arg1)
  Set objSubFolers = objFolder.SubFolders

  '
  For Each item In objSubFolers
    Wscript.Echo item.Name

    If item.Name < dateBefore Then
      If IsDate(Mid(item.Name, 1, 4) &"/"& Mid(item.Name, 5, 2) &"/"& Mid(item.Name, 7, 2)) = True Then
        If arg2 = 1 Then
          Wscript.Echo " delete " , arg1 &"\"& item.Name
          objFSO.DeleteFolder arg1 &"\"& item.Name, True
        Else
          Wscript.Echo " delete test" , arg1 &"\"& item.Name
        End If
      End If
    End If
  Next
End if

VBScript ってWindowsから完全削除?!

2027年にWindows上から完全に削除されるらしいですね。

PowerShellでも作ってみる

VBScriptは、2027年で廃止だから!と中の人に怒られそうなのでPowerShellでも作ってみました。

sample2.bat
powershell -executionpolicy bypass -File sample2.ps1 C:\tmp 1
sample2.ps1
Param($arg1, $arg2)

function IsDate([string]$cdate) {
  try {
    $tmp = [Datetime]::Parse($cdate)
    $True
  } catch {
    $False
  }
}

$objSubFolers = Get-ChildItem -Directory $arg1 | Select-Object name
$dateBefore = (Get-Date).AddDays(-4).ToString("yyyyMMdd")

foreach($item in $objSubFolers) {
  Write-Host $item.name

  if($item.name -lt $dateBefore) {
    $ymd1 = $item.name[0..3] -Join ''
    $ymd2 = $item.name[4..5] -Join ''
    $ymd3 = $item.name[6..7] -Join ''
    $ymd = $ymd1, "-", $ymd2, "-", $ymd3 -Join ''

    $isDateFlag = IsDate($ymd)
    if ($isDateFlag -eq $True) {
      $delteFile = $arg1 + "\" + $item.name
      if ($arg2 -eq 1) {
        Write-Host " delete " , $delteFile
        Remove-Item -Path $delteFile -Force
      } else {
        Write-Host " delete test " , $delteFile
      }
    }
  }
}

最後に

WSL いれてマウントして・・・とやれば簡単なのですが、現場でそれやると怒られるw しやーないすね。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?