Why Get-AZRoleAssignment with ResourceName switch doesn't work? - azure

I am trying to list who have Contributor permissions for specific resource name but when I want to use
Get-AZRoleAssignment -ResourceName "ResName"
I am receiving an error:
"Get-AzRoleAssignment : Parameter set cannot be resolved using the
specified named parameters."
However, I am sure that the mentioned resource exists as I can see it when I run the command
get-azresource -ResourceGroupName "ResGroupName"
I was trying:
Get-AZRoleAssignment -ResourceName "ResName" -ResourceGroupName "ResGroupName"
but no luck.
thanks for help

For your issue, you must miss reading the description of the parameter -ResourceName.
-ResourceName
The resource name. For e.g. storageaccountprod. Must be used in
conjunction with ResourceGroupName, ResourceType, and
(optionally)ParentResource parameters.
So your PowerShell command should like this:
Get-AZRoleAssignment -ResourceName "ResName" -ResourceGroupName "ResGroupName" -ResourceType Microsoft.Compute/virtualMachines
You can change the type as you want. And if you just get the role Contributor, you can add the parameter -RoleDefinitionName with value Contributor.

Related

Assistance needed with powershell script

I am trying the execute the powershell script found at :
https://github.com/amanbedi18/Azure-KeyVault-Automation/tree/master/UploadSecrets
https://github.com/amanbedi18/Azure-KeyVault-Automation
This script is used to automate upload of secrets to azure key-vault.
I have created the below json file and named it /user/kv/AzureSecretsMetaData.json
[
{
"key": "test1",
"value": "1"
},
{
"key": "test2",
"value": "2"
}
]
I then copied contents of setKeyVaultSecrets.ps1 to /user/kv/setKeyVaultSecrets.ps1
I have tried the below commands that were mentioned in the readme and powershell script files and get the below errors, could someone please help me execute this script correctly and point out what I am doing wrong here.
./setkeyVaultSecret.ps1 -KeyVaultName 'avkv01'
setkeyVaultSecret.ps1: Parameter set cannot be resolved using the specified named parameters. One or more parameters issued cannot be used together or an insufficient number of parameters were provided.
./setkeyVaultSecret.ps1 -KeyVaultName 'avkv01' -KVSecretMetadataFilePath '/home/aditya/kv/AzureSecretsMetaData.json'
setkeyVaultSecret.ps1: Parameter set cannot be resolved using the specified named parameters. One or more parameters issued cannot be used together or an insufficient number of parameters were provided.
Any help is greatly appreciated. Thank You
If these are scripts you found, they are very poorly written and I would advise not using them. I would suggest installing the az powershell module and using those scripts as a reference in writing your own script. You can install the az powershell module with powershellget:
Install-module az -force -allowclobber
The way the script that you are trying to call is written very strangely. It defines two different parameter sets, but each of the two parameters are mandatory for BOTH parameter sets?! That doesn't make a lot of sense. If you must run them, you will probably need to modify them a bit. They don't really seem finished.. Why not modify the script and get rid of the parameter sets altogether? Also, the example in the script indicates that the "$KVSecretMetadataFilePath" parameter is not mandatory, since it is not being called, but is defined as being mandatory when defining your parameter. You need to make clear if this parameter is required or not. If it is required Make it look more like this:
<#
.PREREQUISITE
1. An Azure key vault and its name as parameter.
2. Json template should be properly populated with valid json schema in sampleSecretValues.json in KeyVaultjson directory.
.PARAMETER vaultName
The name of the key vault.
.EXAMPLE
. setKeyVaultSecret.ps1 -KeyVaultName 'somekeyvault'
#>
# provision keys and secrets to a key vault
Param(
[Parameter(Mandatory=$true)]
[String]
$KeyVaultName,
[Parameter(Mandatory=$true)]
[String]
$KVSecretMetadataFilePath
)
Install-Module -Name AzureADPreview -ErrorAction SilentlyContinue -Force
Import-Module Azure -ErrorAction SilentlyContinue
Import-Module AzureRM.Resources
Set-StrictMode -Version 3
$json = Get-Content $KVSecretMetadataFilePath | Out-String | ConvertFrom-Json
$json | ForEach {
$secretToSearch = Get-AzureKeyVaultSecret -VaultName $KeyVaultName -Name $_.key -ErrorAction SilentlyContinue
if($secretToSearch -ne $null)
{
echo "The secret $_.key already exists !"
}
Else
{
$NewSecret = Set-AzureKeyVaultSecret -VaultName $KeyVaultName -Name $_.key -SecretValue (ConvertTo-SecureString $_.value -AsPlainText -Force ) -Verbose
Write-Host
Write-Host "Source Vault Resource Id: "$(Get-AzureRmKeyVault -VaultName $KeyVaultName).ResourceId
}
}
If it is not required, remove the line "[Parameter(Mandatory=$true)]" above the $KVSecretMetadataFilePath declaration.

Azure: New-AzRoleAssignment Input string was not in a correct format - error with double parsing... without any number

I have a strange problem with my PowerShell script to create Azure user accounts.
Executing command
New-AzRoleAssignment -RoleDefinitionName 'Contributor' -ObjectId "$Usr.Id" -ResourceGroupName "$rgname"
Results in exception:
New-AzRoleAssignment : Input string was not in a correct format.
At myscript.ps1:151 char:5
+ New-AzRoleAssignment -RoleDefinitionName 'Contributor' -ObjectId ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : CloseError: (:) [New-AzRoleAssignment], FormatException
+ FullyQualifiedErrorId : Microsoft.Azure.Commands.Resources.NewAzureRoleAssignmentCommand
I've extracted stacktrace for this exception, and it looks like this:
at System.Number.ParseDouble(String value, NumberStyles options, NumberFormatInfo numfmt)
at Microsoft.Azure.Commands.Resources.NewAzureRoleAssignmentCommand.ExecuteCmdlet()
at Microsoft.WindowsAzure.Commands.Utilities.Common.AzurePSCmdlet.ProcessRecord()
Which is super strange - I'm not using any double number here. I've dig into source code for NewAzureRoleAssignmentCommand - but there is no System.Number.ParseDouble call there.
Only thing related to double is -ConditionVersion, but I don't want to use any Coditions.
What I should check next? I'm not an advanced Azure/Powershell user, so any suggestions are welcomed!
edit:
I've tried running command manually using same parameter values, with and without quotation marks - every time I get same error
New-AzRoleAssignment -RoleDefinitionName 'Contributor' -ObjectId f01b4003-8a47-4a9d-8935-cd000c8cd9c5 -ResourceGroupName myValidResourceGrupName
Try using Azure Cloud Shell to check whether the problem might be local to your machine.
Remove the double quotes that are around $usr.id
If you'd only have a string like:
$usr = <GUID goes here>
then you could pass "$usr". But in this case, you're trying to access the Id property of the $usr object.
I would try getting your with Get-AzRoleDefinition. I tend to get the objects for everything and use the IDs. This works for me.
$Role = Get-AzRoleDefinition -Name Contributor
$ResourceGroup = Get-AzResourceGroup -Name "ResourceGroupName"
$User = Get-AzADUser -UserPrincipalName "User-UPN-Here"
New-AzRoleAssignment -ObjectId $User.Id -RoleDefinitionId $Role.Id -Scope $ResourceGroup.ResourceId
I had the same problem. This script used to work:
$qa = get-azadgroup -displayname qa;
New-AzRoleAssignment -ObjectId $qa.Id -RoleDefinitionName Owner -ResourceGroupName RG-QA
Started getting this error on one computer but not the other. When I checked the modules version for az.resources, I had 2.1.0, 2.4.0 and 2.5.0. After removing versions 2.4.0 and 2.5.0, the script worked. I have the language of Powershell set to French.
https://github.com/Azure/azure-powershell/issues/13096 it's this issue if anyone else runs into this issue. Workaround as above is to use 2.1.0 of Az.resources but should be fixed soon.

Azure - setting tags on VMs using Powershell

I'm using the following Powershell code to set tags on a bunch of Azure VMs but it doesn't seem to be working. It does not give me an error message, so it appears to run correctly, but it does not set the tags as expected. Any help would be great, perhaps it may be something easy I'm overlooking.
$group = Get-AzResourceGroup -Name my-rg
$resource = Get-AzResource -ResourceName myserver -ResourceGroupName my-rg
Set-AzResource -ResourceId $resource.ResourceId -Tag $group.Tags -Force
I'm only doing a few VMs which I'll probably put on a loop once this works. There are no tags on most of these VMs which may be overwritten.

Azure Powershell - iterate through a list (txt) with db names and set them as variables in script

I have the following challenge at the Moment:
With T-SQL I created a list of databases attached to our SQL instance and put this list in a txt file, so far no Problem.
Now with PowerShell I want to set up LongTermRetention backups in Azure with following cmdlet:
Set-AzSqlDatabaseBackupLongTermRetentionPolicy -ServerName $serverName -DatabaseName [name of database] -ResourceGroupName $resourceGroup -WeeklyRetention P53W -MonthlyRetention P48M -YearlyRetention P10Y -WeekOfYear 52
(I checked the Syntax of the cmdlet by inserting a database name manually and it works)
the variables given are set prior (ServerName, resourceGroup)
Where I am struggling now is, how I can get the names of the txt file one after another as parameter "DatabaseName" into my cmdlet, as I have never done something like this.
I would be very grateful for either a link on how to do this or maybe a solution posted here.
Thank you in advance and Kind regards
EDIT: I found a solution, Maybe not the most elegant, but working:
$files = Get-Content "C:\DEV\testfile.txt"
foreach ($file in $files){
Set-AzSqlDatabaseBackupLongTermRetentionPolicy -ServerName $serverName -DatabaseName $file -ResourceGroupName $resourceGroup -WeeklyRetention P53W -MonthlyRetention P48M -YearlyRetention P10Y -WeekOfYear 52
}
I haven't thought it might have been that easy.
If you have a flat text file where your database names are present like this:
server1
server2
server3
......
You can use the Get-Content cmdlet to read the file and iterate over each line using the ForEach-Object cmdlet. You can access the current item using $_ ($_ represents the current value in the pipeline):
Get-Content -Path 'pathToYourFile.txt' | ForEach-Object {
Set-AzSqlDatabaseBackupLongTermRetentionPolicy `
-ServerName $_ `
-DatabaseName [name of database] `
-ResourceGroupName $resourceGroup `
-WeeklyRetention P53W `
-MonthlyRetention P48M `
-YearlyRetention P10Y `
-WeekOfYear 52
}

Cannot convert the value of type "System.String" to type "System.Collections.Hashtable"

In Azure Devops I'm trying to run a block of Azure Powershell inline script:
Invoke-AzVMRunCommand -ResourceGroupName xxx-Name xxx -CommandId 'RunPowerShellScript' -ScriptPath $env:SYSTEM_DEFAULTWORKINGDIRECTORY/_alias/xxx.ps1 -Parameter $env:xxx -Verbose
As you can see I am passing a parameter to the xxx.ps1 script. This is a small piece of the content of the xxx.ps1 script:
Param(
[string]$xxx
)
#create AD Group
$ADGroupName = "AD" + $xxx+ "_AD"
.....
When I run this code I get the following error in the logs:
[error]Cannot bind parameter 'Parameter'. Cannot convert the "valueofthevariable" value of type "System.String" to type "System.Collections.Hashtable".
How can I correctly pass the value as parameter?
Thanks!
After some more searching online I found my mistake:
In the Powershell command Invoke-AzVMRunCommand I used a String as input type for Parameter, this has to be a hashtable.
I changed that command to the following:
Invoke-AzVMRunCommand -ResourceGroupName xxx-Name xxx -CommandId 'RunPowerShellScript' -ScriptPath $env:SYSTEM_DEFAULTWORKINGDIRECTORY/_alias/xxx.ps1 -Parameter #{xxx = $env:xxx} -Verbose

Resources