[英]PowerShell - Invalid cast from System.DateTime to System.ConsoleColor
# Get Password Expire Date
$EXPDTE = [datetime]::FromFileTime((Get-ADUser -Identity $USERNAME -Properties "msDS-UserPasswordExpiryTimeComputed")."msDS-UserPasswordExpiryTimeComputed")
# Subtract Expire Date from Today
$DAYSTOEXP = (($EXPDTE)-(Get-Date)).Days
Write-Host "{0}" -f $EXPDTE
Gives me the following error: 给我以下错误:
Write-Host : Cannot bind parameter 'ForegroundColor'. Cannot convert value "1/14/2018 10:39:12 AM" to type
"System.ConsoleColor". Error: "Invalid cast from 'System.DateTime' to 'System.ConsoleColor'."
At C:\Users\\Documents\PowerShell\ADPasswordExpire.ps1:14 char:21
+ Write-Host "{0}" -f $EXPDTE
+ ~~~~~~~
+ CategoryInfo : InvalidArgument: (:) [Write-Host], ParameterBindingException
+ FullyQualifiedErrorId : CannotConvertArgumentNoMessage,Microsoft.PowerShell.Commands.WriteHostCommand
This only happens when using Write-Host and the -f
operator. 这仅在使用Write-Host和-f
运算符时发生。
If I do: 如果我做:
$EXPDTE $ EXPDTE
Sunday, January 14, 2018 10:39:12 AM
$EXPDTE.ToString() $ EXPDTE.ToString()
1/14/2018 10:39:12 AM
What am I missing here when using -f
? 使用-f
时,我在这里缺少什么?
In your case, -f
is short for -ForeGroundColor
. 在您的情况下, -f
是-ForeGroundColor
。
Remove Write-Host
, or use a subexpression: 删除Write-Host
,或使用子表达式:
"{0}" -f $EXPDTE
Write-Host $("{0}" -f $EXPDTE)
Edit 编辑
With a [datetime]
object, you should specify the date format. 使用[datetime]
对象,您应该指定日期格式。 Check out this ss64 page . 签出此ss64页面 。 Eg use d
for ShortDatePattern or D
for LongDatePattern. 例如,将d
用于ShortDatePattern或将D
用于LongDatePattern。 If you require a different output string, please reply to comment. 如果您需要其他输出字符串,请回复评论。
"Date to Expiry: {0:d}" -f $EXPDTE
"Days to Expire: {0}"-f $DAYSTOEXP
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.