0

I tried to move some files with a certain extension to another folder using powershell, but I can't put multiple values to the variable "$Ext", this is the code I made. can someone help fix my code?

$Date = Get-Date -UFormat %d-%m-%Y
$Source = 'C:\Source\'
$Temp = 'C:\Backup-Temp\'
$Nas = 'D:\Destination\'
$Ext = '*.zip,*.rar, *.txt '
$SetTime = '-5'

New-Item -Path $Temp -Name Backup-$Date -ItemType "directory"
get-childitem -Path $Source/$Ext -Recurse  |
  Where-object {$_.LastWriteTime -lt (get-date).AddDays($SetTime)} | 
    Move-item -destination $Temp\Backup-$Date
Compress-Archive -Path $Temp\Backup-$Date  -DestinationPath $Nas\Backup-$date.Zip

1 Answers1

0

I haven't tested this but something like this should work.

We are first finding each file recursively with a certain extension, one by one. Then we proceed to move it and compress it.

$Date = Get-Date -UFormat %d-%m-%Y
$Source = 'C:\Source\'
$Temp = 'C:\Backup-Temp\'
$Nas = 'D:\Destination\'
$Ext = "*.zip","*.rar","*.txt"
$SetTime = '-5'

New-Item -Path $Temp -Name "Backup-$Date" -ItemType "directory"

Foreach ($Extension in $Ext) {
get-childitem -Path "$Source" -Recurse |  Where-object {$_.LastWriteTime -lt (get-date).AddDays($SetTime) -and $_.name -like "$Ext"} | Move-item -destination "$Temp\Backup-$Date" | Compress-Archive -Path "$Temp\Backup-$Date"  -DestinationPath "$Nas\Backup-$date.Zip"
}
  • I have tried it, and it is the way I want, thank you for the help. – Tommy Armando Oct 06 '20 at 03:58
  • 1
    It can probably be optimized by specifying the extension in get-childitem so where-object has less to parse. - just add "*.$Extension" to the get-childitem side, and remove the `-and $_.name -like "$ext"` - also i just realized he identifies each individual extension but then loops through with $ext in the where filter. – Robert Cotterman Oct 06 '20 at 04:09