/// <summary> /// Converts a <see cref="Resource{JToken}"/> object into a <see cref="PSObject"/> object. /// </summary> /// <param name="resource">The <see cref="Resource{JToken}"/> object.</param> internal static PSObject ToPsObject(this Resource <JToken> resource) { var resourceType = ResourceIdUtility.GetResourceType(resource.Id); var extensionResourceType = ResourceIdUtility.GetExtensionResourceType(resource.Id); var objectDefinition = new Dictionary <string, object> { { "Name", resource.Name }, { "ResourceId", resource.Id }, { "ResourceName", ResourceIdUtility.GetResourceName(resource.Id) }, { "ResourceType", resourceType }, { "ExtensionResourceName", ResourceIdUtility.GetExtensionResourceName(resource.Id) }, { "ExtensionResourceType", extensionResourceType }, { "Kind", resource.Kind }, { "ResourceGroupName", ResourceIdUtility.GetResourceGroup(resource.Id) }, { "Location", resource.Location }, { "SubscriptionId", ResourceIdUtility.GetSubscriptionId(resource.Id) }, { "Tags", TagsHelper.GetTagsHashtables(resource.Tags) }, { "Plan", resource.Plan.ToJToken().ToPsObject() }, { "Properties", resource.Properties.ToPsObject() }, { "PropertiesText", resource.Properties == null ? null : resource.Properties.ToString() }, { "CreatedTime", resource.CreatedTime }, { "ChangedTime", resource.ChangedTime }, { "ETag", resource.ETag }, }; return(PowerShellUtilities.ConstructPSObject( (resourceType + extensionResourceType).Replace('/', '.'), objectDefinition.Where(kvp => kvp.Value != null).SelectManyArray(kvp => new[] { kvp.Key, kvp.Value }))); }
/// <summary> /// Resolve given input parameters into JSON parameter object for put /// </summary> /// <param name="policyParameter"></param> /// <param name="policyParameterObject"></param> /// <returns></returns> protected JObject GetParameters(string policyParameter, Hashtable policyParameterObject) { // Load parameters from local file or literal if (policyParameter != null) { string policyParameterFilePath = this.TryResolvePath(policyParameter); return(FileUtilities.DataStore.FileExists(policyParameterFilePath) ? JObject.Parse(FileUtilities.DataStore.ReadFileAsText(policyParameterFilePath)) : JObject.Parse(policyParameter)); } // Load from PS object if (policyParameterObject != null) { return(policyParameterObject.ToJObjectWithValue()); } // Load dynamic parameters var parameters = PowerShellUtilities.GetUsedDynamicParameters(AsJobDynamicParameters, MyInvocation); if (parameters.Count() > 0) { return(MyInvocation.BoundParameters.ToJObjectWithValue(parameters.Select(p => p.Name))); } return(null); }
public void RemovesModulePathFromUserPSModulePath() { string originalPSModulePath = Environment.GetEnvironmentVariable(PowerShellUtilities.PSModulePathName); string[] modulePaths = originalPSModulePath.Split(';'); string modulePath = modulePaths[modulePaths.Length - 1]; string expected = null; string actual; try { if (modulePaths.Length > 1) { expected = string.Join(";", modulePaths, 0, modulePaths.Length - 1); } PowerShellUtilities.RemoveModuleFromPSModulePath(modulePath); actual = Environment.GetEnvironmentVariable(PowerShellUtilities.PSModulePathName); Assert.Equal(expected, actual); } finally { Environment.SetEnvironmentVariable(PowerShellUtilities.PSModulePathName, originalPSModulePath); } Assert.Equal(expected, actual); }
protected Hashtable GetTemplateParameterObject(Hashtable templateParameterObject) { // NOTE(jogao): create a new Hashtable so that user can re-use the templateParameterObject. var prameterObject = new Hashtable(); if (templateParameterObject != null) { foreach (var parameterKey in templateParameterObject.Keys) { // Let default behavior of a value parameter if not a KeyVault reference Hashtable var hashtableParameter = templateParameterObject[parameterKey] as Hashtable; if (hashtableParameter != null && hashtableParameter.ContainsKey("reference")) { prameterObject[parameterKey] = templateParameterObject[parameterKey]; } else { prameterObject[parameterKey] = new Hashtable { { "value", templateParameterObject[parameterKey] } }; } } } // Load parameters from the file string templateParameterFilePath = this.ResolvePath(TemplateParameterFile); if (templateParameterFilePath != null && FileUtilities.DataStore.FileExists(templateParameterFilePath)) { var parametersFromFile = TemplateUtility.ParseTemplateParameterFileContents(templateParameterFilePath); parametersFromFile.ForEach(dp => { var parameter = new Hashtable(); if (dp.Value.Value != null) { parameter.Add("value", dp.Value.Value); } if (dp.Value.Reference != null) { parameter.Add("reference", dp.Value.Reference); } prameterObject[dp.Key] = parameter; }); } // Load dynamic parameters IEnumerable <RuntimeDefinedParameter> parameters = PowerShellUtilities.GetUsedDynamicParameters(this.AsJobDynamicParameters, MyInvocation); if (parameters.Any()) { parameters.ForEach(dp => prameterObject[((ParameterAttribute)dp.Attributes[0]).HelpMessage] = new Hashtable { { "value", dp.Value } }); } return(prameterObject); }
/// <summary> /// Executes the cmdlet. /// </summary> protected override void OnProcessRecord() { base.OnProcessRecord(); var resourceId = this.GetResourceId(); var apiVersion = this.DetermineApiVersion(resourceId: resourceId).Result; var parameters = new ExportTemplateParameters { Resources = new string [] { "*" }, Options = this.GetExportOptions() ?? null }; var operationResult = this.GetResourcesClient() .InvokeActionOnResource <JObject>( resourceId: resourceId, action: Constants.ExportTemplate, parameters: parameters.ToJToken(), apiVersion: apiVersion, cancellationToken: this.CancellationToken.Value) .Result; var managementUri = this.GetResourcesClient() .GetResourceManagementRequestUri( resourceId: resourceId, apiVersion: apiVersion, action: Constants.ExportTemplate); var activity = string.Format("POST {0}", managementUri.PathAndQuery); var resultString = this.GetLongRunningOperationTracker(activityName: activity, isResourceCreateOrUpdate: false) .WaitOnOperation(operationResult: operationResult); var template = JToken.FromObject(JObject.Parse(resultString)["template"]); if (JObject.Parse(resultString)["error"] != null) { ExtendedErrorInfo error; if (JObject.Parse(resultString)["error"].TryConvertTo(out error)) { WriteWarning(string.Format("{0} : {1}", error.Code, error.Message)); foreach (var detail in error.Details) { WriteWarning(string.Format("{0} : {1}", detail.Code, detail.Message)); } } } string path = FileUtility.SaveTemplateFile( templateName: this.ResourceGroupName, contents: template.ToString(), outputPath: string.IsNullOrEmpty(this.Path) ? System.IO.Path.Combine(CurrentPath(), this.ResourceGroupName) : this.TryResolvePath(this.Path), overwrite: this.Force, confirmAction: ConfirmAction); WriteObject(PowerShellUtilities.ConstructPSObject(null, "Path", path)); }
public static PSObject GetNamespacePSObject(ExtendedAuthorizationRule rule) { return(null == rule? null : PowerShellUtilities.ConstructPSObject( typeof(ExtendedAuthorizationRule).FullName, "Namespace", rule.Namespace, "Name", rule.Name, "ConnectionString", rule.ConnectionString, "Permission", rule.Permission, "Rule", rule.Rule)); }
public override void ExecuteCmdlet() { string path = GalleryTemplatesClient.DownloadGalleryTemplateFile( Identity, string.IsNullOrEmpty(Path) ? System.IO.Path.Combine(CurrentPath(), Identity) : this.TryResolvePath(Path), Force, ConfirmAction); WriteObject(PowerShellUtilities.ConstructPSObject(null, "Path", path)); }
public override void ExecuteCmdlet() { WriteWarning("This cmdlet is being deprecated and will be removed in a future release."); string path = GalleryTemplatesClient.DownloadGalleryTemplateFile( Identity, string.IsNullOrEmpty(Path) ? System.IO.Path.Combine(CurrentPath(), Identity) : this.TryResolvePath(Path), Force, ConfirmAction); WriteObject(PowerShellUtilities.ConstructPSObject(null, "Path", path)); }
public override void ExecuteCmdlet() { try { ResourceIdentifier resourceIdentifier = (ResourceId != null) ? new ResourceIdentifier(ResourceId) : null; ResourceGroupName = ResourceGroupName ?? resourceIdentifier.ResourceGroupName; Name = Name ?? ResourceIdUtility.GetResourceName(ResourceId); // Get the template spec version model from the SDK: TemplateSpecVersion specificVersion = TemplateSpecsSdkClient.TemplateSpecsClient.TemplateSpecVersions.Get( ResourceGroupName, Name, Version ); // Get the parent template spec from the SDK. We do this because we want to retrieve the // template spec name with its proper casing for naming our main template output file (the // Name parameter may have mismatched casing): TemplateSpec parentTemplateSpec = TemplateSpecsSdkClient.TemplateSpecsClient.TemplateSpecs.Get(ResourceGroupName, Name); PackagedTemplate packagedTemplate = new PackagedTemplate(specificVersion); // TODO: Handle overwriting prompts... // Ensure our output path is resolved based on the current powershell working // directory instead of the current process directory: OutputFolder = ResolveUserPath(OutputFolder); string mainTemplateFileName = $"{parentTemplateSpec.Name}.{specificVersion.Name}.json"; string uiFormDefinitionFileName = $"{parentTemplateSpec.Name}.{specificVersion.Name}.uiformdefinition.json"; string fullRootTemplateFilePath = Path.GetFullPath( Path.Combine(OutputFolder, mainTemplateFileName) ); if (ShouldProcess(specificVersion.Id, $"Export to '{fullRootTemplateFilePath}'")) { TemplateSpecPackagingEngine.Unpack( packagedTemplate, OutputFolder, mainTemplateFileName, uiFormDefinitionFileName); } WriteObject(PowerShellUtilities.ConstructPSObject(null, "Path", fullRootTemplateFilePath)); } catch (Exception ex) { WriteExceptionError(ex); } }
private void ImportAzureModule(string name, string path) { WriteVerbose(string.Format("Importing {0} module...", name)); this.ImportModule(Path.Combine(path, name + ".psd1")); WriteVerbose(string.Format("Adding {0} module path to PSModulePath...", path)); PowerShellUtilities.AddModuleToPSModulePath(path); if (Global) { PowerShellUtilities.AddModuleToPSModulePath(path, EnvironmentVariableTarget.Machine); } }
private void RemoveAzureModule(string name, string path) { WriteVerbose(string.Format("Removing {0} module...", name)); this.RemoveModule(name); WriteVerbose(string.Format("Removing {0} module path from PSModulePath...", path)); PowerShellUtilities.RemoveModuleFromPSModulePath(path); if (Global) { PowerShellUtilities.RemoveModuleFromPSModulePath(path, EnvironmentVariableTarget.Machine); } }
public void AddsModulePathToUserPSModulePath() { string originalPSModulePath = Environment.GetEnvironmentVariable(PowerShellUtilities.PSModulePathName); try { string modulePath = "C:\\ExampleTest\\MyModule.psd1"; string expected = originalPSModulePath + ";" + modulePath; PowerShellUtilities.AddModuleToPSModulePath(modulePath); string actual = Environment.GetEnvironmentVariable(PowerShellUtilities.PSModulePathName); Assert.Equal(expected, actual); } finally { Environment.SetEnvironmentVariable(PowerShellUtilities.PSModulePathName, originalPSModulePath); } }
/// <summary> /// Converts a <see cref="Resource{JToken}"/> object into a <see cref="PSObject"/> object. /// </summary> /// <param name="resource">The <see cref="Resource{JToken}"/> object.</param> internal static PSObject ToPsObject(this Resource <JToken> resource) { var resourceType = string.IsNullOrEmpty(resource.Id) ? null : ResourceIdUtility.GetResourceType(resource.Id); var extensionResourceType = string.IsNullOrEmpty(resource.Id) ? null : ResourceIdUtility.GetExtensionResourceType(resource.Id); var objectDefinition = new Dictionary <string, object> { { "Name", resource.Name }, { "ResourceId", string.IsNullOrEmpty(resource.Id) ? null : resource.Id }, { "ResourceName", string.IsNullOrEmpty(resource.Id) ? null : ResourceIdUtility.GetResourceName(resource.Id) }, { "ResourceType", resourceType }, { "ExtensionResourceName", string.IsNullOrEmpty(resource.Id) ? null : ResourceIdUtility.GetExtensionResourceName(resource.Id) }, { "ExtensionResourceType", extensionResourceType }, { "Kind", resource.Kind }, { "ResourceGroupName", string.IsNullOrEmpty(resource.Id) ? null : ResourceIdUtility.GetResourceGroupName(resource.Id) }, { "Location", resource.Location }, { "SubscriptionId", string.IsNullOrEmpty(resource.Id) ? null : ResourceIdUtility.GetSubscriptionId(resource.Id) }, { "Tags", TagsHelper.GetTagsHashtable(resource.Tags) }, { "Plan", resource.Plan.ToJToken().ToPsObject() }, { "Properties", ResourceExtensions.GetProperties(resource) }, { "CreatedTime", resource.CreatedTime }, { "ChangedTime", resource.ChangedTime }, { "ETag", resource.ETag }, { "Sku", resource.Sku.ToJToken().ToPsObject() }, { "Zones", resource.Zones }, }; var resourceTypeName = resourceType == null && extensionResourceType == null ? null : (resourceType + extensionResourceType).Replace('/', '.'); var psObject = PowerShellUtilities.ConstructPSObject( resourceTypeName, objectDefinition.Where(kvp => kvp.Value != null).SelectManyArray(kvp => new[] { kvp.Key, kvp.Value })); psObject.TypeNames.Add(Constants.MicrosoftAzureResource); return(psObject); }
/// <summary> /// Executes the cmdlet. /// </summary> protected override void OnProcessRecord() { base.OnProcessRecord(); if (ShouldProcess(DeploymentName, VerbsData.Save)) { var resourceId = this.GetResourceId(); var apiVersion = this.DetermineApiVersion(resourceId: resourceId).Result; var operationResult = this.GetResourcesClient() .InvokeActionOnResource <JObject>( resourceId: resourceId, action: Constants.ExportTemplate, apiVersion: apiVersion, cancellationToken: this.CancellationToken.Value) .Result; var managementUri = this.GetResourcesClient() .GetResourceManagementRequestUri( resourceId: resourceId, apiVersion: apiVersion, action: Constants.ExportTemplate); var activity = string.Format("POST {0}", managementUri.PathAndQuery); var resultString = this.GetLongRunningOperationTracker(activityName: activity, isResourceCreateOrUpdate: false) .WaitOnOperation(operationResult: operationResult); var template = JToken.FromObject(JObject.Parse(resultString)["template"]); string path = FileUtility.SaveTemplateFile( templateName: this.DeploymentName, contents: template.ToString(), outputPath: string.IsNullOrEmpty(this.Path) ? System.IO.Path.Combine(CurrentPath(), this.DeploymentName) : this.TryResolvePath(this.Path), overwrite: this.Force, shouldContinue: ShouldContinue); WriteObject(PowerShellUtilities.ConstructPSObject(null, "Path", path)); } }
/// <summary> /// Executes the cmdlet. /// </summary> protected override void OnProcessRecord() { base.OnProcessRecord(); if (ShouldProcess(DeploymentName, VerbsData.Save)) { var template = ResourceManagerSdkClient.GetDeploymentTemplateAtResourceGroup(ResourceGroupName, DeploymentName); string path = FileUtility.SaveTemplateFile( templateName: this.DeploymentName, contents: template.ToString(), outputPath: string.IsNullOrEmpty(this.Path) ? System.IO.Path.Combine(CurrentPath(), this.DeploymentName) : this.TryResolvePath(this.Path), overwrite: this.Force, shouldContinue: ShouldContinue); WriteObject(PowerShellUtilities.ConstructPSObject(null, "Path", path)); } }
internal static PSObject ConstructPolicyOutputPSObject <T>(IDictionary <string, T> sharedAccessPolicies, string policyName) { if (!(typeof(T) == typeof(SharedAccessTablePolicy) || typeof(T) == typeof(SharedAccessBlobPolicy) || (typeof(T) == typeof(SharedAccessQueuePolicy)))) { throw new ArgumentException(Resources.InvalidAccessPolicyType); } return(PowerShellUtilities.ConstructPSObject( typeof(PSObject).FullName, "Policy", policyName, "Permissions", (sharedAccessPolicies[policyName]).GetType().GetProperty("Permissions").GetValue(sharedAccessPolicies[policyName]), "StartTime", (sharedAccessPolicies[policyName]).GetType().GetProperty("SharedAccessStartTime").GetValue(sharedAccessPolicies[policyName]), "ExpiryTime", (sharedAccessPolicies[policyName]).GetType().GetProperty("SharedAccessExpiryTime").GetValue(sharedAccessPolicies[policyName]))); }
private void RemoveAzureModule(string name, string path) { if (IsLoaded(name)) { WriteVerbose(string.Format("Removing {0} module...", name)); this.RemoveModule(name); if (name.Equals(FileUtilities.GetModuleName(AzureModule.AzureServiceManagement))) { this.RemoveAzureAliases(); } WriteVerbose(string.Format("Removing {0} module path from PSModulePath...", path)); PowerShellUtilities.RemoveModuleFromPSModulePath(path); if (Global) { PowerShellUtilities.RemoveModuleFromPSModulePath(path, EnvironmentVariableTarget.Machine); } } }
internal static PSObject ConstructPolicyOutputPSObject <T>(T identifier) { if (!(typeof(T) == typeof(BlobSignedIdentifier) || typeof(T) == typeof(ShareSignedIdentifier) || (typeof(T) == typeof(QueueSignedIdentifier)))) { throw new ArgumentException("Access policy type is invalid, only BlobSignedIdentifier, ShareSignedIdentifier, and QueueSignedIdentifier are supported."); } var accessPolicy = (identifier).GetType().GetProperty("AccessPolicy").GetValue(identifier); return(PowerShellUtilities.ConstructPSObject( typeof(PSObject).FullName, "Policy", (identifier).GetType().GetProperty("Id").GetValue(identifier), "Permissions", (accessPolicy).GetType().GetProperty("Permissions").GetValue(accessPolicy) is null ? null: (accessPolicy).GetType().GetProperty("Permissions").GetValue(accessPolicy).ToString(), "StartTime", (accessPolicy).GetType().GetProperty("PolicyStartsOn").GetValue(accessPolicy), "ExpiryTime", (accessPolicy).GetType().GetProperty("PolicyExpiresOn").GetValue(accessPolicy))); }
protected Hashtable GetTemplateParameterObject(Hashtable templateParameterObject) { // NOTE(jogao): create a new Hashtable so that user can re-use the templateParameterObject. var prameterObject = new Hashtable(); if (templateParameterObject != null) { foreach (var parameterKey in templateParameterObject.Keys) { prameterObject[parameterKey] = new Hashtable { { "value", templateParameterObject[parameterKey] } }; } } // Load parameters from the file string templateParameterFilePath = this.TryResolvePath(TemplateParameterFile); if (templateParameterFilePath != null && FileUtilities.DataStore.FileExists(templateParameterFilePath)) { var parametersFromFile = GalleryTemplatesClient.ParseTemplateParameterFileContents(templateParameterFilePath); parametersFromFile.ForEach(dp => prameterObject[dp.Key] = new Hashtable { { "value", dp.Value.Value }, { "reference", dp.Value.Reference } }); } // Load dynamic parameters IEnumerable <RuntimeDefinedParameter> parameters = PowerShellUtilities.GetUsedDynamicParameters(dynamicParameters, MyInvocation); if (parameters.Any()) { parameters.ForEach(dp => prameterObject[((ParameterAttribute)dp.Attributes[0]).HelpMessage] = new Hashtable { { "value", dp.Value } }); } return(prameterObject); }
protected Hashtable GetTemplateParameterObject(Hashtable templateParameterObject) { templateParameterObject = templateParameterObject ?? new Hashtable(); // Load parameters from the file string templateParameterFilePath = this.TryResolvePath(TemplateParameterFile); if (templateParameterFilePath != null && File.Exists(templateParameterFilePath)) { var parametersFromFile = JsonConvert.DeserializeObject <Dictionary <string, TemplateFileParameter> >(File.ReadAllText(templateParameterFilePath)); parametersFromFile.ForEach(dp => templateParameterObject[dp.Key] = dp.Value.Value); } // Load dynamic parameters IEnumerable <RuntimeDefinedParameter> parameters = PowerShellUtilities.GetUsedDynamicParameters(dynamicParameters, MyInvocation); if (parameters.Any()) { parameters.ForEach(dp => templateParameterObject[((ParameterAttribute)dp.Attributes[0]).HelpMessage] = dp.Value); } return(templateParameterObject); }
protected Hashtable GetTemplateParameterObject(Hashtable templateParameterObject) { templateParameterObject = templateParameterObject ?? new Hashtable(); // Load parameters from the file string templateParameterFilePath = this.TryResolvePath(TemplateParameterFile); if (templateParameterFilePath != null && FileUtilities.DataStore.FileExists(templateParameterFilePath)) { var parametersFromFile = GalleryTemplatesClient.ParseTemplateParameterFileContents(templateParameterFilePath); parametersFromFile.ForEach(dp => templateParameterObject[dp.Key] = dp.Value.Value); } // Load dynamic parameters IEnumerable <RuntimeDefinedParameter> parameters = PowerShellUtilities.GetUsedDynamicParameters(dynamicParameters, MyInvocation); if (parameters.Any()) { parameters.ForEach(dp => templateParameterObject[((ParameterAttribute)dp.Attributes[0]).HelpMessage] = dp.Value); } return(templateParameterObject); }
/// <summary> /// Executes the cmdlet. /// </summary> protected override void OnProcessRecord() { base.OnProcessRecord(); string contents; if (ShouldProcess(ResourceGroupName, VerbsData.Export)) { var resourceGroupId = this.GetResourceGroupId(); if (this.IsParameterBound(c => c.ApiVersion)) { var parameters = new Management.ResourceManager.Models.ExportTemplateRequest { Resources = this.GetResourcesFilter(resourceGroupId: resourceGroupId), Options = this.GetExportOptions(), }; var exportedTemplate = ResourceManagerSdkClient.ExportResourceGroup(ResourceGroupName, parameters); var template = exportedTemplate.Template; contents = template.ToString(); var error = exportedTemplate.Error; if (error != null) { WriteWarning(string.Format("{0} : {1}", error.Code, error.Message)); foreach (var detail in error.Details) { WriteWarning(string.Format("{0} : {1}", detail.Code, detail.Message)); } } } else { var parameters = new ExportTemplateParameters { Resources = this.GetResourcesFilter(resourceGroupId: resourceGroupId), Options = this.GetExportOptions(), }; var apiVersion = this.ApiVersion ?? DefaultApiVersion; var operationResult = this.GetResourcesClient() .InvokeActionOnResource <JObject>( resourceId: resourceGroupId, action: Constants.ExportTemplate, parameters: parameters.ToJToken(), apiVersion: apiVersion, cancellationToken: this.CancellationToken.Value) .Result; var managementUri = this.GetResourcesClient() .GetResourceManagementRequestUri( resourceId: resourceGroupId, apiVersion: apiVersion, action: Constants.ExportTemplate); var activity = string.Format("POST {0}", managementUri.PathAndQuery); var resultString = this.GetLongRunningOperationTracker(activityName: activity, isResourceCreateOrUpdate: false) .WaitOnOperation(operationResult: operationResult); var template = JToken.FromObject(JObject.Parse(resultString)["template"]); contents = template.ToString(); if (JObject.Parse(resultString)["error"] != null) { if (JObject.Parse(resultString)["error"].TryConvertTo(out ExtendedErrorInfo error)) { WriteWarning(string.Format("{0} : {1}", error.Code, error.Message)); foreach (var detail in error.Details) { WriteWarning(string.Format("{0} : {1}", detail.Code, detail.Message)); } } } } string path = FileUtility.SaveTemplateFile( templateName: this.ResourceGroupName, contents: contents, outputPath: string.IsNullOrEmpty(this.Path) ? System.IO.Path.Combine(CurrentPath(), this.ResourceGroupName) : this.TryResolvePath(this.Path), overwrite: Force.IsPresent, shouldContinue: ShouldContinue); WriteObject(PowerShellUtilities.ConstructPSObject(null, "Path", path)); } }