Home > Back-end >  powershell script to create folders named by date and a .1, .2, .3 etc at the end of it, it will be
powershell script to create folders named by date and a .1, .2, .3 etc at the end of it, it will be

Time:06-09

Looking for suggestions on how to solve a little issue, I have powershell script I am working on, it is going to be run say 5 times a day, and will create a folder that is todays days and then like a .1 at the end of it, I will then copy files to that 1 specific folder, then the next time the script runs the folder will be .2 then copy files to that folder, but the problem that I am running into doing as if/elseif statements is the 2nd time it runs it says the .1 file already exists and stops running.

any thoughts on how to get around this?

here is my current set up

if ($Folder1 -eq ".\$((Get-Date).ToString('yyyy-MM-dd')).1") {
    New-Item -ItemType Directory -Path ".\$((Get-Date).ToString('yyyy-MM-dd')).1"
    $Folder1 = ".\$((Get-Date).ToString('yyyy-MM-dd')).1"
} 
elseif ($Folder1 = ".\$((Get-Date).ToString('yyyy-MM-dd')).1"){
    New-Item -ItemType Directory -Path ".\$((Get-Date).ToString('yyyy-MM-dd')).2"
    $Folder2 = ".\$((Get-Date).ToString('yyyy-MM-dd')).2"
}
elseif ($Folder2 -eq ".\$((Get-Date).ToString('yyyy-MM-dd')).2"){
    New-Item -ItemType Directory -Path ".\$((Get-Date).ToString('yyyy-MM-dd')).3"
    $Folder3 = ".\$((Get-Date).ToString('yyyy-MM-dd')).3"
}
elseif ($Folder3 -eq ".\$((Get-Date).ToString('yyyy-MM-dd')).3"){
    New-Item -ItemType Directory -Path ".\$((Get-Date).ToString('yyyy-MM-dd')).4"
    $Folder4 = ".\$((Get-Date).ToString('yyyy-MM-dd')).4"
}
elseif ($Folder4 -eq ".\$((Get-Date).ToString('yyyy-MM-dd')).4"){
    New-Item -ItemType Directory -Path ".\$((Get-Date).ToString('yyyy-MM-dd')).5"
    $Folder5 = ".\$((Get-Date).ToString('yyyy-MM-dd')).5"
}

else {

    "Path doesn't exist."
}

Thanks all!

CodePudding user response:

maybe this might be what you need if I was able to understand your needs. I do validate if the folder for the current date with appended ".n" exists. The "n" is the current folder version starting with 1.

$folder = "c:\temp\"
$today = (Get-Date).ToString('yyyy-MM-dd')
do {
    $i  
    $NewFolder = Join-Path $folder ($today ".$i")
} while (Test-Path $NewFolder)
New-Item -Type Directory -Path $NewFolder | Out-Null
  • Related