Currently, I'm Using the Connect-PnPOnline in a Powershell script:
Connect-PnPOnline -ClientId $tenant_client_id -ClientSecret $tenant_client_secret -Url $TenantUrl
When I run this code in the Windows PowerShell ISE, Works perfectly but if I try to run this in an Azure function this error appears:
ERROR: The type initializer for 'OfficeDevPnP.Core.Utilities.TokenHelper' threw an exception.
Exception :
Type : System.TypeInitializationException
TypeName : OfficeDevPnP.Core.Utilities.TokenHelper
TargetSite :
Name : ProcessRecord
DeclaringType : PnP.PowerShell.Commands.Base.ConnectOnline
MemberType : Method
Module : PnP.PowerShell.Online.Commands.dll
StackTrace :
at PnP.PowerShell.Commands.Base.ConnectOnline.ProcessRecord()
at System.Management.Automation.Cmdlet.DoProcessRecord()
at System.Management.Automation.CommandProcessor.ProcessRecord()
Message : The type initializer for 'OfficeDevPnP.Core.Utilities.TokenHelper' threw an exception.
Data : System.Collections.ListDictionaryInternal
InnerException :
Type : System.TypeLoadException
Message : Could not load type 'System.Web.Configuration.WebConfigurationManager' from assembly 'System.Web, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a'.
TypeName : System.Web.Configuration.WebConfigurationManager
TargetSite : Void .cctor()
StackTrace :
at OfficeDevPnP.Core.Utilities.TokenHelper..cctor()
Source : OfficeDevPnP.Core
HResult : -2146233054
Source : PnP.PowerShell.Online.Commands
HResult : -2146233036
CategoryInfo : NotSpecified: (:) [Connect-PnPOnline], TypeInitializationException
FullyQualifiedErrorId : System.TypeInitializationException,PnP.PowerShell.Commands.Base.ConnectOnline
InvocationInfo :
MyCommand : Connect-PnPOnline
ScriptLineNumber : 36
OffsetInLine : 1
HistoryId : 1
I need to use the Credential ID and The Client Secret to authenticate.
You may need to switch your Azure function to Version 1.0.
According to documentation version 2 is .NET Core 2 and function app version 1.0 ~. That should be the cause why it prompt "Could not load type 'System.Web.Configuration.WebConfigurationManager'.
Related
I am using the following to add in the AzureAD
Import-Module AzureAD -UseWindowsPowerShell
I have also added in 'AzureAD' = '2.*' in the requirements.psd1
Yet when I run the function I am getting the following error message:
ERROR: Failed to generate proxies for remote module 'AzureAD'. The -OutputModule parameter does not resolve to a path, and a user module path cannot be found for the provided name.Exception :Type : System.InvalidOperationExceptionMessage : Failed to generate proxies for remote module 'AzureAD'. The -OutputModule parameter does not resolve to a path, and a user module path cannot be found for the provided name.InnerException :Type : System.Management.Automation.CmdletInvocationExceptionErrorRecord :Exception :Type : System.ArgumentExceptionMessage : The -OutputModule parameter does not resolve to a path, and a user module path cannot be found for the provided name.TargetSite :Name : ThrowTerminatingErrorDeclaringType : System.Management.Automation.MshCommandRuntime, System.Management.Automation, Version=7.2.4.500, Culture=neutral, PublicKeyToken=31bf3856ad364e35MemberType : MethodModule : System.Management.Automation.dllSource : System.Management.AutomationHResult : -2147024809StackTrace :at System.Management.Automation.MshCommandRuntime.ThrowTerminatingError(ErrorRecord errorRecord)TargetObject : Microsoft.PowerShell.Commands.ExportPSSessionCommandCategoryInfo : InvalidArgument: (Microsoft.PowerShel…ortPSSessionCommand:ExportPSSessionCommand) [Export-PSSession], ArgumentExceptionFullyQualifiedErrorId : ExportPSSession_ErrorModuleNameOrPath,Microsoft.PowerShell.Commands.ExportPSSessionCommandInvocationInfo :MyCommand : Export-PSSessionHistoryId : 1InvocationName : Export-PSSessionCommandOrigin : InternalScriptStackTrace : at , C:\home\site\wwwroot\TimerTrigger1\run.ps1: line 3TargetSite :Name : InvokeDeclaringType : System.Management.Automation.Runspaces.PipelineBase, System.Management.Automation, Version=7.2.4.500, Culture=neutral, PublicKeyToken=31bf3856ad364e35MemberType : MethodModule : System.Management.Automation.dllMessage : The -OutputModule parameter does not resolve to a path, and a user module path cannot be found for the provided name.InnerException :Type : System.ArgumentExceptionMessage : The -OutputModule parameter does not resolve to a path, and a user module path cannot be found for the provided name.TargetSite :Name : ThrowTerminatingErrorDeclaringType : System.Management.Automation.MshCommandRuntime, System.Management.Automation, Version=7.2.4.500, Culture=neutral, PublicKeyToken=31bf3856ad364e35MemberType : MethodModule : System.Management.Automation.dllSource : System.Management.AutomationHResult : -2147024809StackTrace :at System.Management.Automation.MshCommandRuntime.ThrowTerminatingError(ErrorRecord errorRecord)Source : System.Management.AutomationHResult : -2146233087StackTrace :at System.Management.Automation.Runspaces.PipelineBase.Invoke(IEnumerable input)at System.Management.Automation.Runspaces.Pipeline.Invoke()at System.Management.Automation.PowerShell.Worker.ConstructPipelineAndDoWork(Runspace rs, Boolean performSyncInvoke)at System.Management.Automation.PowerShell.CoreInvokeHelper[TInput,TOutput](PSDataCollection1 input, PSDataCollection1 output, PSInvocationSettings settings)at System.Management.Automation.PowerShell.CoreInvoke[TInput,TOutput](PSDataCollection1 input, PSDataCollection1 output, PSInvocationSettings settings)at System.Management.Automation.RemoteDiscoveryHelper.InvokeNestedPowerShell(PowerShell powerShell, PSCmdlet cmdlet, PSInvocationSettings invocationSettings, String errorMessageTemplate, CancellationToken cancellationToken)+MoveNext()at System.Management.Automation.RemoteDiscoveryHelper.EnumerateWithCatch[T](IEnumerable1 enumerable, Action1 exceptionHandler)+MoveNext()HResult : -2146233079CategoryInfo : NotSpecified: (:) [Import-Module], InvalidOperationExceptionFullyQualifiedErrorId :
I tried to reproduce the same in my environment and got the same error:
I created a Function App with configuration settings like below:
To resolve the error, make sure to set the Runtime version as 4 like below:
I added 'AzureAD' = '2.*' in the requirements.psd1 file:
I created Http trigger function and got the module imported successfully like below:
using namespace System.Net
param($Request, $TriggerMetadata)
Import-Module -Name 'AzureAD' -UseWindowsPowershell
Push-OutputBinding -Name Response -Value ([HttpResponseContext]#{
StatusCode = [HttpStatusCode]::OK
Body = $body
})
Response:
If still the error persists, try creating a new Function App from scratch with latest versions.
Alternatively, you can also invoke the Http trigger multiple times to get the response successfully.
Reference:
Azure function - import module error by MayankBargali-MSFT
Edit:
I managed to get it to accept 1 parameter. Apparently it hates accepting 2. Now I've got another exception: remote server returning 401 unauthorized. I guess the solution for this is to not use more than 1 parameter, but that's not really a solution. Sounds like a bug to me.
Original question:
I'm at my wit's end on this one.
I have a powershell script that I'd like to execute during a Release that uploads an archived copy of the build to a document library in SharePoint. The build server that hosts TFS 2017 is running Powershell 4. When I RDP in and run the below script in ISE on the same server (precisely where TFS appears to be executing things in the tasks), it works, provided that I add the environment variables where they are commented in the script below.
When I run the same exact script (I'm running it from the drop folder) via TFS, it produces the error:
2017-10-17T13:48:52.5561597Z D:\BuildAgentWorkFolder\f00869677\Git\drop\publish_to_sharepoint.ps1 D:\Integration_20171017.2.zip Integration_20171017.2
2017-10-17T13:48:53.0241597Z Connecting to http://sharepoint_server/sites/TFS_DefaultCollection/NET as srv_promote...
2017-10-17T13:48:53.2737597Z ##[error]D:\BuildAgentWorkFolder\f00869677\Git\drop\publish_to_sharepoin
2017-10-17T13:48:53.2737597Z ##[error]t.ps1 : Cannot bind argument to parameter 'String' because it is null.
which is crazy, because you can clearly see the non-null arguments in the line executing the script.
I have tried specifying the type in the param section, like [string]$filePathToUpload. I have tried specifying the parameters in the command line arguments list, like .\publish_to_sharepoint.ps1 -filePathToUpload "..." -fileName "...", both with and without quotation marks.
One thing to note is when I try to run the task with an in-line powershell script-- because of the character limit, I can only paste up to the first "Write-Host" line-- it passes the parameter step without error and the release passes.
Is this a bug with TFS Powershell task? I can't wrap my head around where this error is coming from.
Thanks in advance. Below are the relevant details.
Powershell script:
param(
$filePathToUpload,
$fileName
)
#$Env:SharePointDomain = "..."
#$Env:SharePointBaseUrl = "http://sharepoint_server"
#$Env:SharePointSite = "/sites/TFS_DefaultCollection/NET/"
#$Env:SharePointUsername = "username"
#$Env:SharePointPassword = "password"
#$Env:SharePointLibrary = "library_name"
Add-Type -AssemblyName "Microsoft.SharePoint.Client, Version=16.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c, processorArchitecture=MSIL"
Add-Type -AssemblyName "Microsoft.SharePoint.Client.Runtime, Version=16.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c, processorArchitecture=MSIL"
Write-Host 'Connecting to'$Env:SharePointBaseUrl$Env:SharePointSite' as '$Env:SharePointUsername'...'
try{
$sharepointFullUrl = $Env:SharePointBaseUrl + $Env:SharePointSite
$clientContext = New-Object Microsoft.SharePoint.Client.ClientContext $sharepointFullUrl
$clientContext.Credentials = New-Object System.Net.NetworkCredential $Env:SharePointUsername, (ConvertTo-SecureString $Env:SharePointPassword -AsPlainText -Force)
$web = $clientContext.Web
$clientContext.Load($web)
$clientContext.ExecuteQuery();
$relDestFilePath = $Env:SharePointSite + $Env:SharePointLibrary + "/" + $fileName
$fStream = New-Object IO.FileStream $filePathToUpload ,'Open','Read','Read'
[Microsoft.SharePoint.Client.File]::SaveBinaryDirect($clientContext, $relDestFilePath, $fStream, $true)
Write-Host 'Successfully uploaded'$fileName' to SharePoint document library '$Env:SharePointLibrary'.'
}
catch {
Write-Error $_
}
Release Task Detail:
Release Environment Variables:
Powershell Task Log
2017-10-17T13:48:52.5405597Z . 'D:\BuildAgentWorkFolder\f00869677\Git\drop\publish_to_sharepoint.ps1' D:\Integration_20171017.2.zip Integration_20171017.2
2017-10-17T13:48:52.5561597Z C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe -NoLogo -NoProfile -NonInteractive -ExecutionPolicy Unrestricted -Command "$env:PSModulePath= $env:PSModulePath + ';' + $([system.io.path]::combine($env:AGENT_HOMEDIRECTORY, 'agent\worker\modules')); try { [System.Security.Cryptography.ProtectedData] | Out-Null } catch { Write-Verbose 'Adding assemly: System.Security' ; Add-Type -AssemblyName 'System.Security' ; [System.Security.Cryptography.ProtectedData] | Out-Null } ; Invoke-Expression -Command ([System.Text.Encoding]::UTF8.GetString([System.Security.Cryptography.ProtectedData]::Unprotect([System.Convert]::FromBase64String('AQAAANCMnd8BFdERjHoAwE/Cl+sAmMDwyguygfTgNLUK3BteusFUlUwAAAAACAAAAAAADZgAAwAAAABAAAACMb/7FzkttmPEf8rMCA10mAAAAAASAAACgAAAAEAAAAN7Pqk+I01BNW4lONiyiuhArrpBqYAAiGrvCfLy/fPm3YiAEuhiuhKwcUEIZFza2IcrqjhKCe4Qn8qRcPMfDEiw82ZUKdNYCrzUjayfThC97Vm3/lNgP15sgTr0NpJwsfvs7fz6zG3zwqwNeu4ivYzcYI/bYd+y608v+jh3d+8vzeQgyIGhto+9WcJlIaCnYv5qymVD7nTME8pnYz+DfNkP02s50jkCySimKgVHGIUAAAAkXCoQxu5+9njKHMCkhB2FSpdivg='), [System.Convert]::FromBase64String('McDlBBSayxJHIwJ35ERNNQ=='), [System.Security.Cryptography.DataProtectionScope]::CurrentUser))) ; if (!(Test-Path -LiteralPath variable:\LastExitCode)) { Write-Verbose 'Last exit code is not set.' } else { Write-Verbose ('$LastExitCode: {0}' -f $LastExitCode) ; exit $LastExitCode }"
2017-10-17T13:48:52.5561597Z Executing the following powershell script. (workingFolder = D:\BuildAgentWorkFolder\f00869677)
2017-10-17T13:48:52.5561597Z D:\BuildAgentWorkFolder\f00869677\Git\drop\publish_to_sharepoint.ps1 D:\Integration_20171017.2.zip Integration_20171017.2
2017-10-17T13:48:53.0241597Z Connecting to http://sharepoint_server/sites/TFS_DefaultCollection/NET as srv_promote...
2017-10-17T13:48:53.2737597Z ##[error]D:\BuildAgentWorkFolder\f00869677\Git\drop\publish_to_sharepoin
2017-10-17T13:48:53.2737597Z ##[error]t.ps1 : Cannot bind argument to parameter 'String' because it is null.
2017-10-17T13:48:53.2737597Z ##[error]At line:1 char:1
2017-10-17T13:48:53.2737597Z ##[error]+ .
2017-10-17T13:48:53.2737597Z ##[error]'D:\BuildAgentWorkFolder\f00869677\Git\drop\publish_to_sharepo
2017-10-17T13:48:53.2737597Z ##[error]...
2017-10-17T13:48:53.2737597Z ##[error]+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
2017-10-17T13:48:53.2737597Z ##[error]~~~
2017-10-17T13:48:53.2737597Z ##[error] + CategoryInfo : NotSpecified: (:) [Write-Error], WriteErrorExcep
2017-10-17T13:48:53.2737597Z ##[error] tion
2017-10-17T13:48:53.2737597Z ##[error] + FullyQualifiedErrorId : Microsoft.PowerShell.Commands.WriteErrorExceptio
2017-10-17T13:48:53.2737597Z ##[error] n,publish_to_sharepoint.ps1
2017-10-17T13:48:53.2737597Z ##[error]
2017-10-17T13:48:53.2737597Z ##[error]Process completed with exit code 0 and had 1 error(s) written to the error stream.
This is the issue: $Env:SharePointPassword. Secrets aren't stored as environment variables. Modify your script and pass in the password as a parameter.
I was testing out DSC with linux,
Here are the details of the linux server i am using
PS C:\Windows\system32> Get-CimInstance -CimSession $Session -namespace root/omi -ClassName omi_identify
InstanceID : 2FDB5542-5896-45D5-9BE9-DC04430AAABE
SystemName : CENTOSTESTDSC
ProductName : OMI
ProductVendor : Microsoft
ProductVersionMajor : 1
ProductVersionMinor : 0
ProductVersionRevision : 8
ProductVersionString : 1.0.8
Platform : LINUX_X86_64_GNU
OperatingSystem : LINUX
Architecture : X86_64
Compiler : GNU
ConfigPrefix : GNU
ConfigLibDir : /opt/omi-1.0.8/lib
ConfigBinDir : /opt/omi-1.0.8/bin
ConfigIncludeDir : /opt/omi-1.0.8/include
ConfigDataDir : /opt/omi-1.0.8/share
ConfigLocalStateDir : /opt/omi-1.0.8/var
ConfigSysConfDir : /opt/omi-1.0.8/etc
ConfigProviderDir : /opt/omi-1.0.8/etc
ConfigLogFile : /opt/omi-1.0.8/var/log/omiserver.log
ConfigPIDFile : /opt/omi-1.0.8/var/run/omiserver.pid
ConfigRegisterDir : /opt/omi-1.0.8/etc/omiregister
ConfigSchemaDir : /opt/omi-1.0.8/share/omischema
ConfigNameSpaces : {root-check, interop, root-omi, root-cimv2}
PSComputerName : 123.112.123.156
When i try to invoke a DSC configuration against the Linux VM i get an error as below.
I am using the latest PSDSC tar file from below location
wget https://github.com/Microsoft/PowerShell-DSC-for-Linux/releases/download/V1.1.0-466/PSDSC.tar.gz
Can some one help please.
I just migrated my Entity Framework from 5 to 6. Then when i tried to run Enable-Migrations command suddenly i got these errors:
Exception calling "LoadFrom" with "1" argument(s): "Could not load file or
assembly 'file:///D:\BitBucketGit\packages\EntityFramework.5.0.0\tools
\EntityFramework.PowerShell.Utility.dll' or one of its dependencies.
Operation is not supported.
(Exception from HRESULT: 0x80131515)" At D:\BitBucketGit\packages
\EntityFramework.6.1.3\tools\EntityFramework.psm1:780 char:5 +
$utilityAssembly = [System.Reflection.Assembly]::LoadFrom((Join-Path
$ToolsP ... +
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : FileLoadException
You cannot call a method on a null-valued expression.
At D:\BitBucketGit\packages\EntityFramework.6.1.3\tool
\EntityFramework.psm1:781 char:5
+ $dispatcher = $utilityAssembly.CreateInstance(
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [], RuntimeException
+ FullyQualifiedErrorId : InvokeMethodOnNull
Exception calling "CreateInstanceFrom" with "8" argument(s): "Could not
load file or assembly
'file:///D:\BitBucketGit\packages\EntityFramework.5.0.0\tools
\EntityFramework.PowerShell.dll' or one of its dependencies. Operation is
not supported. (Exception from HRESULT: 0x80131515)"
At D:\BitBucketGit\packages\EntityFramework.6.1.3\tools
\EntityFramework.psm1:809 char:5
+ $domain.CreateInstanceFrom(
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : FileLoadException
After googling,some suggested to imply a full trust on the package folder which i did. But the error remains.
Is there any other way i can make it fixed.
cheers,
John
Thank for any help. Actually i just found the answer by changing the devenv.exe.config files.
Since I pulled the project from a remote server, I solved this issue by removing all contents of packages folder except repositories.config file and restored all NuGet packages.
I am experiencing a problem similar to the one described here:
Import-AzurePublishSettingsFile throws CryptographicException
We are calling Powershell from IIS to programmatically deploy VMs. Part of this process involves loading new Publish Settings Files in for new customers. We are getting the following error when attempting to do so:
Import-AzurePublishSettingsFile : An internal error occurred.
At C:\WebApps\Provisioning\PowerShellScripts\vmDeploy.ps1:152 char:2
+ Import-AzurePublishSettingsFile ($outputDir + "\" + $azSettingsFile)
-ErrorActi ...
+
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : CloseError: (:)
[Import-AzurePublishSettingsFile], CryptographicException
+ FullyQualifiedErrorId :
Microsoft.WindowsAzure.Commands.Subscription.ImportAzurePublishSettingsCommand
I have a hunch this has something to do with the user space, as if I run exactly the same script from an interactive PS session, on the same server, it works fine.
Any ideas on how to troubleshoot this?
Edit: Stack trace from Powershell:
PSMessageDetails :
Exception : System.Security.Cryptography.CryptographicException: An internal error occurred.
at System.Security.Cryptography.CryptographicException.ThrowCryptographicException(Int32 hr)
at System.Security.Cryptography.X509Certificates.X509Utils._LoadCertFromBlob(Byte[] rawData, IntPtr password, UInt32 dwFlags, Boolean persistKeySet, SafeCertContextHandle& pCertCtx)
at System.Security.Cryptography.X509Certificates.X509Certificate.LoadCertificateFromBlob(Byte[] rawData, Object password, X509KeyStorageFlags keyStorageFlags)
at System.Security.Cryptography.X509Certificates.X509Certificate2..ctor(Byte[] rawData, String password)
at Microsoft.WindowsAzure.Commands.Utilities.Common.PublishSettingsImporter.PublishSubscriptionToAzureSubscription(PublishDataPublishProfile profile, PublishDataPublishProfileSubscription s) in c:\workspace\workspace\build-azure-sdk-tools-msi\WindowsAzurePowershell\src\Commands.Utilities\Common\PublishSettingsImporter.cs:line 56
at System.Linq.Enumerable.WhereSelectArrayIterator`2.MoveNext()
at System.Collections.Generic.List`1..ctor(IEnumerable`1 collection)
at System.Linq.Enumerable.ToList[TSource](IEnumerable`1 source)
at Microsoft.WindowsAzure.Commands.Utilities.Common.WindowsAzureProfile.ImportPublishSettings(String fileName) in c:\workspace\workspace\build-azure-sdk-tools-msi\WindowsAzurePowershell\src\Commands.Utilities\Common\WindowsAzureProfile.cs:line 293
at Microsoft.WindowsAzure.Commands.Subscription.ImportAzurePublishSettingsCommand.ImportFile(String fileName) in c:\workspace\workspace\build-azure-sdk-tools-msi\WindowsAzurePowershell\src\Commands\Subscription\ImportAzurePublishSettings.cs:line 95
at Microsoft.WindowsAzure.Commands.Subscription.ImportAzurePublishSettingsCommand.ExecuteCmdlet() in c:\workspace\workspace\build-azure-sdk-tools-msi\WindowsAzurePowershell\src\Commands\Subscription\ImportAzurePublishSettings.cs:line 46
at Microsoft.WindowsAzure.Commands.Utilities.Common.CmdletBase.ProcessRecord() in c:\workspace\workspace\build-azure-sdk-tools-msi\WindowsAzurePowershell\src\Commands.Utilities\Common\CmdletBase.cs:line 96
TargetObject :
CategoryInfo : CloseError: (:) [Import-AzurePublishSettingsFile],
CryptographicException
FullyQualifiedErrorId : Microsoft.WindowsAzure.Commands.Subscription.ImportAzurePublishSettingsCommand
ErrorDetails :
InvocationInfo : System.Management.Automation.InvocationInfo
ScriptStackTrace : at <ScriptBlock>, C:\WebApps\Provisioning\PowerShellScripts\vmDeploy.ps1: line 163
PipelineIterationInfo : {}
MyCommand : Import-AzurePublishSettingsFile
BoundParameters : {}
UnboundArguments : {}
ScriptLineNumber : 163
OffsetInLine : 2
HistoryId : 1
ScriptName : C:\WebApps\Provisioning\PowerShellScripts\vmDeploy.ps1
Line : Import-AzurePublishSettingsFile ($outputDir + "\" +
$azSettingsFile) -ErrorAction Stop
PositionMessage : At C:\WebApps\Provisioning\PowerShellScripts\vmDeploy.ps
1:163 char:2
+ Import-AzurePublishSettingsFile ($outputDir + "\"
+ $azSettingsFile) -ErrorActi ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
PSScriptRoot : C:\WebApps\Provisioning\PowerShellScripts
PSCommandPath : C:\WebApps\Provisioning\PowerShellScripts\vmDeploy.ps1
InvocationName : Import-AzurePublishSettingsFile
PipelineLength : 0
PipelinePosition : 0
ExpectingInput : False
CommandOrigin : Internal
DisplayScriptPosition :
00000000000000000000000000000000000000000000000000000000000000000000000000000000
Message : An internal error occurred.
Data : {}
InnerException :
TargetSite : Void ThrowCryptographicException(Int32)
StackTrace : at System.Security.Cryptography.CryptographicException.ThrowCryptographicException(Int32 hr)
at System.Security.Cryptography.X509Certificates.X509Utils._LoadCertFromBlob(Byte[] rawData, IntPtr password, UInt32 dwFlags, Boolean persistKeySet, SafeCertContextHandle&pCertCtx)
at System.Security.Cryptography.X509Certificates.X509Certificate.LoadCertificateFromBlob(Byte[] rawData, Object password, X509KeyStorageFlags keyStorageFlags)
at System.Security.Cryptography.X509Certificates.X509Certificate2..ctor(Byte[] rawData, String password)
at Microsoft.WindowsAzure.Commands.Utilities.Common.PublishSettingsImporter.PublishSubscriptionToAzureSubscription(PublishDataPublishProfile profile, PublishDataPublishProfileSubscription s) in c:\workspace\workspace\build-azure-sdk-tools-msi\WindowsAzurePowershell\src\Commands.Utilities\Common\PublishSettingsImporter.cs:line 56
at System.Linq.Enumerable.WhereSelectArrayIterator`2.MoveNext()
at System.Collections.Generic.List`1..ctor(IEnumerable`1collection)
at System.Linq.Enumerable.ToList[TSource](IEnumerable`1source)
at Microsoft.WindowsAzure.Commands.Utilities.Common.WindowsAzureProfile.ImportPublishSettings(String fileName) in c:\workspace\workspace\build-azure-sdk-tools-msi\WindowsAzurePowershell\src\Commands.Utilities\Common\WindowsAzureProfile.cs:line 293
at Microsoft.WindowsAzure.Commands.Subscription.ImportAzurePublishSettingsCommand.ImportFile(String fileName) in c:\workspace\workspace\build-azure-sdk-tools-msi\WindowsAzurePowershell\src\Commands\Subscription\ImportAzurePublishSettings.cs:line 95
at Microsoft.WindowsAzure.Commands.Subscription.ImportAzurePublishSettingsCommand.ExecuteCmdlet() in c:\workspace\workspace\build-azure-sdk-tools-msi\WindowsAzurePowershell\src\Commands\Subscription\ImportAzurePublishSettings.cs:line 46
at Microsoft.WindowsAzure.Commands.Utilities.Common.CmdletBase.ProcessRecord() in c:\workspace\workspace\build-azure-sdk-tools-msi\WindowsAzurePowershell\src\Commands.Utilities\Common\CmdletBase.cs:line 96
HelpLink :
Source : mscorlib
HResult : -2146893792
Answer:
We changed the user context of the IIS app pool to a local administrator, and this resolved the issue. This suggests that the problem was access to the cryptographic store from the previous context. However the error and stack trace are too vague to confirm this hypothesis.
Using the WAML libraries for Compute, I'm able to deploy - however, I have to use slightly different credential loading:
X509Certificate2 certificate = new X509Certificate2(
Convert.FromBase64String(encodedCertificate),
"MyPrivateKey",
X509KeyStorageFlags.MachineKeySet);
Essentially I need to tell the system to load from the machine key set (even though my cert is local), and then the CryptographicException goes away.
I'm guessing this may be somewhat similar - even though you are using PowerShell, it is built on top of the WAML preview.
We had our build agent running on an Azure VM, it had been working fine but suddenly stopped working one day, apparently without any reason with the above error.
Logging on to the VM and running Import-AzurePublishSettingsFile "FileName" manually would run perfectly.
We found that our build agent was setup incorrectly and running under a user account who's MSDN credentials had changed.
We solved the problem firstly by restarting the VM - this will kill any Build Agent Processes running under other user accounts (in our case there was one and it was stopping us from running the next step below)
Next, it's best if you install the build agent as a service by running the script (as an administrator)
<agent home>/bin/service.install.bat file
You can check that the service is install by checking in Computer Management -> Services dialog that a Service called "Team City Agent" (or something similar is running), assuming everything else is setup ok your builds should start working (or at least get past the cryptographic error above :) )
More info can be found here: https://confluence.jetbrains.com/display/TCD8/Setting+up+and+Running+Additional+Build+Agents