【发布时间】:2019-09-20 01:34:35
【问题描述】:
我对 PowerShell 还是很陌生,如果我有一些需求,我现在会做些什么,我会在网上搜索并将代码修改为我需要的。
现在,我正在尝试从我们的服务器中提取 RDP 用户登录信息。我设法获得了一些代码,对其进行了更新,以便我可以通过调用命令远程运行它。但是,我对其中一个变量有疑问,如果我输入一个日期值,例如2019 年 9 月 1 日或 2019 年 9 月 1 日,脚本有效。但是如果我使用 (Get-Date).AddDays(-7),它就行不通了。昨天整个下午我一直在测试这个脚本,但就我的一生而言,我仍然无法让它工作:(
这是我遇到问题的代码部分:
#$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
这是我正在测试的完整脚本。感谢有人可以就如何在不使用静态日期的情况下完成这项工作提供一些提示。提前感谢您的帮助!
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
【问题讨论】:
-
请限定“不起作用”和“不起作用” - 您是否收到错误、意外结果或无结果?
-
同意。您是否收到错误消息?
标签: powershell date get-winevent