将上次登录时间与日期进行比较时出错

时间:2017-08-11 18:02:04

标签: powershell

我编写了一个脚本,它将获取计算机上所有用户的所有登录信息,并过滤掉30天以上的任何用户。我们希望使用它来更准确地计算我们按用户费率支付的一些许可证。该脚本还会过滤掉我们使用的管理员帐户以及系统和服务帐户。

这是剧本。

#This script will check which users have logged on in the last X days
#Set Variables
#Change the number in the parenthesis after adddays to change how far back to filter
#example (get-date).adddays(-30) gets all logins for the last 30 days from     today (-60) would be the last 60 days

$AuditDate = (get-date).adddays(-30)
$ComputerName = $env:COMPUTERNAME
$CurrentDate = Get-Date -UFormat "%Y-%m-%d"

#Delete any previously created files
Get-ChildItem -Path "C:\PowerShellScripts\LastLogon" -Recurse |
Where-Object CreationTime -lt (Get-Date).AddDays(-0) | Remove-Item - ErrorAction SilentlyContinue

#The Login Profile is filtered here
Get-WmiObject -class Win32_NetworkLoginProfile | 
Where-Object -FilterScript {$_.FullName -notlike "*Agvance*"} | 
Where-Object -FilterScript {$_.FullName -notlike "*Sophos*"} |
Where-Object -FilterScript {$_.FullName -notlike "*SSI*"} |
Where-Object -FilterScript {$_.FullName -ne "AgvAdmin"} |
Where-Object -FilterScript {$_.FullName -ne ""} | 
Where-Object -FilterScript {$_.Name -notlike "*SYSTEM*"} |
Where-Object -FilterScript {$_.Name -notlike "*SERVICE*"} |
Where-Object -FilterScript {($_.ConvertToDateTime($_.LastLogon)) -ge $AuditDate} | 
Select-Object  Name,@{label='LastLogon';expression={$_.ConvertToDateTime($_.LastLogon)}} | Export-Csv    C:\PowerShellScripts\LastLogon.csv -NoTypeInformation

#The user count is created here
$number = (Import-Csv C:\PowerShellScripts\LastLogon.csv | measure | % {    $_.Count})

#The file is renamed to include computername, date, and user count
rename-item -path C:\PowerShellScripts\LastLogon.csv -NewName 
C:\PowerShellScripts\LastLogon-$ComputerName-$CurrentDate-UserCount-$number.csv 

该脚本按预期工作,但在运行时我收到此错误。

Exception calling "ConvertToDateTime" with "1" argument(s): "Exception    calling "ToDateTime" with "1" argument(s): "Specified 
argument was out of the range of valid values.
Parameter name: dmtfDate""
At C:\Agvance Updates\LastLogon.ps1:22 char:29
+ Where-Object -FilterScript {$_.ConvertToDateTime($_.LastLogon) -ge $AuditDate} |
+                                ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo          : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : ScriptMethodRuntimeException

我尝试过比较$ .ConvertToDateTime($ .LastLogon)和$ AuditDate的不同方法。这种方式有效,但我想用$ .ConvertToDateTime($ .LastLogon)摆脱错误。是否有更好的方法来获取此日期并将其与过滤进行比较?

1 个答案:

答案 0 :(得分:2)

LastLogon可能为空,ConvertToDateTime()不接受空值。

要排除那些没有LastLogon值的条目(例如,如果配置文件从未登录过),请尝试:

Get-WmiObject -class Win32_NetworkLoginProfile | 
[...]
Where-Object -FilterScript {![System.String]::IsNullOrWhiteSpace($_.LastLogon)} |
Where-Object -FilterScript {($_.ConvertToDateTime($_.LastLogon)) -ge $AuditDate} |
[...]