PowerShell 函数返回布尔值不起作用

问题描述 投票:0回答:2

在我们的 Active Directory 中,我们有两个用于第三方系统的用户同步的组。 第一组包含该系统的所有用户。第二组包含第一组中已禁用或过期的所有成员。这是获得许可所必需的。

现在我想使用 PowerShell 脚本自动执行该过程。


$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
    }
    ""
}

这行不通。该脚本始终将广告用户添加到第二组中。

为什么?

function powershell
2个回答
0
投票

您的函数输出多个值。例如,它总是返回:

$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
    }
    
}

-1
投票

非常感谢,解决了我的问题。 我想知道这是否与其他脚本语言以不同的方式工作。我必须给出一个明确的返回值。

无论如何:再次感谢!

© www.soinside.com 2019 - 2024. All rights reserved.