从Powershell中的Text文件中Puling值



我有一个脚本,它应该访问服务器并为用户更新值。现在我可以让这个脚本为单个用户执行,但我正在尝试让它从文本文件为多个用户执行。该脚本有三个功能,第一个创建到服务器的连接,第二个搜索用户,并从服务器的数据库中提取用户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对象还需要通过管道传输数据。

最新更新