0

Code:

$timestamp = (Get-Date).ToString('yyyy-MM-dd')
$originalSource = Get-ChildItem "D:\output\csv\*.csv", "D:\output\csv\Billing\*.csv" | Where-Object {($_.LastWriteTime -ge [datetime]::today)}
$source = $originalSource
$target = "D:\output\csv\bin\$timestamp.7z"
$housekeepZipFile = "D:\output\csv\bin\*"


####Using 7z to zip 
if (-not (test-path "D:\bin\7-Zip\7z.exe")) {throw "D:\bin\7-Zip\7z.exe needed"}
set-alias sz "D:\bin\7-Zip\7z.exe"
sz a -mx=0 -mhe=on -m0=lzma2 $target $source

I have tried above powershell. When i pumped files into csv and billing folder, it will create archive file that I want. When there is no today's date input file pumped into the csv and billing folder, 7zip random pull window files and create archive to me.

Question: How can I set that only create archive if there's a file with current date or create archive (with empty folder) if there no file with current date. P/S: I tried to put where-object to filter lastwritetime but seems not useful enough.

TylerH
  • 20,799
  • 66
  • 75
  • 101
user3542587
  • 313
  • 1
  • 4
  • 13

1 Answers1

0

you just have to add an if after calling Get-ChildItem

$timestamp = (Get-Date).ToString('yyyy-MM-dd')
$originalSource = Get-ChildItem "D:\output\csv\*.csv", "D:\output\csv\Billing\*.csv" | Where-Object {($_.LastWriteTime -ge [datetime]::today)}
if($originalSource) {
  $source = $originalSource
  $target = "D:\output\csv\bin\$timestamp.7z"
  $housekeepZipFile = "D:\output\csv\bin\*"


  ####Using 7z to zip 
  if (-not (test-path "D:\bin\7-Zip\7z.exe")) {throw "D:\bin\7-Zip\7z.exe needed"}
  set-alias sz "D:\bin\7-Zip\7z.exe"
  sz a -mx=0 -mhe=on -m0=lzma2 $target $source
}

so only if files are found the archive will be created

Guenther Schmitz
  • 1,955
  • 1
  • 9
  • 23
  • https://stackoverflow.com/questions/56789801/unable-to-compress-a-file-with-powershell-2-0 currently am using this method to archive file. however, the number of file will be vary every day. 1st day 20 csv, 2nd day 19 csv. total files i want is 21 files and must not be more and less. will this 7z method useful? – user3542587 Feb 05 '20 at 14:16
  • 1
    what do you mean? did you ask the question twice? is this the wrong answer? – Guenther Schmitz Feb 05 '20 at 14:18