【问题标题】:Puling a value from a Text file in Powershell从 Powershell 中的文本文件中提取值
【发布时间】:2020-08-07 04:38:23
【问题描述】:

我有一个脚本应该连接到服务器并更新用户的值。现在,我可以让该脚本为单个用户执行此操作,但我正在尝试获取它,以便它可以从文本文件中为多个用户执行此操作。该脚本具有三个功能,第一个创建与服务器的连接,第二个搜索用户,并从服务器的数据库中提取用户 GUID,第三个设置用户的值。

我尝试更新 getuser 函数,以便它使用 get-content 从文本文件中提取用户数据,然后使用 foreach-object,但是当我运行脚本时,它会继续询问电子邮件地址,然后出错。

这里是来自 getuser 的 sn-ps 和主要功能。如果有人有任何建议,我将不胜感激。

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; 

【问题讨论】:

  • “当我运行脚本时,它会继续询问电子邮件地址,然后出错。” - 错误信息是什么意思?

标签: powershell rest blackberry


【解决方案1】:

你的问题很可能在这里:

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

如果不运行它会很难调试,但是你想用这个做什么?:

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

$emailAddress 从我可以看到是一个从未定义过的。 users.txt 是否只是一个充满用户文件的逐行文件?

ForEach-Object 还需要通过管道传输数据。

【讨论】:

  • 所以文本文件只是用户电子邮件地址的列表,脚本获取电子邮件地址并定位用户 GUID。让我看看我能不能按照它的工作方式发布整个脚本。
  • 啊,我明白了,所以您必须执行 $getUserResponse = Get-Content .\users.txt 然后执行类似 $getUserReponse | Foreach-Object { #把检查API的代码放在这里}
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-01-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多