How can I give today a date as the default value for a parameter in powershell

I would like to create a script that will help copy files modified in the time range. I would like to leave the parameter $EndDateas optional, and in that case I would like the script to use today's date as the default value.

Below is a Script:

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
+4
source share
2 answers
[Parameter(Mandatory=$False)][string]$enddate = Get-Date,

set the default value the same way, you can also format it:

[Parameter(Mandatory=$False)][string]$enddate = (Get-Date -f dd\MM\yy)
+3
source
[Parameter(Mandatory=$False)]
[string]$EndDate = Get-Date

I would not recommend formatting it, as this turns it from type DateTimeto data type String, which leads to problems in yourWhere-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
+2

Source: https://habr.com/ru/post/1681283/


All Articles