Unable is issue command in Azure Powershell

Hello Experts

Can someone please let me know why I'm getting the following error when trying to add the New-Object command in Microsoft Azure powershell?

Who is Participating?
Lawrence TseConnect With a Mentor Principle ConsultantCommented:
I found 2 problems:
1. Why you still get "c:\azurekeys\.pfx", is because you are using "$keySpath" instead of "$keypath" (one more "S") thus you are using an old variable residue.

2. please try typing "$keyname" and press <enter>, I bet it will be empty.  You need to identify your certificate file name.  For example, if it is "MyCert.pfx", you need to type in $keyname="MyCert" and press <enter>, so that the $keyname variable is stored with the correct certificate file name value.

When you can successfully read the file, then the file binary data will be filled into the $bytes buffer, thus the [System.Convert]::ToBase64String($bytes) command will not give error.

Lawrence TsePrinciple ConsultantCommented:
Maybe you would like to try the code below:

$cert=New-Object System.Security.Cryptography.X509Certificates.X509Certificate2

Open in new window

Member_2_7966113Author Commented:
Hi Lawrence,

The full code is as follows:

$cert = new-object System.Security.Cryptography.X509Certificates.X509Certificate2 $keysPath, $passwordEnc

Open in new window

Will You Be GDPR Compliant by 5/28/2018?

GDPR? That's a regulation for the European Union. But, if you collect data from customers or employees within the EU, then you need to know about GDPR and make sure your organization is compliant by May 2018. Check out our preparation checklist to make sure you're on track today!

Lawrence TsePrinciple ConsultantCommented:

Is the purpose of the whole script is to load in a .pfx file with password and then to retrieve the thumbprint?

If that's the case you can use this:

$cert=New-Object System.Security.Cryptography.X509Certificates.X509Certificate2
$cert.Import("YourPFXFilePath.pfx", "password", [System.Security.Cryptography.X509Certificates.X509KeyStorageFlags]"Exportable")

Open in new window

You can change the flag "Exportable" to one of, or combination of the followings:


Member_2_7966113Author Commented:
Hi Lawrence,

So, in light of your suggestions, I thought I would start from scratch.

I entered the following commands:

ResourceGroupName : mykevaultrg
Location          : westus
ProvisioningState : Succeeded
Tags              :
ResourceId        : /subscriptions/zxxx.xxxxx.xxxx.xxxxxx/resourceGroups/mykevaultrg

PS C:\Users\Carlton\Google Drive\AZURE\Service Fabric> New-AzureRmKeyVault -VaultName $vaultName -resourceGroup $resourceGroup -Location $location -EnabledForDeployment -EnabledForTemplateDeployment

Vault Name                       : mykevaultname
Resource Group Name              : mykevaultrg
Location                         : WestUS
Resource ID                      : /subscriptions/xxxx.xxxxx.xxxxx.xxxxx/resourceGroups/mykevaultrg/
Vault URI                        : https://mykevaultname.vault.azure.net
Tenant ID                        : xxxxx.xxx.xxxx.xxxx.xxxxxx
Enabled For Template Deployment? : True
Enabled For Disk Encryption?     : False
Soft Delete Enabled?             :
Access Policies                  :
                                   Tenant ID                                  :
                                   Object ID                                  :
                                   Application ID                             :
                                   Display Name                               : Carlton Patterson
                                   Permissions to Keys                        : get, create, delete, list,
                                   update, import, backup, restore, recover
                                   Permissions to Secrets                     : get, list, set, delete, backup,
                                   restore, recover
                                   Permissions to Certificates                : get, delete, list, create,
                                   import, update, deleteissuers, getissuers, listissuers, managecontacts,
                                   manageissuers, setissuers, recover
                                   Permissions to (Key Vault Managed) Storage : delete, deletesas, get, getsas,
                                   list, listsas, regeneratekey, set, setsas, update
Tags                             :

PS C:\Users\Carlton\Google Drive\AZURE\Service Fabric> $keypath = "c:\certs\$keyname.pfx"

PS C:\Users\Carlton\Google Drive\AZURE\Service Fabric> $passwordEnc = ConvertTo-SecureString -String $password -AsPlainText -Force

PS C:\Users\Carlton\Google Drive\AZURE\Service Fabric> $bytes = [System.IO.File]::ReadAllBytes($keysPath)

The script is still looking for c:\azurekeys\.pfx even though I didn't specify above, see error below

Exception calling "ReadAllBytes" with "1" argument(s): "Could not find file 'c:\azurekeys\.pfx'."
At line:1 char:1
+ $bytes = [System.IO.File]::ReadAllBytes($keysPath)
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [], MethodInvocationException
    + FullyQualifiedErrorId : FileNotFoundException

Thanks for the additional information, but can you help resolve the above before I implement the rest of your suggestion.

Lawrence TsePrinciple ConsultantCommented:
If possible please post your screen captures during step by step execution from very beginning (please remove your personal sensitive data), I can read them through and give you some suggestion if I can.

Member_2_7966113Author Commented:
Hi Lawrence,

Thanks for helping out.

Here are the screen cap up until the error:

Member_2_7966113Author Commented:
Hi Lawrence,

Great answer. I have applied your suggestion and I have managed to get past the problem with keySpath.

However, the script now fails at

[System.Convert]::ToBase64String([System.IO.File]::ReadAllBytes("$keylocation.pfx")) | Out-File "$keylocation.txt"

Open in new window

I get the following error message, see image:

Can you assist?

I have attached the script again:

$subscriptionId = 'xxxx.xxxxx.xxxxxx.xxxxxx'; #Pre Production        
        $resourceGroup = 'mykevaultrg'
        $location = 'WestUS'
        $vaultName = 'mykevault'
        $keyname = 'mykevaultname'
        $password = 'Patters0n'

Select-AzureRmSubscription -SubscriptionId $subscriptionId
Set-AzureRmContext -SubscriptionId $subscriptionId

if(Get-AzureRmResourceGroup -Name $resourceGroup){
    Write-Output "Deleteing Resource Group $resourceGroup"
    Remove-AzureRmResourceGroup -Name $resourceGroup -Force
    Write-Output 'No Resource Group found'

New-AzureRmResourceGroup -Name $resourceGroup -Location $location
New-AzureRmKeyVault -VaultName $vaultName -resourceGroup $resourceGroup -Location $location -EnabledForDeployment -EnabledForTemplateDeployment

Import-Module "$THIS_SCRIPTS_DIRECTORY\ServiceFabricRPHelpers.psm1"

$keypath = "c:\azurekeys\$keyname.pfx"

$passwordEnc = ConvertTo-SecureString -String $password -AsPlainText -Force

$bytes = [System.IO.File]::ReadAllBytes($keypath)
$base64 = [System.Convert]::ToBase64String($bytes)

$jsonBlob = @{ 
    data = $base64
    dataType = 'pfx'
    password = $password
        } | ConvertTo-Json 
            $contentBytes = [System.Text.Encoding]::UTF8.GetBytes($jsonBlob) 
            $content = [System.Convert]::Tobase64String($contentBytes) 
            $secretValue = ConvertTo-SecureString -String $content -AsPlainText –Force
            Set-AzureKeyVaultSecret -VaultName $vaultName -Name $keyname -SecretValue $secretValue

$cert = new-object System.Security.Cryptography.X509Certificates.X509Certificate2 $keysPath, $passwordEnc

#Create Self Signed Cert
Invoke-AddCertToKeyVault -SubscriptionId $subscriptionId -resourceGroup $resourceGroup -Location $location -VaultName $vaultName -CertificateName $keyname -Password $pwd -CreateSelfSignedCertificate -DnsName 'cds-pp-02-careersvc.westeurope.cloudapp.azure.com' -OutputPath 'C:\certs\'
#Use existing cert
#Invoke-AddCertToKeyVault -SubscriptionId $subscriptionId -resourceGroup $resourceGroup -Location $location -VaultName $vaultName -CertificateName cds-prd-01-careersvc -Password $pwd -UseExistingCertificate -ExistingPfxFilePath $keypath

[System.Convert]::ToBase64String([System.IO.File]::ReadAllBytes("$keylocation.pfx")) | Out-File "$keylocation.txt"

Get-PfxCertificate -FilePath $keypath\NameOfCert.pfx

Open in new window

Member_2_7966113Author Commented:
Hi Experts,

Any more thoughts on this?
Member_2_7966113Author Commented:
This fixed the problem. Thanks Lawrence
All Courses

From novice to tech pro — start learning today.