powershell - Powershell 日期时间空值
问题描述
我正在开发一个关于 AD 用户帐户过期日期的 powershell。但是我遇到了一个问题,它无法传递空参数来将 AD 用户帐户过期日期设置为 NEVER。
请帮忙!谢谢。
https://i.stack.imgur.com/Zt8sv.png
下面是我的脚本。
import-module C:\PS\color_menu.psm1
CreateMenu -Title "AD User Account Expire Tools" -MenuItems "View the User Account Expire Date","Set the User Account Expire Date","Exit" -TitleColor Red -LineColor Cyan -menuItemColor Yellow
do {
[int]$userMenuChoice = 0
while ( $userMenuChoice -lt 1 -or $userMenuChoice -gt 3) {
Write-Host "1. View the User Account Expire Date"
Write-Host "2. Set the User Account Expire Date"
Write-Host "3. Exit"
[int]$userMenuChoice = Read-Host "Please choose an option"
switch ($userMenuChoice) {
1{$useraccount = Read-Host -prompt "Please input an user account"
Get-ADUser -Identity $useraccount -Properties AccountExpirationDate | Select-Object -Property SamAccountName, Name, AccountExpirationDate
Write-Host "";
Write-Host "";
}
2{$useraccount = Read-Host -prompt "Please input an user account"
[Datetime]$expiredatetime = Read-Host -prompt "Please input the user expire date and time (DateFormat: MM/dd/yyyy)"
Set-ADAccountExpiration -Identity $useraccount -DateTime $expiredatetime
Write-Host "";
Write-Host "";
Get-ADUser -Identity $useraccount -Properties AccountExpirationDate | Select-Object -Property SamAccountName, Name, AccountExpirationDate
Write-Host "";
Write-Host "";
}
3{Write-Host "Exit";Exit
}
default {Write-Host "Incorrect input" -ForegroundColor Red
Write-Host "";
Write-Host "";
}
}
}
} while ( $userMenuChoice -ne 3 )```
解决方案
使用Clear-ADAccountExpiration将帐户设置为永不过期。
此外,您不能在调用中直接使用[datetime]
类型约束变量Read-Host
,因为不支持将空字符串 ( ''
)转换[datetime]
为(您看到的错误)。
这是解决此问题的一种方法:
do {
# Read the input as a string first...
$expiredatetimeStr = Read-Host -prompt "Please input the user expiration date and time (DateFormat: MM/dd/yyyy) or just press Enter to make the account non-expiring"
# ... and then try to convert it to [datetime]
if ($expiredatetime = $expiredatetimeStr -as [datetime]) {
Set-ADAccountExpiration -Identity $useraccount -DateTime $expiredatetime
}
elseif ($expiredatetimeStr.Trim() -eq '') { # empty input -> no expiration
Clear-ADAccountExpiration -Identity $useraccount
}
else { # invalid input
Write-Warning 'Please enter a valid date.'
continue
}
break
} while ($true)
推荐阅读
- java - 在春季使用 OneToMany JPA 关系中的子数据获取父数据
- php - 根据自定义字段值隐藏添加到购物车按钮 - woocommerce
- mysql - 如何防止整个服务器在不相关表的 ALTER 期间被锁定?
- javascript - React-day-picker 警告
- azure - Azure 门户添加后不会加载 IP 限制,无法移除限制
- docker - 带有 ceph rbd 的 Kubernetes
- unity3d - Unity3D 动态网格带孔
- c# - 有没有办法指示编译器不要为匿名委托创建内部类?
- c++ - QTcpSocket 发送的数据比想要的多 - Qt/C++
- oracle - 显示 MaxValue 的表单生成器