Login-AzureRmAccount : -Credential parameter can only be used with Organization ID credentials - azure

While logging into the Azure account through powershell, I am getting the error -
Login-AzureRmAccount : -Credential parameter can only be used with Organization ID credentials.
I need to understand when this error comes?
[string]$TenantID,
[string]$ApplicationID,
[string]$SecretKey,
[string]$ProcessInstanceID,
[string]$Endpoint
)
$securePassword = ConvertTo-SecureString -String $SecretKey -AsPlainText -Force
$cred = New-Object System.Management.Automation.PSCredential($ApplicationID, $securePassword)
$profilePath = "D:\" + $ProcessInstanceID + "_azureProfile.json"
Clear-AzureRmContext -Scope Process
$azureok = $null
while ($azureok -eq $null) {
if($Endpoint -match "china"){
Connect-AzureRmAccount -ServicePrincipal -TenantId $TenantID -Credential $cred -Environment AzureChinaCloud -ea silentlycontinue -wa silentlycontinue -ev errorvar | out-null
}
else{
Connect-AzureRmAccount -ServicePrincipal -TenantId $TenantID -Credential $cred -ea silentlycontinue -wa silentlycontinue -ev errorvar | out-null
}
if ($errorvar.exception -ne $null) {
if ($errorvar.exception.message -eq "An error occurred while sending the request.") {
Start-sleep -s 10
$error.clear()
} else {
break
}
} else {
$azureok = $true
}
}
Save-AzureRmContext -Path $profilePath ````
Error message -
Login-AzureRmAccount : -Credential parameter can only be used with Organization ID credentials.

Related

Azure powershell Graph explorer query Cannot process argument because the value of argument "name" is not valid

We have more than 1000 Azure subscriptions and some subscriptions have 1000+ resources. We are running powershell script from automation account to collect using graph explorer module to collect information about all resource in each subscription. There is a default limit where powershell can only collect data from 1000 subscriptions and also 100 reources and to overcome this limit we have put togather following script but it is giving us an error. I believe the issue is within for loop somwhere.
Import-Module Az.Accounts
Import-Module Az.Automation
Import-Module Az.Storage
Import-Module Az.ResourceGraph
$resourceGroup = "rg-xxxxx"
$storageAccount = "stxxxxxxxxxx"
$subscriptionid = "xxxx-xxxx-xxxx"
$storageAccountContainer = "azure"
$connectionName = "AzureRunAsConnection" # Run using Run As account
try
{
# Get the connection "AzureRunAsConnection "
$servicePrincipalConnection = Get-AutomationConnection -Name $connectionName
"Logging in to Azure..."
$connectionResult = Connect-AzAccount -Tenant $servicePrincipalConnection.TenantID `
-ApplicationId $servicePrincipalConnection.ApplicationID `
-CertificateThumbprint $servicePrincipalConnection.CertificateThumbprint `
-ServicePrincipal
"Logged in."
}
catch {
if (!$servicePrincipalConnection)
{
$ErrorMessage = "Connection $connectionName not found."
throw $ErrorMessage
} else{
Write-Error -Message $_.Exception
throw $_.Exception
}
}
$date = get-date -format dd-MM-yyyy
$query = Search-AzGraph -Query 'Resources'
$subscriptions = Get-AzSubscription
$SubscriptionIds = $subscriptions.Id
$counter = [PSCustomObject] #{ Value = 0 }
$batchSize = 1000
$response = #()
$data = #()
$subscriptionsBatch = $subscriptionIds | Group -Property { [math]::Floor($counter.Value++ / $batchSize) }
foreach ($batch in $subscriptionsBatch){
$skipToken = $null;
$queryResult = $null;
do {
if ($null -eq $skipToken){
$queryResult = Search-Azgraph -Query $query -first 1000 -subscription $batch.Group;
$data = $data + $queryResult;
}
else{
$queryResult = Search-AzGraph -Query $query -SkipToken $skipToken -subscription $batch.Group;
$data = $data + $queryResult;
}
$skipToken = $queryResult.SkipToken;
}
while ($null -ne $skipToken);
}
$data | Export-Csv "$Env:temp/Azure-temp-totalresources.csv" -notypeinformation
Set-AzContext -SubscriptionId $subscriptionid
Set-AzCurrentStorageAccount -StorageAccountName $storageAccount -ResourceGroupName $resourceGroup
Remove-AzStorageBlob -Blob 'Azure-Azure-totalresources.csv' -Container $storageAccountContainer
Set-AzStorageBlobContent -Container $storageAccountContainer -file "$Env:temp/Azure-temp-totalresources.csv" -Blob "Azure-totalresources.csv" -force
Error we are getting is below
Search-AzGraph: C:\Temp\z11pylt2.z2k\8a832791-6abe-4a38-b4b5-0c4eea1a215d.ps1:61
Line |
61 | … eryResult = Search-AzGraph -Query $query -SkipToken $skipToken -subsc …
| ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
| Cannot process argument because the value of argument "name" is not
| valid. Change the value of the "name" argument and run the operation
| again.

PowerShell - How do I bulk upload Certificates to an Azure App Registration Certificate store?

As you can see from the code below I can upload on certificate at a time, but the problem is it wipes out all of the existing certificates when doing so.
$Tenant_ID = '00000000-0000-0000-0000-000000000000'
$Subscription_ID = '00000000-0000-0000-0000-000000000000'
$Azure_PassWord = (Get-StoredCredential -Target 'Domain' -Type Generic -AsCredentialObject).Password
$UserName = "$($env:USERNAME)#Google.com"
$EncryptedPassword = ConvertTo-SecureString $Azure_PassWord -AsPlainText -Force
$Credential = New-Object System.Management.Automation.PsCredential($UserName,$EncryptedPassword)
$AzureConnection = (Connect-AzAccount -Credential $Credential -Tenant $Tenant_ID -Subscription $Subscription_ID -WarningAction 'Ignore').context
$AzureContext = (Set-AzContext -SubscriptionName $Subscription_ID -DefaultProfile $AzureConnection)
$Application_ID = '00000000-0000-0000-0000-000000000000'
$PFX_FileName = "Azure_Dev_V2"
$Cert_Password = "123456"
$Cert_Password = ConvertTo-SecureString -String $Cert_Password -Force -AsPlainText
$CurrentDate = Get-Date
$EndDate = $CurrentDate.AddYears(10)
$certificatePath = "C:\FilePath\Certificates\Certs\$($PFX_FileName).pfx" # OR Get-ChildItem -Path cert:\localmachine\my\$($Certificate_Thumbprint)
$cert = New-Object -TypeName System.Security.Cryptography.X509Certificates.X509Certificate2($certificatePath, $Cert_Password)
$keyValue = [System.Convert]::ToBase64String($cert.GetRawCertData())
$Azure_App_Registration = Get-AzADApplication -ApplicationId $Application_ID -DefaultProfile $AzureContext
New-AzADAppCredential -ApplicationObject $Azure_App_Registration -CertValue $keyValue -EndDate $EndDate -StartDate $CurrentDate
Connect-AzAccount -Subscription $Subscription_ID -ApplicationId $Azure_App_Registration.AppId -Tenant $Tenant_ID -CertificateThumbprint $cert.Thumbprint | Out-Null
Get-AzADAppCredential -ApplicationId $Azure_App_Registration.AppId | Where-Object {$_.DisplayName -match "CN=Azure_Dev_V2"}
In the Azure portal multiple certificates can be uploaded manually, and they will not delete the existing certificates.
EDIT: If bulk upload is not possible then how would I go about making sure the existing certificates that are in the Azure AD App Registration cert store do not get deleted ?
Thanks in Advance.

get-quarantinemessages in Azure Automation

If i try the script below in Azure Automation, I get the error Get-QuarantineMessages is not recognized ...
This cmdlet dont work in Azure Automation?
$MyCredential = "O365Credential"
$subject = "Mail send from Azure Automation using Office 365"
$userid='xistoso#xistoso.ca'
# Get the PowerShell credential and prints its properties
$Cred = Get-AutomationPSCredential -Name $MyCredential
if ($Cred -eq $null)
{
$Body = Write-Output "Credential entered: $MyCredential does not exist in the automation service. Please create one `n"
}
else
{
$ExchangeOnlineSession = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri https://outlook.office365.com/powershell-liveid/ -Credential $Cred -Authentication Basic -AllowRedirection -Name $ConnectionName
Import-Module (Import-PSSession -Session $ExchangeOnlineSession -AllowClobber -DisableNameChecking) -Global
$today = get-date
$yesterday = (get-date).AddHours(-1)
$Body = Get-QuarantineMessage -Direction Inbound -StartReceivedDate $yesterday -EndReceivedDate $today
<#$CredUsername = $Cred.UserName
$CredPassword = $Cred.GetNetworkCredential().Password
Write-Output "-------------------------------------------------------------------------"
Write-Output "Credential Properties: "
Write-Output "Username: $CredUsername"
Write-Output "Password: *************** `n"
Write-Output "-------------------------------------------------------------------------"
# Write-Output "Password: $CredPassword `n" 3#>
}
Send-MailMessage -To 'xisto#xisto.com' -Subject $subject -Body $Body -UseSsl -Port 587 -SmtpServer 'smtp.office365.com' -From $userid -BodyAsHtml -Credential $Cred
Write-Output "Mail is now send `n"
Write-Output "-------------------------------------------------------------------------"
Remove-PSSession $ExchangeOnlineSession

Azure Start/Stop VM via webhook

We have multiple VM's in our azure environment with multiple resourcegroups. Some of the resourcegroups have multiple VM's. We are now using an URL triggers webhook that will start or stop VM's. This is working, but when a resourcegroup contains multiple VM's all the VM's will start or all the VM's will stop instead of the one you want to start/stop.
Tried multiple scripts but it's isn't working or give me errors.
param(
[Parameter(Mandatory=$false)]
[object]
$WebHookData
)
write output "Data WebHook $WebHookData"
#retrieve ResourceGroup
$ResourceGroupName = $WebHookData.RequestBody
write output "Data ResourceGroup $ResourceGroupName"
$Conn = Get-AutomationConnection -Name AzureRunAsConnection
Connect-AzureRmAccount -ServicePrincipal -Tenant $Conn.TenantID -ApplicationId $Conn.ApplicationID -CertificateThumbprint $Conn.CertificateThumbprint
$VMs = Get-AzureRmVM -ResourceGroupName $ResourceGroupName
if(!$VMs)
{
Write-Output -InputObject 'No VMs were found in the specified Resource Group.'
}
else
{
ForEach ($VM in $VMs)
{
$StartVM = Stop-AzureRmVM -ResourceGroupName $ResourceGroupName -Name $VM.Name -Force #-ErrorAction SilentlyContinue
}
}
$message = ConvertTo-Json -Compress -InputObject ([ordered]#{
headers = #{'content-type' = 'text/plain'}
body = ''
statusCode = 200
})
You could try below script for Start/Stop Virtual machine.
Start VM
$connectionName = "AzureRunAsConnection"
$servicePrincipalConnection = Get-AutomationConnection -Name $connectionName
$null = Add-AzureRmAccount -ServicePrincipal -TenantId $servicePrincipalConnection.TenantId -ApplicationId $servicePrincipalConnection.ApplicationId -CertificateThumbprint $servicePrincipalConnection.CertificateThumbprint
$VMs = Get-AzureRmResource|Where-Object {$_.Tags.Keys -eq "owner" -and $_.Tags.Values -eq "daneum"}
foreach ($VM in $VMs) {
if ($VM.ResourceType -eq "Microsoft.Compute/virtualMachines") {
Start-AzureRmVM -ResourceGroupName $VM.ResourceGroupName -Name $VM.Name -Verbose
}
}
Stop VM
$connectionName = "AzureRunAsConnection"
$servicePrincipalConnection = Get-AutomationConnection -Name $connectionName
$null = Add-AzureRmAccount -ServicePrincipal -TenantId $servicePrincipalConnection.TenantId -ApplicationId $servicePrincipalConnection.ApplicationId -CertificateThumbprint $servicePrincipalConnection.CertificateThumbprint
$VMs = Get-AzureRmResource|Where-Object {$_.Tags.Keys -eq "owner" -and $_.Tags.Values -eq "daneum"}
foreach ($VM in $VMs) {
if ($VM.ResourceType -eq "Microsoft.Compute/virtualMachines") {
Stop-AzureRmVM -ResourceGroupName $VM.ResourceGroupName -Name $VM.Name -Force -Verbose
}
}
For webhook integration procedure you could take a look here

Azure PS Automation Provided subscription "xxxx" does not exists

I wish to select a subscription available for my service principle within an Azure Automation PS job. Running the following code locally works fine, but within the automation job, I only get the following error
Provided subscription xxxx-xxxx-xxxx-xxx-xxxx does not exist.
The subscription does exist, and the service principal has access to it when I log onto it locally.
$id = "someid"
$pass = "somepass"
$securePass = $pass | ConvertTo-SecureString -AsPlainText -Force
$cred = new-object -TypeName System.Management.Automation.PsCredential -ArgumentList $id, $securePass
$tenantId = "someID"
Add-AzureRmAccount -Credential $cred -TenantId $tenantId -ServicePrincipal
Select-AzureRmSubscription -SubscriptionId "someID"
Finally, I figured out this issue, after some days.
This issue is already reported here.
It is due to the issue related to Add-AzureRmAccount cmdlets with Service Principal.
There is a workaround to solve this issue, as mentioned by Hariharan
$connectionAssetName = "AzureRunAsConnection"
$conn = Get-AutomationConnection -Name $ConnectionAssetName
Login-AzureRmAccount `
-ServicePrincipal `
-CertificateThumbprint $conn.CertificateThumbprint `
-ApplicationId $conn.ApplicationId `
-TenantId $conn.TenantID `
-Environment AzureGermanCloud
Refer this S.O
For using Azure Automation, you should create the Automation account with AzureRunAsConnection enabled. Then from the script you utilize it like this
$connectionName = "AzureRunAsConnection"
try {
# Get the connection "AzureRunAsConnection "
$servicePrincipalConnection = Get-AutomationConnection -Name $connectionName
"Logging in to Azure..."
Connect-AzureRmAccount `
-ServicePrincipal `
-TenantId $servicePrincipalConnection.TenantId `
-ApplicationId $servicePrincipalConnection.ApplicationId `
-CertificateThumbprint $servicePrincipalConnection.CertificateThumbprint
}
catch {
if (!$servicePrincipalConnection) {
$ErrorMessage = "Connection $connectionName not found."
throw $ErrorMessage
}
else {
Write-Error -Message $_.Exception
throw $_.Exception
}
}
Hope this helps

Resources