powershell - 在 Powershell 中从文本文件中提取值
问题描述
我有一个脚本应该连接到服务器并更新用户的值。现在,我可以让该脚本为单个用户执行此操作,但我正在尝试获取它,以便它将为来自文本文件的多个用户执行此操作。该脚本具有三个功能,第一个创建与服务器的连接,第二个搜索用户,并从服务器的数据库中提取用户 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;
解决方案
您的问题很可能在这里:
$getUserResponse = get-content .\users.txt $emailaddress;
$getUserResponse = ForEach-Object
如果不运行它就很难调试它,但你想用这个做什么?:
$getUserResponse = get-content .\users.txt $emailaddress
我所看到的 $emailAddress 从未定义过。users.txt 是否只是一个充满用户文件的逐行文件?
ForEach-Object 还需要通过管道传输数据。
推荐阅读
- javascript - 我在注册和登录时遇到问题
- java - 从像素坐标到opengl坐标
- php - PHP - 将循环数组合并为一个
- iis - WebDav IIS - Access-Control-Allow-Origin:如何允许多个值
- java - UserDetailsService 是必需的
- node.js - 如何创建nodejs和mongo creat
- html - 如何在我的 wordpress 网站上为一行创建一个倾斜的分隔线?
- node.js - 在nodejs中查找2个坐标之间的速度
- ios - Xcode 10 如何使用带有 obfuscator-llvm 插件的新构建系统
- android - ChipGroup 2 路绑定适配器