Function PowerShell函数返回布尔值';行不通
你好 在我们的Active Directory中,我们有两个组用于第三方系统的用户同步。 第一个组包含该系统的所有用户。第二个组包含第一个组中禁用或过期的所有成员。这是许可证发放所必需的 现在,我想使用PowerShell脚本自动化该过程Function PowerShell函数返回布尔值';行不通,function,powershell,Function,Powershell,你好 在我们的Active Directory中,我们有两个组用于第三方系统的用户同步。 第一个组包含该系统的所有用户。第二个组包含第一个组中禁用或过期的所有成员。这是许可证发放所必需的 现在,我想使用PowerShell脚本自动化该过程 $d3_UserGrp = Get-ADGroup -Identity "d3_users" $d3_DisabledUserGrp = Get-ADGroup -Identity "d3_Users disabled v2&q
$d3_UserGrp = Get-ADGroup -Identity "d3_users"
$d3_DisabledUserGrp = Get-ADGroup -Identity "d3_Users disabled v2"
Function IsUserActive
{
param(
$AD_User
)
#$return = $false
$AD_User.SamAccountName
$AD_User.AccountExpirationDate
$now = get-date
if ( $AD_User.AccountExpirationDate -ne $null ) {
#"Account has expiration date"
if ( $AD_User.AccountExpirationDate -lt $now ) {
"Account expired"
} else {
#Write-Host "account not expired"
}
} elseif ( $AD_User.Enabled -ne $true ) {
"Account not active"
} else {
#"everything fine with that account"
#return $true
}
#write-host "return is $return"
#return $false
}
$grp = Get-ADGroupMember $d3_UserGrp
foreach ( $username in $grp )
{
$ad_user = Get-ADUser -Identity $username -Properties AccountExpirationDate, DisplayName
if ( IsUserActive -AD_User $ad_user )
{
write-host "add $ad_user.SamAccountName"
#Add-ADGroupMember -Identity $d3_DisabledUserGrp -Members $ad_user -Confirm:$false
}
else
{
write-host "remove $ad_user.SamAccountName"
#Remove-ADGroupMember -Identity $d3_DisabledUserGrp -Members $ad_user -Confirm:$false
}
""
}
这行不通。脚本总是将广告用户添加到第二个组中
知道为什么吗
向您致意您的函数输出多个值。例如,它总是返回:
$AD_User.SamAccountName
$AD_User.AccountExpirationDate
这意味着IsUserActive-AD_User$AD_User
的计算结果总是为true
考虑:
$test = @(1, $null, $false)
if ($test) { 'It is true' } else { 'It is false' }
即使多个值单独都应为false,也不会为false:
$test = @($null, $false)
if ($test) { 'It is true' } else { 'It is false' }
您需要确保函数的输出只是返回值。要做到这一点,请确保在希望写入屏幕而不返回输出时使用Write Host
尝试:
非常感谢,这解决了我的问题。 我想知道这是否与其他脚本语言的工作方式不同。在这里,我必须给出一个显式的返回值
永远不要少:再次感谢 只是想指出一点,在您的示例中,所有返回语句都被注释掉了,因此不起作用:)。我希望这不是问题所在,如果不是,您将如何调用该函数?
Function IsUserActive
{
param(
$AD_User
)
#$return = $false
Write-Host $AD_User.SamAccountName
Write-Host $AD_User.AccountExpirationDate
$now = get-date
if ( $null -eq $AD_User.AccountExpirationDate ) {
Write-Host "Account has expiration date"
if ( $AD_User.AccountExpirationDate -lt $now ) {
Write-Host "Account expired"
$false
} else {
Write-Host "account not expired"
$true
}
} elseif ( $AD_User.Enabled -ne $true ) {
Write-Host "Account not active"
$false
} else {
Write-Host "everything fine with that account"
$true
}
}