How to check if the Powershell cmdlet Get-AzKeyVaultSecret supports -AsPlainText parameter? - azure

With the following command I am able to retrieve a list (or is it a dictionary? My Powershell knowledge is unfortunately very limited) of parameters supported by the Get-AzKeyVaultSecret cmdlet:
PS C:\> $params = (Get-Command Get-AzKeyVaultSecret).ParameterSets | Select -ExpandProperty Parameters
PS C:\> $params | ForEach {$_.Name}
VaultName
Name
InRemovedState
DefaultProfile
Verbose
Debug
ErrorAction
WarningAction
InformationAction
...
How could I please check if the list contains the AsPlainText parameter, which was added in the newer versions of the cmdlet?
In my custom script I would like to check for that and then adapt the way I retrieve a secret value from a key vault:
if ($is_AsPlainText_Supported) # how to set this variable?
{
$mySecret = Get-AzKeyVaultSecret -VaultName 'MyKeyVault' -Name 'MySecret' -AsPlainText
}
else
{
$mySecret = (Get-AzKeyVaultSecret -VaultName 'MyKeyVault' -Name 'MySecret').SecretValueText
}
I would prefer not to use try/catchhere (or check if retrieved secret value is null), because I have numerous Get-AzKeyVaultSecret calls in my real script and such approaches would cost performance.

Add this line before your if statement:
$is_AsPlainText_Supported = (Get-Command Get-AzKeyVaultSecret).ParameterSets.Parameters.Name -contains "AsPlainText"
The -contains operator will return a boolean based on if the list before the operator contains the item after it.

Related

Export Azure key vault secrets as json list (or file)

Azure powershell - how to create json file with azure keyvaults secrets
(I know how to read the secrets with power shell). I do know how to put key values pairs and export as a file.
So, given I have this
secret1Name - secret1Value
secret2Name - secret2Value
secret3Name - secret3Value
I need a file saved to the file system
{
"secret1Name":"secret1Value",
"secret2Name":"secret2Value",
"secret3Name":"secret3Value",
}
I found that there is something like this for reading from a file
$globalParametersJson = Get-Content $globalParametersFilePath
$globalParametersObject = [Newtonsoft.Json.Linq.JObject]::Parse($globalParametersJson)
And I (think) i need help doing it for writing a file.
Can anyone help ??
Export Azure key vault secrets as json list (or file)
I have tried to reproduce your ask and I have received expected results:
What I have understood from your question is that you want to write a secret to file (then below is the answer for that).
Firstly, created an empty Json file and copied its path and I followed Microsoft-Document.
Then I executed the below script:
$y="C:\Users\vs\emo.json"
$secret = Get-AzKeyVaultSecret -VaultName "rithkey"
$secretnames=$secret.Name
$Target = #()
$result = New-Object -TypeName PSObject
foreach($em in $secretnames )
{
$Target=Get-AzKeyVaultSecret -VaultName rithkey -Name $em
$x=Get-AzKeyVaultSecret -VaultName rithkey -AsPlainText -Name $em
$result | Add-Member -Type NoteProperty -Name $Target.Name -Value $x
}
$result | ConvertTo-Json | Set-Content $y
Now we can check file emo.json as we used Set-Content to write to emo.json file and output is below:

Query ObjectId of ConditionalAccessLocationCondition

I am writing a script to write to Azure, I basically want to find a user, create a network location, create a conditional access policy. This is what I have so far. The trouble is that the $secmon_guid and $location_policy_guid do not work. If I manually put the values in, it works.
# Run these commands first to connect and install without the #
Install-Module -Name AzureAD -AllowClobber -Force # Answer Y to install NuGet. Run once on workstation running script.
Install-Module -Name Microsoft.Graph.Identity.SignIns -Force # Install this to allow us to setup a trusted location. Run once on workstation running script.
Install-Module MSOnline -Force #Allow us to edit users. Run once on workstation running script.
Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope LocalMachine #Set execution policy to allow our script to do things.
Import-Module -Name AzureAD #The following 3 commands are ran for each client.
Connect-AzureAD # Use GA credentials from Glue
Connect-MsolService #Reauthenticate if necessary.
Get-AzureADMSConditionalAccessPolicy #This will list out all of the existing CA policies. This is a good opportunity to get them into documentation.
Connect-MgGraph #This enabled graph, you will need to approve the request in the popup window.
#Set variable for account name
Set-Variable -name "account" -Value "secmon"
#Create named location for the IP address
$ipRanges = New-Object -TypeName Microsoft.Open.MSGraph.Model.IpRange
$ipRanges.cidrAddress = "IP ADDR"
New-AzureADMSNamedLocationPolicy -OdataType "#microsoft.graph.ipNamedLocation" -DisplayName "Blackpoint IP Address for SecMon" -IsTrusted $true -IpRanges $ipRanges
#Disable MFA for secmon
Get-MsolUser -SearchString "secmon" | Set-MsolUser -StrongAuthenticationRequirements #()
#Get the Azure AD GUID for use later
$secmon_guid = Get-MsolUser -SearchString "secmon" | Select ObjectID
#Name the policy
$name = "Allow Secmon Only from Blackpoint IP"
#Enable the policy. Set to Disabled to test.
$state = "Enabled"
#Get location GUID and save to variable
$location_policy_guid = Get-AzureADMSNamedLocationPolicy | Where-Object -Property DisplayName -Contains 'Blackpoint IP Address for SecMon' | Select-Object -Property Id
#Working on this
#Create the overarching condition set for CA, this is the container.
$conditions = New-Object -TypeName Microsoft.Open.MSGraph.Model.ConditionalAccessConditionSet
#Include all applications - This might be able to be removed?
$conditions.Applications = New-Object -TypeName Microsoft.Open.MSGraph.Model.ConditionalAccessApplicationCondition
$conditions.Applications.IncludeApplications = 'All'
#Create the user condition and include secmon
$conditions.Users = New-Object -TypeName Microsoft.Open.MSGraph.Model.ConditionalAccessUserCondition
$conditions.Users.IncludeUsers = $secmon_guid
#Add new location policy to CA policy
$conditions.Locations = New-Object -TypeName Microsoft.Open.MSGraph.Model.ConditionalAccessLocationCondition
$conditions.Locations.IncludeLocations = $location_policy_guid
#Grant access control to CA policy
$controls = New-Object -TypeName Microsoft.Open.MSGraph.Model.ConditionalAccessGrantControls
$controls._Operator = "OR"
$controls.BuiltInControls = "block"
#End work
New-AzureADMSConditionalAccessPolicy `
-DisplayName $name `
-State $state `
-Conditions $conditions `
-GrantControls $controls
The error I get is due to poorly formatted GUID's, the values I am pulling are not correct. How can I fix this? Any help is greatly appreciated!
New-AzureADMSConditionalAccessPolicy : Error occurred while executing NewAzureADMSConditionalAccessPolicy
Code: BadRequest
Message: 1054: Invalid location value: #{Id=1234GUID}.
InnerError:
RequestId: 5678GUID
Where you define the variables, you need to use -ExpandProperty on the select-object statement e.g:
$secmon_guid = Get-MsolUser -SearchString "secmon" | Select -ExpandProperty ObjectID
Otherwise, you would have to access your current variable like so:
$conditions.Users.IncludeUsers = $secmon_guid.ObjectID

Assign the result of a query to a variable in powershell in Azure-Runbooks

I have a runbook using automation in Azure. It is getting a single integer result from a table and it can return the correct value. The code I am using is below and it works.
$SQLServerCred = Get-AutomationPSCredential -Name "SqlCredential"
#Import the SQL Server Name from the Automation variable.
$SQL_Server_Name = Get-AutomationVariable -Name "SqlServer"
#Import the SQL DB from the Automation variable.
$SQL_DB_Name = Get-AutomationVariable -Name "Database"
$Query = "select max(je.ExecutionOrder) as LastStepExecuted
from PPoint.JobExecutionHistory je
where je.EventType = 'Start'
and je.JobRunId = PPoint.fnGetJobRunID()"
invoke-sqlcmd -ServerInstance "$SQL_Server_Name" -Database "$SQL_DB_Name" -Credential $SQLServerCred -Query "$Query" -Encrypt
The next step for me is to assign the result from the query to a variable and then evaluate it to see if it should call another runbook. So I want to have a variable named LastStep and assign it the integer result of LastStepExecuted from the query below. I then want to do something along this line (this is pseudocode)
if LastStep = 2147483647
call another runbook
else
do nothing - end the runbook
I have tried several ways to capture the LastStepExecuted in a variable but I can't figure it out. Can anyone help?
Any help or advice much appreciated.
You can use the Start-AzAutomationRunbook cmdlet to trigger a child runbook from the another run book inside the automation account.
$SQLServerCred = Get-AutomationPSCredential -Name "SqlCredential"
#Import the SQL Server Name from the Automation variable.
$SQL_Server_Name = Get-AutomationVariable -Name "SqlServer"
#Import the SQL DB from the Automation variable.
$SQL_DB_Name = Get-AutomationVariable -Name "Database"
$Query = "select max(je.ExecutionOrder) as LastStepExecuted
from PPoint.JobExecutionHistory je
where je.EventType = 'Start'
and je.JobRunId = PPoint.fnGetJobRunID()"
$LastStep=invoke-sqlcmd -ServerInstance "$SQL_Server_Name" -Database "$SQL_DB_Name" -Credential $SQLServerCred -Query "$Query" -Encrypt
if($LastStep -eq 2147483647)
{
Start-AzAutomationRunbook -AutomationAccountName "MyAutomationAccount" -Name "Test-ChildRunbook" -ResourceGroupName "LabRG" -DefaultProfile $AzureContext -Parameters $params -Wait
}
else
{
Write-Output "conditionfailed the value of $LastStep"
}
You can refer this documentation, about modular runbooks in azure automation.

Parse Excel variables into powershell

I am trying to create a powershell that will grab the varibles from an excel sheet and then add them to the powersehll command.
in the excel sheet i have 3 columns i am interested in the data from (Name , resourcegroup, location)
And then for each line with this i want it to parse into into the varible field for the powershell
I have created the powershell to do what i need but it would be better if it could loop through and pull this as I am just running the command again with different machine info manually added from the excel.
With #Theo Help
I am working with this version of the script now
Import-Csv -Path 'c:\scripts\vmtest.csv' | ForEach-Object {
# combine the VMName with suffix '-Snapshot'
$snapshotName = $vm.name + "-Snapshot"
$SnapshotStorage = "Azure-Snapshots"
$vm = Get-AzVM -ResourceGroupName $_.ResourceGroup -Name $_.Name
# using splatting for better readability
$configParams = #{
SourceUri = $vm.StorageProfile.OsDisk.ManagedDisk.Id
Location = $_.location
CreateOption = 'copy'
}
$snapshot = New-AzSnapshotConfig #configParams
New-AzSnapshot -Snapshot $snapshot -SnapshotName $snapshotname -ResourceGroupName $snapshotstorage
}
If as you have commented, you now have the data stored in a CSV file that might look something like this:
Name,ResourceGroup,Location
PRD-ITM001,SJAVIRTUALMACHINES,uksouth
TST-GRSSQL001,SJAVIRTUALMACHINES,uksouth
it has become very simple to import that data and loop through the records like below:
Import-Csv -Path 'c:\scripts\vmtest.csv' | ForEach-Object {
# combine the VMName with suffix '-Snapshot'
$snapshotName = '{0}-Snapshot' -f $_.Name
$SnapshotStorage = "Azure-Snapshots"
$vm = Get-AzVM -ResourceGroupName $_.ResourceGroup -Name $_.Name
# using splatting for better readability
$configParams = #{
SourceUri = $vm.StorageProfile.OsDisk.ManagedDisk.Id
Location = $_.Location
CreateOption = 'copy'
}
$snapshot = New-AzSnapshotConfig #configParams
New-AzSnapshot -Snapshot $snapshot -SnapshotName $snapshotName -ResourceGroupName $_.ResourceGroup
}
Note that the above code assumes your CSV uses the (default) comma as delimiter character. If in your case this is some other character, append parameter -Delimiter followed by the character the csv uses.
Inside a ForEach-Object {..} loop, the $_ automatic variable references the current record from the csv
I used Splatting for better readability of the code. This helps on cmdlets that take a long list of parameters and eliminates the use of the backtick.
Based on the above shared requirement, we understood that you want to pull the values of ResourceGroupName, VMName from the excel sheet & also you want to use those values in the script further.
Using PSExcel Module, We have written the below PowerShell Script which will pull the ResourceGroupName, VMName from excel & it will run Get-AzVM Cmdlet.
Before running the below PowerShell script , run the below cmdlet Save-Azcontext cmdlet it will saves the current authentication information for use in other PowerShell sessions.
Connect-AzAccount
Save-AzContext -Path C:\test.json
Here is the PowerShell script:
$currentDir = "C:\Program Files\WindowsPowerShell\Modules" ##pass the path of the PSexcel Module
Import-Module $currentDir"\PSExcel"
Import-AzContext -Path C:\test.json ##passing the azcontext file path which was saved earlier
$ExcelFile = "Give here the path of the current folder where scripts are stored"
$objExcel = New-Excel -Path $ExcelFile
$WorkBook = $objExcel|Get-Workbook
ForEach($Worksheet in #($Workbook.Worksheets)){
$totalNoOfRecords = $Worksheet.Dimension.Rows
$totalNoOfItems = $totalNoOfRecords-1
# Declare the starting positions first row and column names
$rowNo,$colResourceGroupName = 1,1
$rowNo,$colVMName = 1,2
if ($totalNoOfRecords -gt 1){
#Loop to get values from excel file
for($i=1;$i -le ($totalNoOfRecords-1);$i++){
$ResourceGroupName=$Worksheet.Cells.Item($rowNo+$i,$colResourceGroupName).Value
$VMName=$Worksheet.Cells.Item($rowNo+$i,$colVMName).Value
Get-AzVM -ResourceGroupName $ResourceGroupName -Name $VMName |select -Property Name,ResourceGroupName,Location
}
}
}
Here is the sample output for reference:
For more information ,you refer this blog post on How to Read excel file using PSExcel Module in PowerShell.

Recursively list all resource tags within Azure Resource Groups

We have a large number of Azure Subscriptions which currently run into the hundreds.
I'm looking to generate a report (ideally using Azure Powershell or Azure CLI) to recursively extract a list of all tags assigned to every single resource within every resource group, for between 40-50 of the subscriptions.
Currently, I can list all tags assigned at Resource Group level, but I simply can't find a way to list the tags assigned to the individual resources within each Resource Group. The list of subscriptions and resource groups on which I'd like to extract this report, are saved in a CSV file which includes two columns displaying the Subscription name and Resource Group respectively.
Any tips on how to achieve the above would be fantastic and most appreciated.
Not detailed code but the idea here.
1.You should write a loop, in the loop, change the subscription each time by using this cmdlet:
Set-AzContext -Subscription $subscription_name.
2.Then get all the resource group in the specified subscription by using this cmdlet:
$resource_groups = Get-AzResourceGroup
3.Then write a nested loop(loop for each resource group), in this nested loop, use this cmdlet to get all azure resources within a resource group:
foreach($rg in $resource_groups){
$azure_resources = Get-AzResource -ResourceGroupName $rg.ResourceGroupName
}
4.Write another nested loop in step 3, this loop is used to go though all the azure resources within the specified resource group. Then use the code below to fetch tags for each azure resource within the resource group:
foreach($r in $azure_resources){
#the following code can get all the tags for one resource
$r.tags
}
Based on Ivan Yang's logic. I have built the PowerShell Script;
#---------DECLARE VARIABLES------------------------------------#
$bnsSubscription = Get-AzSubscription
$day = Get-Date -Format " ddMMMyyyy"
$tagPath = "C:\mytempfolder\"+"$day-Tag-Details.csv"
$tagFolderPath = "C:\mytempfolder\"
#---------DECLARE VARIABLES------------------------------------#
function Get-ResourceTag {
foreach ($subs in $bnsSubscription) {
Select-AzSubscription -SubscriptionName $subs.Name | Out-Null
Write-Host 'The selected Subscription is' ($subs).Name
New-Item -ItemType file -Path "$tagFolderPath\$($subs.Name).csv" -Force
$resource_groups = Get-AzResourceGroup
$resource_groups_details = Get-AzResourceGroup | Sort-Location ResourceGroupName | Format-Table -GroupBy Location ResourceGroupName,ProvisioningState,Tags
Write-Host 'The selected Resource Group is' ($resource_groups).Name 'and the tag information as follows'
#$resource_groups_details
$resource_groups | Select-Object ResourceGroupName,Tags | Export-CSV -Path "$tagFolderPath\$($subs.Name).csv" -Append
$OutputFile = #()
foreach($rg in $resource_groups){
$azure_resources = Get-AzResource -ResourceGroupName $rg.ResourceGroupName
$TestTags = $Resource.Tags.GetEnumerator()
foreach($r in $azure_resources){
Write-Host 'The selected resource is' ($r).Name 'and the information as follows'
$RGHT = New-Object "System.Collections.Generic.List[System.Object]"
$RGHT.Add("RGName",$r.ResourceGroupName)
$RGHT.Add("ResourceName",$r.name)
$RGHT.Add("Location",$r.Location)
$RGHT.Add("Id",$r.ResourceId)
$RGHT.Add("ResourceType",$r.ResourceType)
$RGHT.Add("ResourceTags",$r.Tags)
$OutputFile += New-Object psobject -Property $RGHT
$OutputFile | Export-Csv -Path "C:\mytempfolder\test22.csv" -append -NoClobber -NoTypeInformation -Encoding UTF8 -Force
}
}
}
}
#---------CALL FUNCTION------------------------------------#
Get-ResourceTag

Resources