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?

kop
Thanks
LVL 1
Member_2_7966113Asked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

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

$cert=New-Object System.Security.Cryptography.X509Certificates.X509Certificate2
$cert.Import("YourX509Cert.cer")

Open in new window


Cheers.
0
Member_2_7966113Author Commented:
Hi Lawrence,

The full code is as follows:

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

Open in new window

0
Lawrence TsePrinciple ConsultantCommented:
Hi,

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:

X509KeyStorageFlags
Reference:
https://msdn.microsoft.com/en-us/library/system.security.cryptography.x509certificates.x509keystorageflags(v=vs.110).aspx

Cheers.
0
Creating Active Directory Users from a Text File

If your organization has a need to mass-create AD user accounts, watch this video to see how its done without the need for scripting or other unnecessary complexities.

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/
                                   providers/Microsoft.KeyVault/vaults/mykevaultname
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                                  :
                                  xxxxxxxxxxxxxxxxxx.xxxxxxxxxxxxxxx
                                   Object ID                                  :
                                   6a451291-3b03-4255-98e3-993ac0209850
                                   Application ID                             :
                                   Display Name                               : Carlton Patterson
                                   (cpatte7372_outlook.com#EXT#@cpatte7372outlook.onmicrosoft.com)
                                   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.

Cheers
0
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.

Cheers.
0
Member_2_7966113Author Commented:
Hi Lawrence,

Thanks for helping out.

Here are the screen cap up until the error:

kop
kop
0
Lawrence TsePrinciple 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.

Cheers.
1

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
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:

kop
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
}
else
{
    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
$cert.Thumbprint


#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

0
Member_2_7966113Author Commented:
Hi Experts,

Any more thoughts on this?
0
Member_2_7966113Author Commented:
This fixed the problem. Thanks Lawrence
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Powershell

From novice to tech pro — start learning today.

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.