Powershell mandatory parameters, I am a newbie to PowerShell scripting - powershell

I have task on my ci/cd that calls below powershell script meant to stop a function before other deployment tasks on the same job. The script seem to throwing error even though I have all the variables correctly set. Please help and many thanks in advance..
#####Script#######
Param(
[Parameter(Mandatory)][string] $XxxxFunctionAppName,
[Parameter(Mandatory)][string] $ResourceGroupName
)
#stoping function app
$trap = Get-AzFunctionApp -Name $XxxxFunctionAppName -ResourceGroupName $ResourceGroupName -ErrorAction SilentlyContinue
if($trap.state -eq "Running")
{
Stop-AzFunctionApp -Force
}
####Error message#####
2021-04-06T10:24:43.3332161Z ## Validating Inputs
2021-04-06T10:24:43.3390381Z ## Validating Inputs Complete
2021-04-06T10:24:43.4262841Z ## Initializing Az module
2021-04-06T10:24:43.6949853Z Added TLS 1.2 in session.
2021-04-06T10:24:44.0148107Z ##[command]Import-Module -Name C:\Program Files\WindowsPowerShell\Modules\Az.Accounts\1.9.0\Az.Accounts.psd1 -Global
2021-04-06T10:24:44.9908767Z ##[command]Clear-AzContext -Scope CurrentUser -Force -ErrorAction SilentlyContinue
2021-04-06T10:24:45.5333784Z ##[command]Clear-AzContext -Scope Process
2021-04-06T10:24:45.9446194Z ##[command]Connect-AzAccount -ServicePrincipal -Tenant *** -Credential System.Management.Automation.PSCredential -Environment AzureCloud #processScope
2021-04-06T10:24:46.9272395Z ##[command] Set-AzContext -SubscriptionId XXXXXXXXXXXXXXX -TenantId ***
2021-04-06T10:24:47.4342523Z ## Az module initialization Complete
2021-04-06T10:24:47.4352242Z ## Beginning Script Execution
2021-04-06T10:24:47.4690205Z ##[command]& 'c:\vstsagent\A4\_work\r241\a\_xxxxxxxxxxxx\Scripts\Stopxxxx.ps1' -xxxxFunctionAppName "func-xxxxx-develop-02" -ResourceGroupName "xxxxx-develop-rg"
2021-04-06T10:24:50.7841003Z ##[command]Disconnect-AzAccount -Scope Process -ErrorAction Stop
2021-04-06T10:24:51.2391709Z ##[command]Clear-AzContext -Scope Process -ErrorAction Stop
2021-04-06T10:24:51.8052164Z ##[error]Cannot process command because of one or more missing mandatory parameters: Name ResourceGroupName.
2021-04-06T10:24:51.8527691Z ##[section]Finishing: StopxxxxFunc

Related

Powershell incorrect running sequence

Kinda new to powershell and trying to write scripts in general. Im trying to create a script that creates an AD user and then assigns that user a license.
However doesn't seem to matter what I do, the sync command I have doesnt execute before the waiting period; so it cant find the user to assign the license to.
Any ideas what Im getting wrong?
`$DCSync = 'DC01'
#Starts AD Sync
Invoke-Command -ComputerName $DCSync -scriptblock {
Import-Module ADSync
Start-ADSyncSyncCycle -PolicyType Delta
Write-Output "testing"
}
send-mailmessage -From "abc#test123.co.uk" -To "abcHelpdesk#test123.co.uk" -Subject "New user creation" -Body "Please connect to DC01 and authenticate to Office 365 to complete the user setup for $UserPrincipalName" -SmtpServer [REDACTED]
Start-Countdown -Seconds 5 -Message "Synchronizing changes to Office 365"
#Install-Module PowerShellGet
#Install-Module Microsoft.Graph -Scope CurrentUser
#Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope CurrentUser
Connect-MgGraph -Scopes User.ReadWrite.All, Organization.Read.All
$MgUserID = Get-MgUser -UserId "$EmailAddress"
Update-MgUser -UserId "$MgUserID" -UsageLocation GB
Set-MgUserLicense -UserId $MgUserID -AddLicenses #{SkuId = "6fd2c87f-b296-42f0-b197-1e91e994b900" } -RemoveLicenses #()`
Write-Outpost "testing" always prints after the ADsync commands
Creating a user - assigning a license to newly created user
It just errors out because its not syncing to AD using the command so the user doesn't 'exist' yet
A couple of thoughts:
Try using Start-Sleep rather than Start-Countdown
If it isn't asynchronous, you can try running Start-ADSyncSyncCycle -PolicyType Delta using the -AsJob parameter, and then retrieve the status of that job using a while loop and not proceeding until the job is completed
If you have the e-mail address, then you can use a while loop to not proceed until the account is created, like:
while ($null -eq $MgUserID){
try {
$MgUserID = Get-MgUser -UserId "$EmailAddress"
}
catch {
$MgUserID = $null
}
Start-Sleep -Seconds 30
}

Failure when creating service fabric cluster with powershell

I'm trying to create a service fabric cluster with a powershell script. Here's the script:
Param(
[Parameter(HelpMessage="Azure user name")]
[String]$azUserName,
[Parameter(HelpMessage="Azure password")]
[String]$azPassword,
[Parameter(HelpMessage="What is the resource group name?")]
[String]$ResourceGroupName="sfLinuxClusterRg",
[Parameter(HelpMessage="What is the key vault group name?")]
[String]$KeyVaultResourceGroupName="KeyVaultRg",
[Parameter(HelpMessage="Where is the azure location?")]
[String]$Location="uksouth",
[Parameter(HelpMessage="what is the key vault group?")]
[String]$VaultGroupName="linuxclusterkeyvaultgroup",
[Parameter(HelpMessage="Where is the certificate stored locally?")]
[String]$CertFileName="certificate.pfx",
[Parameter(HelpMessage="What is the subscription id?")]
[String]$SubscriptionId,
[Parameter(HelpMessage="What is the tenant id?")]
[String]$TenantId
)
Function DecryptSecureString([SecureString] $secureText){
return [Runtime.InteropServices.Marshal]::PtrToStringAuto([Runtime.InteropServices.Marshal]::SecureStringToBSTR($secureText))
}
Function CreateKeyVaultCert(){
try{
Select-AzureRmSubscription -SubscriptionId $SubscriptionId `
-TenantId $TenantId
# Create a Resource Group to hold your Key Vault(s)
# Note this should be separate from your other resources so you can delete those other resource groups without impacting your registered certs
New-AzureRmResourceGroup -Name $KeyVaultResourceGroupName -Location uksouth -Force
# Create a Key Vault to hold your secrets
New-AzureRmKeyVault -VaultName $vaultName -ResourceGroupName $KeyVaultResourceGroupName `
-Location uksouth -EnabledForDeployment `
-EnabledForDiskEncryption -EnabledForTemplateDeployment
# Have Key Vault create the certificate with a simple policy
$policy = New-AzureKeyVaultCertificatePolicy `
-SubjectName "CN=cluster123.uksouth.cloudapp.azure.com" `
-IssuerName Self -ValidityInMonths 12
Add-AzureKeyVaultCertificate -VaultName $vaultName -Name cert1 -CertificatePolicy $policy
Set-AzureRmKeyVaultAccessPolicy -VaultName $vaultName -EnabledForDeployment
Set-AzureRmKeyVaultAccessPolicy -VaultName $vaultName -EmailAddress $azUserName -PermissionsToSecrets Get
}
catch{
Write-Host $_.Exception.Message
exit
}
}
$azPassword = $azPassword | ConvertTo-SecureString -AsPlainText -Force
Import-AzureRmContext -Path "C:\stuff\AzureProfile.json"
$Date = Get-Date
$VaultName="VaultLearn" + $Date.ToString("hhmmss")
# sign in to your Azure account and select your subscription
$certName = "CN=cluster123.uksouth.cloudapp.azure.com"
$clustersize=5
$clustername = "cluster123" + $Date.ToString("hhmmss")
$adminuser="admin"
$vmsku = "Standard_D2_v2"
$os = "UbuntuServer1604"
Select-AzureRmSubscription -SubscriptionId $SubscriptionId
CreateKeyVaultCert
New-AzureRmServiceFabricCluster -Name $clustername `
-ResourceGroupName $ResourceGroupName `
-Location uksouth `
-ClusterSize $clustersize `
-VmUserName $adminuser -VmPassword $azPassword `
-CertificateSubjectName $certName `
-CertificatePassword $azPassword `
-VmSku $vmsku `
-CertificateOutputFolder 'C:\stuff' `
-OS $os `
-KeyVaultName $VaultName
Write-Host "Created service fabric cluster in resource group $ResourceGroupName"
#Add-AzureRmAccount
# $path = "C:\stuff\AzureProfile.json"
# Save-AzureRmContext -Path $path -Force
I keep getting the error:
New-AzureRmServiceFabricCluster : The name 'VaultLearn090903' is already in use.
This is really weird, because I'm pretty sure yesterday this script at least attempted to create the cluster, although I was getting another error about Ubuntu image not being found. What could be causing this error?
By the way, in order to run this script, I have previously run this code:
Add-AzureRmAccount
$path = "C:\stuff\AzureProfile.json"
Save-AzureRmContext -Path $path -Force
which has cached my azure credentials locally.
I have specifically added two statements into the script to add a policy for access to the keyvault:
Set-AzureRmKeyVaultAccessPolicy -VaultName $vaultName -EnabledForDeployment
Set-AzureRmKeyVaultAccessPolicy -VaultName $vaultName -EmailAddress $azUserName -PermissionsToSecrets Get
I know this is probably overkill, but I'm trying to get rid of this problem.
The other weird thing is I have tried the Azure Sample Github repo
I'm at a loss for how I can continue with service fabric.
For completeness:
I managed to get something different working by going to the azure portal, creating a service fabric cluster and downloading the ARM template (which includes some powershell scripts).
thanks

A positional parameter cannot be found that accepts argument 'System.Management.Automation.PSCredential'

I'm try running a DSC configuration in azure automations, but it get's suspended with following exception:
"The running command stopped because the preference variable
"ErrorActionPreference" or common parameter is set to Stop: A
positional parameter cannot be found that accepts argument
'System.Management.Automation.PSCredential'.
The code I'm running is :
Configuration DomainJoin{
$cred = Get-AutomationPSCredential -Name "azurelogin"
Login-AzureRmAccount $cred
Import-DscResource -ModuleName 'PSDesiredStateConfiguration'
Import-DscResource -ModuleName 'xDSCDomainjoin'
$dscDomainAdmin = Get-AzureRmAutomationCredential -Name "GSY admin" -ResourceGroupName "RG-DC-ROCS" -AutomationAccountName "RocsAutomation"
$dscDomainName = Get-AzureRMAutomationVariable -Name "dscDomainName" -ResourceGroupName "RG-DC-ROCS" -AutomationAccountName "RocsAutomation"
#PSDscAllowDomainUser = $True
node localhost
{
xDSCDomainjoin JoinDomain
{
Domain = $dscDomainName
Credential = $dscDomainAdmin
}
}
}
Any idea how I can solve the exception?
I think you might need to change:
Login-AzureRmAccount $cred
To:
Login-AzureRmAccount -Credential $cred
It seems that -Credential has to be named to be used.

Upgrading Tier (Sku) via Set-AzureRmAnalysisServicesServer not working

I want to upscale and downscale my Azure Analysis Services with PowerShell (Automation Runbook), but changing the Tier (Sku) doesn't seem to work. However there are no errors. Any suggestions?
# PowerShell code
# Connect to a connection to get TenantId and SubscriptionId
$Connection = Get-AutomationConnection -Name "AzureRunAsConnection"
$TenantId = $Connection.TenantId
$SubscriptionId = $Connection.SubscriptionId
# Get the service principal credentials connected to the automation account.
$null = $SPCredential = Get-AutomationPSCredential -Name "SSISJoost"
# Login to Azure ($null is to prevent output, since Out-Null doesn't work in Azure)
Write-Output "Login to Azure using automation account 'SSISJoost'."
$null = Login-AzureRmAccount -TenantId $TenantId -SubscriptionId $SubscriptionId -Credential $SPCredential
# Select the correct subscription
Write-Output "Selecting subscription '$($SubscriptionId)'."
$null = Select-AzureRmSubscription -SubscriptionID $SubscriptionId
# Get variable values
$ResourceGroupName = Get-AutomationVariable -Name 'ResourceGroupName'
$AnalysisServerName = Get-AutomationVariable -Name 'AnalysisServerName'
# Get old status (for testing/logging purpose only)
$OldAsSetting = Get-AzureRmAnalysisServicesServer -ResourceGroupName $ResourceGroupName -Name $AnalysisServerName
try
{
# changing tier
Write-Output "Upgrade $($AnalysisServerName) to S1. Current tier: $($OldAsSetting.Sku.Name)"
Set-AzureRmAnalysisServicesServer -ResourceGroupName $ResourceGroupName -Name $AnalysisServerName -Sku "S1"
}
catch
{
Write-Error -Message $_.Exception
throw $_.Exception
}
Write-Output "Done"
# Get new status (for testing/logging purpose only)
$NewAsSetting = Get-AzureRmAnalysisServicesServer -ResourceGroupName $ResourceGroupName -Name $AnalysisServerName
Write-Output "New tier: $($NewAsSetting.Sku.Name)"
using Set-AzureRmAnalysisServicesServer
There was a little bug in the PowerShell AzureRM.AnalysisServices module. It has been fixed in 0.4.0 (Thursday, June 08 2017)
Now the code finally works: http://microsoft-bitools.blogspot.com/2017/06/schedule-upscaledownscale-azure.html

Start-AzureStorageBlobCopy error in Automation runbook

I'm following this guide to automate backups of Linux VMs in Azure Automation. Everything goes well in testing on initial run, but the second and all subsequent tests return the following error:
11/26/2014 11:03:45 AM, Error: Start-AzureStorageBlobCopy : One or more errors occurred.
At LinuxVMBackup:40 char:40
+
+ CategoryInfo : CloseError: (:) [Start-AzureStorageBlobCopy], AggregateException
+ FullyQualifiedErrorId :
AggregateException,Microsoft.WindowsAzure.Commands.Storage.Blob.Cmdlet.StartAzureStorageBlobCopy
Here is the runbook:
workflow LinuxVMBackup
{
param (
[Parameter(Mandatory=$true)]
[PSCredential]
$Cred,
[Parameter(Mandatory=$true)]
[string]
$subName,
[Parameter(Mandatory=$true)]
[string]
$serviceName,
[Parameter(Mandatory=$true)]
[string]
$vmName
)
# Login and get VM
$null = Add-AzureAccount -Credential $Cred
$null = Select-AzureSubscription -SubscriptionName $subName
$vm = Get-AzureVM -ServiceName $serviceName -Name $vmName
# Stop VM
$vm | Stop-AzureVM -StayProvisioned
# Get OS and Data Disks
$vmOSDisk = Get-AzureOSDisk -VM (Get-AzureVM -ServiceName $serviceName -Name $vmName)
$vmDataDisks = Get-AzureDataDisk -VM (Get-AzureVM -ServiceName $serviceName -Name $vmName)
# Get and set storage name
$StorageAccountName = $vmOSDisk.MediaLink.Host.Split('.')[0]
Set-AzureSubscription -CurrentStorageAccount $StorageAccountName -SubscriptionName $subName
$backupContainerName = "backups"
if (!(Get-AzureStorageContainer -Name $backupContainerName -ErrorAction SilentlyContinue)) {
New-AzureStorageContainer -Name $backupContainerName -Permission Off
}
# Snapshot OS Disk
$vmOSBlobName = $vmOSDisk.MediaLink.Segments[-1]
$vmOSContainerName = $vmOSDisk.MediaLink.Segments[-2].Split('/')[0]
#Error on this line
Start-AzureStorageBlobCopy -SrcContainer $vmOSContainerName -SrcBlob $vmOSBlobName -DestContainer $backupContainerName
#Error on this line
Get-AzureStorageBlobCopyState -Container $backupContainerName -Blob $vmOSBlobName -WaitForComplete
#Snapshot Data Disks
ForEach ($vmDataDisk in $vmDataDisks) {
$vmDataBlobName = $vmDataDisk.MediaLink.Segments[-1]
$vmDataContainerName = $vmDataDisk.MediaLink.Segments[-2].Split('/')[0]
Start-AzureStorageBlobCopy -SrcContainer $vmDataContainerName -SrcBlob $vmDataBlobName -DestContainer $backupContainerName -Force
Get-AzureStorageBlobCopyState -Container $backupContainerName -Blob $vmDataBlobName -WaitForComplete
}
#Get blobs in storage and output
$insertedBlobs = Get-AzureStorageBlob -Container $backupContainerName
Write-Output $insertedBlobs
$vm | Start-AzureVM
}
I couldn't find anything online, save an answer on Microsoft forums for a similar error stating that the VM needs to be stopped, so I thought maybe the VM is not fully stopped when Start-AzureStorageBlobCopy is initiated. I tried testing with a stopped VM and still got the error.
Thanks for your help.
Given the error only happens after the first successful copy, what is probably happening is the Start-AzureStorageBlobCopy cmdlet is trying to request user confirmation for the operation, since it would overwrite existing data. Since Azure Automation runs runbooks in a non-interactive session, user confirmation cannot be asked, so the command is failing.
Adding -Force should "force" user confirmation for the cmdlet and fix the issue. You have this parameter on the second instance of Start-AzureStorageBlobCopy, but not the first.
PS - You should put this runbook in our runbook gallery so others can take advantage of it!