Please suggest the way forward for this, similarly I have to do for enddate, username etc. sample:
$StartDate, $String = "", ""
$StartDate = Read-Host -Prompt 'Enter the start date of the logs, Ex: 17/07/2017 09:00:00 '
if ($StartDate -and ( $StartDate -ne " ") -and ($StartDate -ne "")) {
$StartDate = $StartDate -replace "`t|`n|`r", ""
$String += " -After '$StartDate'"
} else {
'You did not enter a valid Start date!'
}
echo "Get-EventLog -LogName Application $String"
Get-EventLog -LogName Application $String
Output:
Get-EventLog -LogName Application -After '19/07/2017' Get-EventLog : Cannot bind parameter 'InstanceId'. Cannot convert value " -After '19/07/2017'" to type "System.Int64". Error: "Input string was not in a correct format." At C:\Users\kumars2\Downloads\Santosh\Powershell scripts\Enhancements\View logs examples\small_test.ps1:17 char:13 + Get-EventLog <<<< -LogName Application $String + CategoryInfo : InvalidArgument: (:) [Get-EventLog], ParameterBindingException + FullyQualifiedErrorId : CannotConvertArgumentNoMessage,Microsoft.PowerShell.Commands.GetEventLogCommand
If you want to construct a parameter list for a cmdlet you should use splatting instead of building (partial) string commandlines. You're getting the error you observed because PowerShell passes the entire string " -After '$StartDate'"
as an argument to the parameter -InstanceId
. Also, your date string has the format dd/MM/yyyy
. PowerShell can't automagically convert this string to a DateTime
value, so you need to do that yourself.
$culture = [Globalization.CultureInfo]::InvariantCulture
$pattern = 'dd\/MM\/yyyy'
$StartDate = $StartDate -replace '\s' # remove all whitespace from date string
$EndDate = $EndDate -replace '\s' # remove all whitespace from date string
$params = @{
'LogName' = 'Application'
}
if ($StartDate) {
$params['After'] = [DateTime]::ParseExact($StartDate, $pattern, $culture)
}
if ($EndDate) {
$params['Before'] = [DateTime]::ParseExact($EndDate, $pattern, $culture)
}
Get-EventLog @params