从Powershell中的文本文件中输入值

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了从Powershell中的文本文件中输入值相关的知识,希望对你有一定的参考价值。

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

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

以下是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; 
答案

您的问题很可能在这里:

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

如果不运行它将很难调试它,但是您打算如何处理?:

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

$ emailAddress从我看到的是一个从未定义。是不是users.txt只是一个一行一行的文件,里面充满了用户文件?

ForEach-Object还需要将数据通过管道传递到。

以上是关于从Powershell中的文本文件中输入值的主要内容,如果未能解决你的问题,请参考以下文章

如何从“活动”中的“编辑”文本中获取值并将其用于片段?

我们如何使用Windows Powershell脚本替换文本文件中的日期?

powershell Powershell脚本,用于根据匹配的表达式从文本文件中增加一行中的数字,然后将其写入文件。

OnItemClick 如何从列表视图中获取单击项目的文本值

如何使用Argument将路径文件作为输入数据获取到PowerShell中的其他脚本?

如何使用powershell将文本($)替换为文本文件中的引号