Junaid
Junaid

Reputation: 603

Powershell file extension match .*

I need to match the extension to ".*" to return all files in a given source folder that have the LastWriteTime of $lwt as shown in code. The user can either provide a specific extension like ".csv" but one is not provided then the script will simply search all files. But i can't match the extension with ".*" to return all files.

[CmdletBinding()]
param (
[Parameter(Mandatory=$true)][string]$source,
[Parameter(Mandatory=$true)][string]$destination,
[string]$exten=".*",
[int]$olderthandays = 30
)
$lwt = (get-date).AddDays(-$olderthandays)

if(!(Test-Path $source)){
    Write-Output "Source directory does not exist."
    exit
}

if(!(Test-Path $destination)){
    Write-Output "Source directory does not exist."
    exit
}

if($olderthandays -lt 0){
    Write-Output "You can't provide a negative number of days. If you want everything deleted simply provide 0 for number of days."
    exit
}

if(!$exten.StartsWith(".")){
    $exten = "."+$exten
    $exten
}


try{
    Get-ChildItem $source -ErrorAction Stop | ?{$_.LastWriteTime -lt $lwt -AND $_.Extension -eq $exten} | foreach {
        Write-Output $_.FullName 
       # Move-item $_.FullName $destination -ErrorAction Stop
    }
}
catch{
    Write-Output "Something went wrong while moving items. Aborted operation."
}

How can this be achieved ?

Upvotes: 1

Views: 2440

Answers (2)

Glen Buktenica
Glen Buktenica

Reputation: 332

Move your extension filter back into child item and use . or *.

[CmdletBinding()]
param 
(
    [Parameter(Mandatory=$true)][string]$source,
    [Parameter(Mandatory=$true)][string]$destination,
    [string]$exten="*.*",
    [int]$olderthandays = 30
)
$lwt = (get-date).AddDays(-$olderthandays)

if(!(Test-Path $source)){
    Write-Output "Source directory does not exist."
    exit
}

if(!(Test-Path $destination)){
    Write-Output "Source directory does not exist."
    exit
}

if($olderthandays -lt 0){
    Write-Output "You can't provide a negative number of days. If you want everything deleted simply provide 0 for number of days."
    exit
}

if(!$exten.StartsWith('*.')){
    $exten = "*."+$exten
    $exten
}


try{
    Get-ChildItem $source -Filter $exten -ErrorAction Stop | ?{$_.LastWriteTime -lt $lwt} | foreach {
        Write-Output $_.FullName 
       # Move-item $_.FullName $destination -ErrorAction Stop
    }
}
catch{
    Write-Output "Something went wrong while moving items. Aborted operation."
}

Upvotes: 0

ESG
ESG

Reputation: 9425

The Extension of a file will never be .*.

You could try:

$exten = "*.$exten"
Get-ChildItem $source -ErrorAction Stop -Filter $exten | ?{$_.LastWriteTime -lt $lwt} | foreach { ... }

Upvotes: 1

Related Questions