重启当前运行的脚本?

时间:2015-09-15 20:10:07

标签: powershell

好的,所以我有这么多。

# Prompts the script user to confirm that the account from
# $userName is indeed the one they want to Terminate
function Get-Confirmation {
    [CmdletBinding(SupportsShouldProcess=$true)]
    param (
        [Parameter(Mandatory=$true)]
        [String]
        $userName
    )

    $confirmMessage = 'Are you sure that {0} is the user that you want to terminate?' -f $userName

    $PSCmdlet.ShouldContinue($confirmMessage, 'Terminate User?')
}

# Code that populates $userName and starts the Termination process
if (Get-Confirmation -User $userName) {
    # If  confirmation == True: start Termination

    # Copy user's security groups to $groups.txt in their user folder
    Out-File $logFilePath -InputObject $userNameGroups.memberOf -Encoding utf8

    # TODO: Remove $userName's security groups from AD Object
    # Remove-ADGroupMember -Identity $_ -Members $userNameGroups -Confirm:$false

    Copy-Item -Path "\\path\to\active\user\folder" ` 
        -Destination "\\path\to\terminated\user\folder"
} else {
    # Don't Terminate
    # TODO: Restart script to select another user
}

所以我的问题是:如何在else声明中满足TODO?我在网上搜索,但唯一出现的是重新启动计算机。我只想重新运行脚本。它是否像./scriptName一样简单?

1 个答案:

答案 0 :(得分:2)

而不是“重新启动”你的脚本,你甚至可以在“开始”你的脚本之前检查输入是否正确,如果所有输入都是正确的,则不需要“重新启动”:)

这里使用Do-While循环来检查AD中是否存在用户名,然后再继续下面的脚本:

$message = "Please enter the username you'd like to terminate"

Do
{
    # Get a username from the user
    $getUsername = Read-Host -prompt $message

    Try
    {
        # Check if it's in AD
        $checkUsername = Get-ADUser -Identity $getUsername -ErrorAction Stop
    }
    Catch
    {
        # Couldn't be found
        Write-Warning -Message "Could not find a user with the username: $getUsername. Please check the spelling and try again."

        # Loop de loop (Restart)
        $getUsername = $null
    }
}
While ($getUsername -eq $null)

# Do-While succeeded so username is correct
# Put script to run if input is correct here