我想创建一个脚本来帮助复制在某个时间范围内修改的文件。我想将$EndDate
参数保留为可选参数,在这种情况下,我希望脚本使用今天的日期作为默认值。
下面是脚本:
param (
[Parameter(Mandatory=$True)]
[string]$Path,
[Parameter(Mandatory=$True)]
[string]$targetDir,
[Parameter(Mandatory=$True)]
[string]$BeginDate,
[Parameter(Mandatory=$False)]
[string]$EndDate,
[switch]$force
)
Get-ChildItem -Path $Path -Recurse | Where-Object {$_.LastWriteTime -gt $BeginDate -and $_.LastWriteTime -lt $EndDate }| cp -Destination $targetDir -Force
[Parameter(Mandatory=$False)][string]$enddate = Get-Date,
给它一个默认值,你可能还想格式化它:
[Parameter(Mandatory=$False)][string]$enddate = (Get-Date -f ddMMyy)
[Parameter(Mandatory=$False)]
[string]$EndDate = Get-Date
我不建议格式化它,因为这会将其从DateTime
类型转换为String
数据类型,从而导致您的Where-Object
出现问题编辑:刚刚意识到您明确地投射为[string]
。AFAIK 这会破坏您的Where-Object
,因为您将DateTime
与字符串进行比较(除非 PowerShell 自动将$EndDate
转换为DateTime
......
这使它更加强大。如果 4c74356b41 的答案是你想要的,那就去吧!
param (
[Parameter(Mandatory=$True)]
[string]$Path,
[Parameter(Mandatory=$True)]
[string]$targetDir,
[Parameter(Mandatory=$True)]
[string]$BeginDate,
[Parameter(Mandatory=$False)]
[string]$EndDate = (Get-Date),
[switch]$force
)
try{
[datetime]$BeginDate = $BeginDate
}catch{
Write-Output "$BeginDate is not a valid datetime"
}
try{
[datetime]$EndDate = $EndDate
}catch{
Write-Output "$EndDate is not a valid datetime"
}
Get-ChildItem -Path $Path -Recurse | Where-Object {$_.LastWriteTime -gt $BeginDate -and $_.LastWriteTime -lt $EndDate }| cp -Destination $targetDir -Force