Powershell文件扩展名匹配。*

时间:2016-07-28 01:27:52

标签: powershell file-extension

我需要将扩展​​名与“。*”匹配,以返回给定源文件夹中具有$ lwt的LastWriteTime的所有文件,如代码所示。用户可以提供特定的扩展名,如“.csv”,但不提供一个,然后脚本将只搜索所有文件。但我无法将扩展名与“。*”匹配以返回所有文件。

[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."
}

如何实现这一目标?

2 个答案:

答案 0 :(得分:1)

文件的Extension永远不会是.*

你可以尝试:

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

答案 1 :(得分:0)

将您的扩展程序过滤器移回子项目并使用或*。

[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."
}