0

Variable's values are unintentionally getting printed in output in PowerShell. How to avoid this. I wrote a PowerShell script in which I am loading values into bunch of variables. Those values are getting printed in output window. how can i avoid them to print those values.

I have couple of ForEach loops in the script as well.

Annoyingly, below variable's values are constantly getting printed on to the output window. Is there a way to avoid these values to be printed. $ClusterName, $ResourceGroupName, $HDInsightsClusterUri, $HDInsightsClusterResults

I only want one table $AllLocalAccounts to be printed in the end

cls
$Tenant = 'Corp'
$SubscriptionID = 'xxxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx'
$DestinationFile = 'V:\MyDocuments\CPU\Projects\RAMP\PreviewTool\HDInsights-Permissions.csv'

switch ($Tenant)
{
    AME { $TenantID = "00000000-0000-0000-0000-000000000001" }
    GME { $TenantID = "00000000-0000-0000-0000-000000000002" }
    PME { $TenantID = "00000000-0000-0000-0000-000000000003" }
    Corp {$TenantID = "00000000-0000-0000-0000-000000000004" }
}
    
clear-AzContext -force
$TenantConnectionContext = Connect-AzAccount -Tenant $TenantID -WarningAction SilentlyContinue
$SubscriptionContext = set-AzContext -Tenant $TenantID -SubscriptionId $SubscriptionID
$azContext = Get-AzContext
$azProfile = [Microsoft.Azure.Commands.Common.Authentication.Abstractions.AzureRmProfileProvider]::Instance.Profile
$profileClient = New-Object -TypeName Microsoft.Azure.Commands.ResourceManager.Common.RMProfileClient -ArgumentList ($azProfile)
$token = $profileClient.AcquireAccessToken($azContext.Subscription.TenantId)
    
$authHeader = @{
    'Content-Type'='application/json'
    'Authorization'='Bearer ' + $token.AccessToken
}
    
$AllHDInsightClusters = Get-AzResource -ResourceType "Microsoft.HDInsight/clusters" | select Name, ResourceType, ResourceGroupName
$AllLocalAccounts = @()

foreach ($HDInsightCluster in $AllHDInsightClusters)
{
    $ClusterName,
    $ResourceGroupName,
    $HDInsightsClusterResults,
    $HDInsightsClusterUri
    $ClusterAdmins
    $UserName,
    $SecurePassword,
    $Secret,
    $credential,
    $base64AuthInfo,
    $UsersUri,
    $UsersResult = $null

    $ClusterName = $HDInsightCluster.Name
    $ResourceGroupName = $HDInsightCluster.ResourceGroupName

    Write-Host "Working on ClusterName" $ClusterName -ForegroundColor Green
    # To get Cluster Admin UserName and Password
    $HDInsightsClusterUri = -join("https://management.azure.com/subscriptions/$SubscriptionID/resourceGroups/$ResourceGroupName/providers/Microsoft.HDInsight/clusters/$ClusterName/configurations?api-version=2021-06-01")
    $HDInsightsClusterResults = Invoke-RestMethod -Uri $HDInsightsClusterUri -Method POST -Headers $authHeader -Verbose:$false
    Start-Sleep -Seconds 5

    $ClusterAdmin = $HDInsightsClusterResults.configurations.gateway

    $UserName = $ClusterAdmin.'restAuthCredential.username'
    $Secret = $ClusterAdmin.'restAuthCredential.password'
    $SecurePassword = ConvertTo-SecureString –String $Secret –AsPlainText -Force
    $credential = New-Object –TypeName "System.Management.Automation.PSCredential" –ArgumentList $UserName, $SecurePassword
    $base64AuthInfo = [Convert]::ToBase64String([Text.Encoding]::ASCII.GetBytes(("{0}:{1}" -f $UserName,$SecurePassword)))
    $UsersUri = "https://$ClusterName.azurehdinsight.net/api/v1/users"
    $UsersResult = Invoke-RestMethod -Method Get -Uri $UsersUri -Headers @{Authorization = "Basic $base64AuthInfo"} -Credential $credential -ContentType "application/json"
    Start-Sleep -Seconds 5

    $localUsers = $UsersResult.items.Users
    Write-Host "    Found" $localUsers.count "Native\Local Users on  ClusterName" $ClusterName -ForegroundColor cyan
        

    foreach ($localUser in $localUsers)
    {
        $Info = "" | select SubscriptionID, ResourceGroupName, ClusterName, LocalAccountName
        $Info.SubscriptionID = $SubscriptionID
        $Info.ResourceGroupName = $ResourceGroupName
        $Info.ClusterName = $ClusterName
        $Info.LocalAccountName = $localUser.user_name
        $AllLocalAccounts += $Info
    }        
}
Start-Sleep -Seconds 5
Write-Output $AllLocalAccounts | FT
Ken White
  • 123,280
  • 14
  • 225
  • 444
Vinny
  • 461
  • 1
  • 5
  • 18
  • Show minimal code to reproduce the problem. Not necessarily the entire script. – Tarik Feb 23 '23 at 04:39
  • Done. Added my entire code. also i updated the post with exactly 4 offending variables. – Vinny Feb 23 '23 at 05:04
  • You’re literally outputting them, what’s the point of listing the variables in the loop? You either need to capture the output you’re creating or remove them to stop outputting. – Doug Maurer Feb 23 '23 at 05:18
  • 1
    Thanks a ton @Doug. I though initializing the variables with Null so that in every iteration, variables starts with no data in them. Wow. I guess I am overthinking. removing those initializing variables has solved the problem and reduced 15 lines of code for me :) – Vinny Feb 23 '23 at 19:47

1 Answers1

1

The variable values are actually being intentionally outputted, based on the code you submitted. When you just write a variable, without assigning it, setting it or similar, then it will output it's value.

Assuming your request is only to avoid printing those values, you should remove the following lines from the foreach ($HDInsightCluster in $AllHDInsightClusters) loop:

    $ClusterName,
    $ResourceGroupName,
    $HDInsightsClusterResults,
    $HDInsightsClusterUri
    $ClusterAdmins
    $UserName,
    $SecurePassword,
    $Secret,
    $credential,
    $base64AuthInfo,
    $UsersUri,
Marc H
  • 101
  • 5
  • Wow. I though initializing the variables with Null so that in every iteration, variables starts with no data in them. Wow. I guess I am overthinking. removing those initializing variables has solved the problem and reduced 15 lines of code for me :) – Vinny Feb 23 '23 at 19:47
  • @Vinny Powershell does not require you to initialize the variables before you use them. Actually scopes in Powershell is a bit confusing to me e.g. if you inside an if-block write $x = 1, then $x is available outside the scope with the value of 1. I actually think that the value that was outputted, was values from the PREVIOUS iteration in the loop, making the entire thing more confusing. – Marc H Feb 24 '23 at 21:08