Is there a way where I can convert the C# code to powershell script? I want the below code in powershell script. But since I am a newbie to powershell I am not able to convert it. Is there any utitlity to do it?
var tenantId = tId;
var clientId = Environment.GetCommandLineArgs()[5];
var clientSecret = Environment.GetCommandLineArgs()[6];
var audience = Environment.GetCommandLineArgs()[2] + "/";
var domainUrl = Environment.GetCommandLineArgs()[7];
using var httpClient = new HttpClient();
httpClient.BaseAddress = new Uri(domainUrl);
var httpRequestBody = "{ \"client_id\": \"" + clientId + "\", \"client_secret\": \"" + clientSecret + "\" , \"audience\": \"" + audience + "\"," +
" \"grant_type\": \"client_credentials\", \"TenantId\": \"" + tenantId + "\"}";
var jsonContent = new StringContent(httpRequestBody, Encoding.UTF8, "application/json");
string relativeUrl = $"oauth/token";
var httpResponse = httpClient.PostAsync(relativeUrl, jsonContent).Result;
if (httpResponse.IsSuccessStatusCode)
{
var jsonString = httpResponse.Content.ReadAsStringAsync().Result;
JObject obj = JObject.Parse(jsonString.ToString());
var accessToken = obj["access_token"].ToString();
return accessToken;
}
else
{
Console.WriteLine("Error generating token.");
Environment.Exit((int)ExitCode.TokenError);
}
asked Sep 20, 2023 at 11:41
$tenantId = tId;
$clientId = [System.Environment]::GetCommandLineArgs()[5];
$clientSecret = [System.Environment]::GetCommandLineArgs()[6];
$audience = [System.Environment]::GetCommandLineArgs()[2] + "/";
$domainUrl = [System.Environment]::GetCommandLineArgs()[7];
$httpClient = [System.Net.WebClient.HttpClient]::new();
$httpClient.BaseAddress = [System.Uri]::new($domainUrl);
$httpRequestBody = "{ \"client_id\": \"" + clientId + "\", \"client_secret\": \"" + clientSecret + "\" , \"audience\": \"" + audience + "\"," + " \"grant_type\": \"client_credentials\", \"TenantId\": \"" + tenantId + "\"}";
$jsonContent = [System.Net.Http.StringContent]::new($httpRequestBody, [System.Text.Encoding]::UTF8, "application/json");
$relativeUrl = $"oauth/token";
$httpResponse = $httpClient.PostAsync($relativeUrl, $jsonContent).Result;
if ($httpResponse.IsSuccessStatusCode)
{
$jsonString = $httpResponse.Content.ReadAsStringAsync().Result;
$obj = JObject.Parse(jsonString.ToString());
$accessToken = obj["access_token"].ToString();
return $accessToken;
}
else
{
Write-Host("Error generating token.");
[System.Environment]::Exit(12345);
}
answered Sep 20, 2023 at 16:07
3 gold badges16 silver badges20 bronze badges