I'm still quite new with PowerShell, and what I do right now if I have some requirements, I will search the web and modify the code to what I need.
Right now, I am trying to extract RDP user logins from our servers. I have managed to get some codes, updated it so I can run it remotely thru invoke-command. However, I am having issue with one of the variables, wherein if I put a value of a date, e.g. 1-Sep-2019 or 9/1/2019, the script works. But if I use (Get-Date).AddDays(-7), it won't work. I have been testing this script the whole afternoon yesterday, and for the life of me, I can't still make it work :(
This is the part of the code that I am having issues:
#$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
And here is the complete script that I am testing. Appreciate if someone can give some hint on how to make this work without using a static date. Thanks in advance for the help!
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