Планирование значения из текстового файла в Powershell - PullRequest
0 голосов
/ 23 апреля 2020

У меня есть сценарий, который должен связаться с сервером и обновить значение для пользователя. Прямо сейчас я могу заставить этот скрипт делать это для одного пользователя, но я пытаюсь сделать так, чтобы он делал это для нескольких пользователей из текстового файла. Сценарий имеет три функции: первая создает соединение с сервером, вторая выполняет поиск пользователя и извлекает GUID пользователя из базы данных сервера, а третья устанавливает значение пользователя.

Я попытался обновить функцию getuser, чтобы она извлекала пользовательские данные из текстового файла, используя get-content, а затем для foreach-object, но когда я запускаю скрипт, он продолжает запрашивать адрес электронной почты, а затем ошибки.

Вот фрагменты из getuser и основные функции. Если у кого-то есть какие-либо предложения, я был бы очень признателен.

function getUser($email)
{

   $methodName = "getUser()";
   enterMethod($methodName);
   $response = $null;

   <# Create and set the headers for the REST request #>
   $headers = @{}
   $headers.add("Authorization", $global:authString);
   $headers.add("Content-Type", "application/vnd.blackberry.users-v1+json");



   $request = $global:uemBaseUrl + "/users?query=emailAddress=" + $email;


   # Invoke RESTMethod to call users API to obtain users in the system
   try
   {
       $response = Invoke-RestMethod -Method GET -Headers $headers -Uri $request;
       if (($response.users -ne $null) -and ($response.users.length -eq 1))
       {
           Write-Host([string]::Format("User with email address '{0}' was found", $email));
       }
       else
       {
           Write-Host([string]::Format("User with email address '{0}' not found", $email));
           exit(1);
       }
   }
   catch
   {
        handleError $_;
   }
   exitMethod($methodName);
   return $response;
} 

     function main
{
    $methodName = "main()";
    enterMethod($methodName);
    try
    {
        if (setup)
        {
            $getUserResponse = get-content .\users.txt $emailaddress;
            $getUserResponse = ForEach-Object 
            $userGUID = $getUserResponse.users.guid;
            if($actionType -eq "Set")
            {
                if([string]::IsNullOrEmpty($expiry))
                {
                    throw [System.ArgumentNullException]"The expiry argument is required when actionType=Set";
                }
                if(setActivationpassword($userGUID))
                {
                    Write-Host([string]::Format("Random activation password has been set for user '{0}'", $emailAddress));
                }
            }
            elseif($actionType -eq "ReplaceAll")
            {
                if([string]::IsNullOrEmpty($expiry))

                {
                    throw [System.ArgumentNullException]"The expiry argument is required when actionType=ReplaceAll";
                }
                if(replaceActivationpassword($userGUID))
                {
                    Write-Host([string]::Format("Activation password has been replaced for user '{0}'. Existing passwords have been expired.", $emailAddress ));
                }
            }
            elseif($actionType -eq "ExpireAll")
            {
                if(expireActivationpasswords($userGUID))
                {
                    Write-Host([string]::Format("All activation passwords expired for user '{0}'", $emailAddress));
                }
            }
        }
    }
    catch
    {
        handleError $_;
    }
    exitMethod($methodName);
    Write-Host("Complete!");
    exit(0);
} 

РЕДАКТИРОВАТЬ:

Вот полный рабочий скрипт. Этот скрипт позволяет вам делать по одному пользователю за раз.

 <#
.DESCRIPTION
    Authenticate and call either "Set", "Expire all" or "Replace" activation passwords for user BWS REST API depending what actionType is used.
.PARAMETER uemHostAndPort
    Host and port of the UEM.
.PARAMETER tenantGuid
    tenantGuid to use for authentication.
.PARAMETER authType
    Authentication type to use.  (Local or AD).
.PARAMETER username
    username to use for authentication.
.PARAMETER password
    password to use for authentication.
.PARAMETER domain
    domain to use for authentication if authType=AD.
.PARAMETER actionType
    Action to perform. (Set, ExpireAll or ReplaceAll)
.PARAMETER emailAddress
    Email address of the user to perform the action on.
.PARAMETER expiry
    The date and time the activation password will expire in ISO-8601 format.
#>

Param(
    [Parameter(
        Mandatory=$true,
        HelpMessage="UEM Host and port."
    )]
    [ValidateNotNullorEmpty()]
    [string]$uemHostAndPort,

    [Parameter(
        Mandatory=$true,
        HelpMessage="Tenant guid to authenticate with."
    )]
    [ValidateNotNullorEmpty()]
    [string]$tenantGuid,

    [Parameter(
        Mandatory=$true,
        HelpMessage="Choose (AD | Local) authType."
    )]
    [ValidateSet('AD', 'Local')]
    [string]$authType,

    [Parameter(
        Mandatory=$true,
        HelpMessage="Username to authenticate with."
    )]
    [ValidateNotNullorEmpty()]
    [string]$username,

    [Parameter(
        Mandatory=$true,
        HelpMessage="Password to authenticate with."
    )]
    [ValidateNotNullorEmpty()]
    [string]$password,

    [Parameter(
        Mandatory=$false
    )]
    [string]$domain,

    [Parameter(
        Mandatory=$true,
        HelpMessage="Choose (Set | ExpireAll | ReplaceAll) actionType."
    )]
    [ValidateSet('Set', 'ExpireAll', 'ReplaceAll')]
    [string]$actionType,

    [Parameter(
        Mandatory=$true,
        HelpMessage="User email address to add or remove from group."
    )]
    [string]$emailAddress,

    [Parameter(
        Mandatory=$false,
        HelpMessage="The date and time the activation password will expire in ISO-8601 format."
    )]
    [string]$expiry
)

$global:authString = $null;
$global:uemBaseUrl = $null;


<#
    * Generate authorization header required to perform the REST call.
    *
    * @return
    *       True if successful, false otherwise.
#>
function setup()
{
    $methodName = "setup()";
    enterMethod($methodName);
    $provider = $null;

    $global:uemBaseUrl = "https://" + $uemHostAndPort + "/" + $tenantGuid + "/api/v1";

    # Create and set the headers for the REST request
    $headers = @{}
    $headers.add("Content-Type", "application/vnd.blackberry.authorizationrequest-v1+json")

    # Create body for REST call
    $body = @{}
    $body.add("provider",$authType);
    $body.add("username", $username);
    $body.add("password", [Convert]::ToBase64String([System.Text.Encoding]::UTF8.GetBytes($password)));
    if($authType -eq "AD")
    {
        if(-not($domain))
        {
            throw [System.ArgumentNullException]"The domain argument is required when authType=AD";
        }
        $body.add("domain", $domain);
    }

    $request = $global:uemBaseUrl + "/util/authorization";

    # Invoke RESTMethod to call authorization route to generate the authorization headers
    try
    {
        $response = Invoke-RestMethod -Method POST -Headers $headers -Uri $request -Body ($body | ConvertTo-Json);
        $global:authString = $response
    }
    catch
    {
        handleError $_;
    }

    Write-Host([string]::Format("Authorization header string generated: {0}", $global:authString));
    Write-Host("Setup Complete...");
    exitMethod($methodName);
    return $true;
}

<#
    * Generate authorization header required to perform the REST call.
    *
    * @param email
    *       Email of the user to get.
    * @return
    *       User that was found.
#>
function getUser($email)

{

   $methodName = "getUser()";
   enterMethod($methodName);
   $response = $null;

   <# Create and set the headers for the REST request #>
   $headers = @{}
   $headers.add("Authorization", $global:authString);
   $headers.add("Content-Type", "application/vnd.blackberry.users-v1+json");



   $request = $global:uemBaseUrl + "/users?query=emailAddress=" + $email;


   # Invoke RESTMethod to call users API to obtain users in the system
   try
   {
       $response = Invoke-RestMethod -Method GET -Headers $headers -Uri $request;
       if (($response.users -ne $null) -and ($response.users.length -eq 1))
       {
           Write-Host([string]::Format("User with email address '{0}' was found", $email));
       }
       else
       {
           Write-Host([string]::Format("User with email address '{0}' not found", $email));
           exit(1);
       }
   }
   catch
   {
        handleError $_;
   }
   exitMethod($methodName);
   return $response;
}

<#
    * Set acctivation password for a user.
    *
    * @param userGuid
    *       Guid of user.
    * @return
    *       True if successful, false otherwise.
#>
function setActivationpassword($userGuid)
{
    $methodName = "setActivationpassword()";
    enterMethod($methodName);


    # Create and set the headers for the REST command
    $headers = @{}
    $headers.add("Authorization", $global:authString);
    $headers.add("Content-Type", "application/vnd.blackberry.activationpasswords-v1+json");

    # Create body for REST call
    $body = @{};
    $innerBody = @(@{
    "password" = $null;
    "emailTemplate" = $null;
    "expiry" = $expiry;
    "expireAfterUse" = "true";
    "activationProfile"= $null;
    });
    $body.add("activationPasswords",$innerBody);

    $request = $global:uemBaseUrl + "/users/" + $userGuid + "/activationPasswords";

    # Invoke RESTMethod to set activation password.
    try
    {
        $response = Invoke-RestMethod -Method POST -Headers $headers -Uri $request -Body ($body | ConvertTo-Json);
    }
    catch
    {
         handleError $_;
    }

    exitMethod($methodName);
    return $true;
}

<#
    * Expire all acctivation passwords for a user.
    *
    * @param userGuid
    *       Guid of user.
    * @return
    *       True if successful, false otherwise.
#>
function expireActivationpasswords($userGuid)
{
    $methodName = "expireActivationpasswords()";
    enterMethod($methodName);

    # Create and set the headers for the REST command
    $headers = @{}
    $headers.add("Authorization", $global:authString);
    $headers.add("Content-Type", "application/vnd.blackberry.activationpasswords-v1+json");

    $request = $global:uemBaseUrl + "/users/" + $userGuid + "/activationPasswords";

    # Invoke RESTMethod to exipre all activation passwords.
    try
    {
        $response = Invoke-RestMethod -Method DELETE -Headers $headers -Uri $request
    }
    catch
    {
         handleError $_;
    }

    exitMethod($methodName);
    return $true;
}

<#
    * Replace all acctivation passwords for a user.
    *
    * @param userGuid
    *       Guid of user.
    * @return
    *       True if successful, false otherwise.
#>
function replaceActivationpassword($userGuid)
{
    $methodName = "replaceActivationpassword()";
    enterMethod($methodName);

    # Create and set the headers for the REST command
    $headers = @{}
    $headers.add("Authorization", $global:authString);
    $headers.add("Content-Type", "application/vnd.blackberry.activationpasswords-v1+json");

    # Create body for REST call
    $body = @{};
    $innerBody = @(@{
    "password" = $null;
    "emailTemplate" = $null;
    "expiry" = $expiry;
    "expireAfterUse" = "true";
    "activationProfile"= $null;
    });
    $body.add("activationPasswords",$innerBody);

    $request = $global:uemBaseUrl + "/users/" + $userGuid + "/activationPasswords";

    # Invoke RESTMethod to set activation password.
    try
    {
        $response = Invoke-RestMethod -Method PUT -Headers $headers -Uri $request -Body ($body | ConvertTo-Json);
    }
    catch
    {
         handleError $_;
    }

    exitMethod($methodName);
    return $true;
}

<#
    * Logging for method entry.
    *
    * @param methodName
    *       Name of the method to log
#>
function enterMethod($methodName)
{
    Write-Host([string]::Format("Entering {0}...", $methodName));
}

<#
    * Logging for method exit.
    *
    * @param methodName
    *       Name of the method to log.
#>
function exitMethod($methodName)
{
    Write-Host([string]::Format("Exiting {0}...", $methodName));
}

<#

    * Handle any errors that occur when performing the REST call.
    *
    * @param error
    *       The group create context.
#>
function handleError($error)
{
    Write-Error ("The command cound not be completed.  `r`nReason: " + $error.exception.message + " `r`nDetails: "+ $error.errordetails);
    exit(1);
}

function main
{
    $methodName = "main()";
    enterMethod($methodName);
    try
    {
        if (setup)
        {
            $getUserResponse = getuser $emailaddress;
            $userGUID = $getUserResponse.users.guid;
            if($actionType -eq "Set")
            {
                if([string]::IsNullOrEmpty($expiry))
                {
                    throw [System.ArgumentNullException]"The expiry argument is required when actionType=Set";
                }
                if(setActivationpassword($userGUID))
                {
                    Write-Host([string]::Format("Random activation password has been set for user '{0}'", $emailAddress));
                }
            }
            elseif($actionType -eq "ReplaceAll")
            {
                if([string]::IsNullOrEmpty($expiry))
                {
                    throw [System.ArgumentNullException]"The expiry argument is required when actionType=ReplaceAll";
                }
                if(replaceActivationpassword($userGUID))
                {
                    Write-Host([string]::Format("Activation password has been replaced for user '{0}'. Existing passwords have been expired.", $emailAddress ));
                }
            }
            elseif($actionType -eq "ExpireAll")
            {
                if(expireActivationpasswords($userGUID))
                {
                    Write-Host([string]::Format("All activation passwords expired for user '{0}'", $emailAddress));
                }
            }
        }
    }
    catch
    {
        handleError $_;
    }
    exitMethod($methodName);
    Write-Host("Complete!");
    exit(0);
}

# Call main function.
main; 

1 Ответ

0 голосов
/ 23 апреля 2020

Ваша проблема, скорее всего, здесь:

 $getUserResponse = get-content .\users.txt $emailaddress;
 $getUserResponse = ForEach-Object

Будет сложно отладить это без запуска, но что вы пытаетесь с этим сделать?:

$getUserResponse = get-content .\users.txt $emailaddress

$ emailAddress из того, что я вижу, никогда не определяется. Является ли users.txt просто построчным файлом, полным файлов пользователей?

ForEach-Object также должен был бы передавать данные.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...