Hi All,
I am still a newbie in PowerShell, and I normally search for existing scripts, study it and modify it to my requirements. Right now, I have been testing a script, run thru Task Scheduler, that will provide me successful RDP login information from our servers, and save the result to a CSV file. However, I have been stuck all afternoon on a date variable that will provide the start time in my filter.
The script will work if put the date itself on the variable, but fails everytime I try to use the Get-Date:
#$StartDate = (Get-Date).AddDays(-7).ToString(“dd-MMM-yyyy”) #–> does not work
#$StartDate = (Get-Date).AddDays(-7) #–> does not work
$StartDate = “1-Sep-2019” #–> Works
$StartDate = “9/1/2019” #–> Works
Can anyone help to review this code, and for the life of me, I can’t understand why using Get-Date does not work. Here is the full script I am trying to run, and thanks in advance for any hint on how to resolve this:
Start-Transcript -path "D:\temp\Get-User-Logins_$(Get-Date -f yyyyMMddHHmm).log"
$Computers = Get-Content "D:\temp\Server list.txt"
Write-Output "Processing the computers"
$LogEntries = Invoke-Command -Computername $Computers -Authentication NegotiateWithImplicitCredential -ThrottleLimit 10 -ErrorAction "SilentlyContinue" -Scriptblock {
# Get the date 7 days ago as start date
#$StartDate = (Get-Date).AddDays(-7).ToString("dd-MMM-yyyy") #--> does not work
#$StartDate = (Get-Date).AddDays(-7) #--> does not work
$StartDate = "1-Sep-2019" #--> Works
$StartDate = "9/1/2019" #--> Works
$LogOutput = @()
$LogFilter = @{
LogName = 'Microsoft-Windows-TerminalServices-LocalSessionManager/Operational'
ID = 22
StartTime = $StartDate
}
$LogOutput = Get-WinEvent -FilterHashtable $LogFilter
$LogOutput | Foreach {
$entry = [xml]$_.ToXml()
[array]$EVOutput += New-Object PSObject -Property @{
TimeCreated = $_.TimeCreated
User = $entry.Event.UserData.EventXML.User
IPAddress = $entry.Event.UserData.EventXML.Address
EventID = $entry.Event.System.EventID
EventRecordID = $entry.Event.System.EventRecordID
ServerName = $env:COMPUTERNAME
}
}
$EVOutput
}
Write-Output "Writing the output to the file"
$FilteredOutput += $LogEntries | Select ServerName, TimeCreated, User, IPAddress, EventRecordID, @{Name='Action';Expression={
if ($_.EventID -eq '22'){"Shell start"}
}
}
$FilePath = "D:\temp\$(Get-Date -f yyyyMMddHHmm)_RDP_Report.csv"
$FilteredOutput | Sort -Property ServerName, TimeCreated | Export-Csv $FilePath -NoTypeInformation
Write-Output "Writing File: $FilePath"
Write-Output "Done!"
Stop-Transcript