我对PowerShell还是很陌生,如果有一些要求,现在我应该做的是,我将在网上搜索并修改所需的代码。
现在,我正在尝试从我们的服务器中提取RDP用户登录名。我设法获取了一些代码,对其进行了更新,以便可以通过invoke-command远程运行它。但是,我对其中一个变量有疑问,如果我输入日期值,例如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
答案 0 :(得分:0)
仍然不确定为什么使用变量$ StartDate对哈希表不起作用,但是我终于找到了满足我要求的解决方案。如果其他人感兴趣,我将不再使用单独的哈希表变量(脚本中的$ LogFilter),而是使用以下行:
$StartDate = (Get-Date).AddDays(-7).ToString("dd-MMM-yyyy")
$LogOutput = Get-Winevent -logname Microsoft-Windows-TerminalServices-LocalSessionManager/Operational | where {$_.TimeCreated -gt $StartDate -and $_.Id -eq "22"}
我设法获得了所需的结果,从而结束了这篇文章。