/// <summary> /// Writes the PSGetResourceInfo properties to the specified file path as a /// PowerShell serialized xml file, maintaining compatibility with /// PowerShellGet v2 file format. /// </summary> public bool TryWrite( string filePath, out string errorMsg) { errorMsg = string.Empty; if (string.IsNullOrWhiteSpace(filePath)) { errorMsg = "TryWritePSGetInfo: Invalid file path. Filepath cannot be empty or whitespace."; return(false); } try { var infoXml = PSSerializer.Serialize( source: ConvertToCustomObject(), depth: 5); System.IO.File.WriteAllText( path: filePath, contents: infoXml); return(true); } catch (Exception ex) { errorMsg = string.Format( CultureInfo.InvariantCulture, @"TryWritePSGetInfo: Cannot convert and write the PowerShellGet information to file, with error: {0}", ex.Message); return(false); } }
internal static void ProcessCliXmlTestabilityHook(PSStreamObject streamObject) { if (!s_isCliXmlTestabilityHookActive) { return; } if (streamObject.ObjectType != PSStreamObjectType.Output) { return; } if (streamObject.Value == null) { return; } if (!(PSObject.AsPSObject(streamObject.Value).BaseObject.GetType().Name.Equals("CimInstance"))) { return; } string serializedForm = PSSerializer.Serialize(streamObject.Value, depth: 1); object deserializedObject = PSSerializer.Deserialize(serializedForm); streamObject.Value = PSObject.AsPSObject(deserializedObject).BaseObject; }
object DoPSPassThroughConversion <T>(T objectToConvert) { string content = PSSerializer.Serialize(objectToConvert, 10); var reconstituted = PSSerializer.Deserialize(content); var converter = new AzureContextConverter(); Assert.True(converter.CanConvertFrom(reconstituted, typeof(IAzureContextContainer))); return(converter.ConvertFrom(reconstituted, typeof(IAzureContextContainer), CultureInfo.InvariantCulture, true)); }
/// <summary> /// Converts an object into compressed bytes /// </summary> /// <param name="Item">The arbitrary object to serialize</param> /// <param name="Depth">The depth to which to serialize</param> /// <returns>A compressed byte array containing the serialized inputobject</returns> public static byte[] ToByteCompressed(object Item, int Depth) { byte[] bytes = Encoding.UTF8.GetBytes(PSSerializer.Serialize(Item, Depth)); MemoryStream outputStream = new MemoryStream(); GZipStream gZipStream = new GZipStream(outputStream, CompressionMode.Compress); gZipStream.Write(bytes, 0, bytes.Length); gZipStream.Close(); outputStream.Close(); return(outputStream.ToArray()); }
protected override void ProcessRecord() { PwshCode pwsh = new PwshCode(); string ObjectType = InputObject.ImmediateBaseObject.GetType().FullName; string Input; switch (ObjectType) { case "System.String": Input = InputObject.ToString() + "##IsString##"; break; default: Input = PSSerializer.Serialize(InputObject); break; } Prefix = Prefix == "None" ? "" : Prefix; string pwshCode = String.IsNullOrEmpty(Secret) ? pwsh.GetPwshCode(Input, Prefix) : pwsh.GetPwshCode(Input, Secret, Prefix); WriteObject(pwshCode); }
private IObservable <Collection <PSObject> > Start(object o, IObservable <int> retrySignal) { return(Observable.Defer(() => Observable.Start(() => { using (var runspace = RunspaceFactory.CreateRunspace()){ runspace.Open(); runspace.SetVariable(new PSVariable("_", o)); runspace.SetVariable(_psVariables); var psObjects = runspace.Invoke($"[CmdletBinding()]\r\nParam()\r\n{Script}").Cast <PSObject>(); var lastExitCode = runspace.Invoke($"$LastExitCode").Any(_ => _?.BaseObject is int code && code > 0); var errors = runspace.Invoke("$Error").Where(_ => _?.BaseObject is ErrorRecord) .GroupBy(exception => ((ErrorRecord)exception.BaseObject).Exception.Message) .SelectMany(objects => objects); var collection = new Collection <PSObject>(); foreach (var psObject in psObjects.Concat(errors)) { if (lastExitCode) { var targetObject = PSSerializer.Serialize(psObject, 3); collection.Add(PSObject.AsPSObject(new ErrorRecord(new Exception(psObject.ToString()), ErrorCategory.FromStdErr.ToString(), ErrorCategory.FromStdErr, targetObject))); } else { collection.Add(psObject); } } return Observable.Return(collection); } }).Merge() .RetryWhen(_ => _.SelectMany(exception => { return retrySignal .Select(i => i) .Concat(Observable.Throw <int>(exception)); })) ) ); }
/// <summary> /// Converts any object into its persisted state. /// </summary> /// <param name="Item">The item to convert.</param> /// <returns>Its persisted state representation.</returns> public static ConfigurationValue ConvertToPersistedValue(object Item) { if (Item == null) { return(new ConfigurationValue("null", ConfigurationValueType.Null)); } switch (Item.GetType().FullName) { case "System.Boolean": if ((bool)Item) { return(new ConfigurationValue("true", ConfigurationValueType.Bool)); } return(new ConfigurationValue("false", ConfigurationValueType.Bool)); case "System.Int16": return(new ConfigurationValue(Item.ToString(), ConfigurationValueType.Int)); case "System.Int32": return(new ConfigurationValue(Item.ToString(), ConfigurationValueType.Int)); case "System.Int64": return(new ConfigurationValue(Item.ToString(), ConfigurationValueType.Long)); case "System.UInt16": return(new ConfigurationValue(Item.ToString(), ConfigurationValueType.Int)); case "System.UInt32": return(new ConfigurationValue(Item.ToString(), ConfigurationValueType.Long)); case "System.UInt64": return(new ConfigurationValue(Item.ToString(), ConfigurationValueType.Long)); case "System.Double": return(new ConfigurationValue(String.Format(System.Globalization.CultureInfo.InvariantCulture, "{0}", Item), ConfigurationValueType.Double)); case "System.String": return(new ConfigurationValue(Item.ToString(), ConfigurationValueType.String)); case "System.TimeSpan": return(new ConfigurationValue(((TimeSpan)Item).Ticks.ToString(), ConfigurationValueType.Timespan)); case "System.DateTime": return(new ConfigurationValue(((DateTime)Item).Ticks.ToString(), ConfigurationValueType.Datetime)); case "System.ConsoleColor": return(new ConfigurationValue(Item.ToString(), ConfigurationValueType.ConsoleColor)); case "System.Collections.Hashtable": List <string> hashItems = new List <string>(); Hashtable tempTable = Item as Hashtable; foreach (object key in tempTable.Keys) { hashItems.Add(String.Format("{0}þEþ{1}", Utf8ToBase64(key.ToString()), Utf8ToBase64(ConvertToPersistedValue(tempTable[key]).TypeQualifiedPersistedValue))); } return(new ConfigurationValue(String.Join("þHþ", hashItems), ConfigurationValueType.Hashtable)); case "System.Object[]": List <string> items = new List <string>(); foreach (object item in (object[])Item) { ConfigurationValue temp = ConvertToPersistedValue(item); if (temp.PersistedValue == "<type not supported>") { return(temp); } items.Add(String.Format("{0}:{1}", temp.PersistedType, temp.PersistedValue)); } return(new ConfigurationValue(String.Join("þþþ", items), ConfigurationValueType.Array)); default: return(new ConfigurationValue(Utility.UtilityHost.CompressString((PSSerializer.Serialize(Item))), ConfigurationValueType.Object)); } }
public List <string> InstallHelper(string repositoryUrl, List <string> pkgsLeftToInstall, CancellationToken cancellationToken) { PackageSource source = new PackageSource(repositoryUrl); if (_credential != null) { string password = new NetworkCredential(string.Empty, _credential.Password).Password; source.Credentials = PackageSourceCredential.FromUserInput(repositoryUrl, _credential.UserName, password, true, null); } var provider = FactoryExtensionsV3.GetCoreV3(NuGet.Protocol.Core.Types.Repository.Provider); SourceRepository repository = new SourceRepository(source, provider); SearchFilter filter = new SearchFilter(_prerelease); ////////////////////// packages from source /// PackageSource source2 = new PackageSource(repositoryUrl); if (_credential != null) { string password = new NetworkCredential(string.Empty, _credential.Password).Password; source2.Credentials = PackageSourceCredential.FromUserInput(repositoryUrl, _credential.UserName, password, true, null); } var provider2 = FactoryExtensionsV3.GetCoreV3(NuGet.Protocol.Core.Types.Repository.Provider); SourceRepository repository2 = new SourceRepository(source2, provider2); // TODO: proper error handling here PackageMetadataResource resourceMetadata2 = null; try { resourceMetadata2 = repository.GetResourceAsync <PackageMetadataResource>().GetAwaiter().GetResult(); } catch { } SearchFilter filter2 = new SearchFilter(_prerelease); SourceCacheContext context2 = new SourceCacheContext(); foreach (var n in _name) { IPackageSearchMetadata filteredFoundPkgs = null; // Check version first to narrow down the number of pkgs before potential searching through tags VersionRange versionRange = null; if (_version == null) { // ensure that the latst version is returned first (the ordering of versions differ // TODO: proper error handling try { filteredFoundPkgs = (resourceMetadata2.GetMetadataAsync(n, _prerelease, false, context2, NullLogger.Instance, cancellationToken).GetAwaiter().GetResult() .OrderByDescending(p => p.Identity.Version, VersionComparer.VersionRelease) .FirstOrDefault()); } catch { } } else { // check if exact version NuGetVersion nugetVersion; //VersionRange versionRange = VersionRange.Parse(version); NuGetVersion.TryParse(_version, out nugetVersion); // throw if (nugetVersion != null) { // exact version versionRange = new VersionRange(nugetVersion, true, nugetVersion, true, null, null); } else { // check if version range versionRange = VersionRange.Parse(_version); } // Search for packages within a version range // ensure that the latst version is returned first (the ordering of versions differ filteredFoundPkgs = (resourceMetadata2.GetMetadataAsync(n, _prerelease, false, context2, NullLogger.Instance, cancellationToken).GetAwaiter().GetResult() .Where(p => versionRange.Satisfies(p.Identity.Version)) .OrderByDescending(p => p.Identity.Version, VersionComparer.VersionRelease) .FirstOrDefault()); } List <IPackageSearchMetadata> foundDependencies = new List <IPackageSearchMetadata>(); // found a package to install and looking for dependencies // Search for dependencies if (filteredFoundPkgs != null) { // need to parse the depenency and version and such // need to improve this later // this function recursively finds all dependencies // might need to do add instead of AddRange foundDependencies.AddRange(FindDependenciesFromSource(filteredFoundPkgs, resourceMetadata2, context2)); } /// end dep conditional // check which pkgs you actually need to install List <IPackageSearchMetadata> pkgsToInstall = new List <IPackageSearchMetadata>(); // install pkg, then install any dependencies to a temp directory pkgsToInstall.Add(filteredFoundPkgs); pkgsToInstall.AddRange(foundDependencies); if (_asNupkg) { // CreateFolderFeedV3Async(_path, PackageSaveMode.Nupkg | PackageSaveMode.Nuspec, packages). var tempInstallPath = System.IO.Path.Combine(System.IO.Path.GetTempPath(), Guid.NewGuid().ToString()); var dir = Directory.CreateDirectory(tempInstallPath); // should check it gets created properly //dir.SetAccessControl(new DirectorySecurity(dir.FullName, AccessControlSections.Owner)); // To delete file attributes from the existing ones get the current file attributes first and use AND (&) operator // with a mask (bitwise complement of desired attributes combination). dir.Attributes = dir.Attributes & ~FileAttributes.ReadOnly; //remove any null pkgs pkgsToInstall.Remove(null); // install everything to a temp path foreach (var p in pkgsToInstall) { var pkgIdentity = new PackageIdentity(p.Identity.Id, p.Identity.Version); var resource = new DownloadResourceV2FeedProvider(); var resource2 = resource.TryCreate(repository, cancellationToken); var cacheContext = new SourceCacheContext(); var downloadResource = repository.GetResourceAsync <DownloadResource>().GetAwaiter().GetResult(); var result = downloadResource.GetDownloadResourceResultAsync( pkgIdentity, new PackageDownloadContext(cacheContext), tempInstallPath, logger: NullLogger.Instance, CancellationToken.None).GetAwaiter().GetResult(); // need to close the .nupkg result.Dispose(); // 4) copy to proper path // TODO: test installing a script when it already exists // or move to script path // check for failures // var newPath = Directory.CreateDirectory(Path.Combine(psModulesPath, p.Identity.Id, p.Identity.Version.ToNormalizedString())); var installPath = SessionState.Path.GetResolvedPSPathFromPSPath(_path).FirstOrDefault().Path; // when we move the directory over, we'll change the casing of the module directory name from lower case to proper casing. // if script, just move the files over, if module, move the version directory overp var tempPkgIdPath = System.IO.Path.Combine(tempInstallPath, p.Identity.Id, p.Identity.Version.ToString()); var tempPkgVersionPath = System.IO.Path.Combine(tempPkgIdPath, p.Identity.Id.ToLower() + "." + p.Identity.Version + ".nupkg"); var newPath = System.IO.Path.Combine(installPath, p.Identity.Id + "." + p.Identity.Version + ".nupkg"); File.Move(tempPkgVersionPath, newPath); // 2) TODO: Verify that all the proper modules installed correctly // remove temp directory recursively Directory.Delete(tempInstallPath, true); pkgsLeftToInstall.Remove(n); } } else { var tempInstallPath = System.IO.Path.Combine(System.IO.Path.GetTempPath(), Guid.NewGuid().ToString()); var dir = Directory.CreateDirectory(tempInstallPath); // should check it gets created properly //dir.SetAccessControl(new DirectorySecurity(dir.FullName, AccessControlSections.Owner)); // To delete file attributes from the existing ones get the current file attributes first and use AND (&) operator // with a mask (bitwise complement of desired attributes combination). dir.Attributes = dir.Attributes & ~FileAttributes.ReadOnly; //remove any null pkgs pkgsToInstall.Remove(null); // install everything to a temp path foreach (var p in pkgsToInstall) { var pkgIdentity = new PackageIdentity(p.Identity.Id, p.Identity.Version); var resource = new DownloadResourceV2FeedProvider(); var resource2 = resource.TryCreate(repository, cancellationToken); var cacheContext = new SourceCacheContext(); var downloadResource = repository.GetResourceAsync <DownloadResource>().GetAwaiter().GetResult(); var result = downloadResource.GetDownloadResourceResultAsync( pkgIdentity, new PackageDownloadContext(cacheContext), tempInstallPath, logger: NullLogger.Instance, CancellationToken.None).GetAwaiter().GetResult(); // need to close the .nupkg result.Dispose(); // create a download count to see if everything was installed properly // 1) remove the *.nupkg file // may need to modify due to capitalization var dirNameVersion = System.IO.Path.Combine(tempInstallPath, p.Identity.Id, p.Identity.Version.ToNormalizedString()); var nupkgMetadataToDelete = System.IO.Path.Combine(dirNameVersion, ".nupkg.metadata").ToLower(); var nupkgToDelete = System.IO.Path.Combine(dirNameVersion, (p.Identity.ToString() + ".nupkg").ToLower()); var nupkgSHAToDelete = System.IO.Path.Combine(dirNameVersion, (p.Identity.ToString() + ".nupkg.sha512").ToLower()); var nuspecToDelete = System.IO.Path.Combine(dirNameVersion, (p.Identity.Id + ".nuspec").ToLower()); File.Delete(nupkgMetadataToDelete); File.Delete(nupkgSHAToDelete); File.Delete(nuspecToDelete); File.Delete(nupkgToDelete); // if it's not a script, do the following: var scriptPath = System.IO.Path.Combine(dirNameVersion, (p.Identity.Id.ToString() + ".ps1").ToLower()); var isScript = File.Exists(scriptPath) ? true : false; // 3) create xml //Create PSGetModuleInfo.xml //Set attribute as hidden [System.IO.File]::SetAttributes($psgetItemInfopath, [System.IO.FileAttributes]::Hidden) var fullinstallPath = isScript ? System.IO.Path.Combine(dirNameVersion, (p.Identity.Id + "_InstalledScriptInfo.xml")) : System.IO.Path.Combine(dirNameVersion, "PSGetModuleInfo.xml"); if (_includeXML) { // Create XMLs using (StreamWriter sw = new StreamWriter(fullinstallPath)) { var psModule = "PSModule"; var tags = p.Tags.Split(' '); var module = tags.Contains("PSModule") ? "Module" : null; var script = tags.Contains("PSScript") ? "Script" : null; List <string> includesDscResource = new List <string>(); List <string> includesCommand = new List <string>(); List <string> includesFunction = new List <string>(); List <string> includesRoleCapability = new List <string>(); List <string> filteredTags = new List <string>(); var psDscResource = "PSDscResource_"; var psCommand = "PSCommand_"; var psFunction = "PSFunction_"; var psRoleCapability = "PSRoleCapability_"; foreach (var tag in tags) { if (tag.StartsWith(psDscResource)) { includesDscResource.Add(tag.Remove(0, psDscResource.Length)); } else if (tag.StartsWith(psCommand)) { includesCommand.Add(tag.Remove(0, psCommand.Length)); } else if (tag.StartsWith(psFunction)) { includesFunction.Add(tag.Remove(0, psFunction.Length)); } else if (tag.StartsWith(psRoleCapability)) { includesRoleCapability.Add(tag.Remove(0, psRoleCapability.Length)); } else if (!tag.StartsWith("PSWorkflow_") && !tag.StartsWith("PSCmdlet_") && !tag.StartsWith("PSIncludes_") && !tag.Equals("PSModule") && !tag.Equals("PSScript")) { filteredTags.Add(tag); } } Dictionary <string, List <string> > includes = new Dictionary <string, List <string> >() { { "DscResource", includesDscResource }, { "Command", includesCommand }, { "Function", includesFunction }, { "RoleCapability", includesRoleCapability } }; Dictionary <string, VersionRange> dependencies = new Dictionary <string, VersionRange>(); foreach (var depGroup in p.DependencySets) { PackageDependency depPkg = depGroup.Packages.FirstOrDefault(); dependencies.Add(depPkg.Id, depPkg.VersionRange); } var psGetModuleInfoObj = new PSObject(); // TODO: Add release notes psGetModuleInfoObj.Members.Add(new PSNoteProperty("Name", p.Identity.Id)); psGetModuleInfoObj.Members.Add(new PSNoteProperty("Version", p.Identity.Version)); psGetModuleInfoObj.Members.Add(new PSNoteProperty("Type", module != null ? module : (script != null ? script : null))); psGetModuleInfoObj.Members.Add(new PSNoteProperty("Description", p.Description)); psGetModuleInfoObj.Members.Add(new PSNoteProperty("Author", p.Authors)); psGetModuleInfoObj.Members.Add(new PSNoteProperty("CompanyName", p.Owners)); psGetModuleInfoObj.Members.Add(new PSNoteProperty("PublishedDate", p.Published)); psGetModuleInfoObj.Members.Add(new PSNoteProperty("InstalledDate", System.DateTime.Now)); psGetModuleInfoObj.Members.Add(new PSNoteProperty("LicenseUri", p.LicenseUrl)); psGetModuleInfoObj.Members.Add(new PSNoteProperty("ProjectUri", p.ProjectUrl)); psGetModuleInfoObj.Members.Add(new PSNoteProperty("IconUri", p.IconUrl)); psGetModuleInfoObj.Members.Add(new PSNoteProperty("Includes", includes.ToList())); // TODO: check if getting deserialized properly psGetModuleInfoObj.Members.Add(new PSNoteProperty("PowerShellGetFormatVersion", "3")); psGetModuleInfoObj.Members.Add(new PSNoteProperty("Dependencies", dependencies.ToList())); psGetModuleInfoObj.Members.Add(new PSNoteProperty("RepositorySourceLocation", repositoryUrl)); psGetModuleInfoObj.Members.Add(new PSNoteProperty("Repository", repositoryUrl)); psGetModuleInfoObj.Members.Add(new PSNoteProperty("InstalledLocation", null)); // TODO: add installation location psGetModuleInfoObj.TypeNames.Add("Microsoft.PowerShell.Commands.PSRepositoryItemInfo"); var serializedObj = PSSerializer.Serialize(psGetModuleInfoObj); sw.Write(serializedObj); // set the xml attribute to hidden //System.IO.File.SetAttributes("c:\\code\\temp\\installtestpath\\PSGetModuleInfo.xml", FileAttributes.Hidden); } } // 4) copy to proper path // TODO: test installing a script when it already exists // or move to script path // check for failures // var newPath = Directory.CreateDirectory(Path.Combine(psModulesPath, p.Identity.Id, p.Identity.Version.ToNormalizedString())); var installPath = SessionState.Path.GetResolvedPSPathFromPSPath(_path).FirstOrDefault().Path; var newPath = isScript ? installPath : System.IO.Path.Combine(installPath, p.Identity.Id.ToString()); // when we move the directory over, we'll change the casing of the module directory name from lower case to proper casing. // if script, just move the files over, if module, move the version directory overp var tempModuleVersionDir = isScript ? System.IO.Path.Combine(tempInstallPath, p.Identity.Id.ToLower(), p.Identity.Version.ToNormalizedString()) : System.IO.Path.Combine(tempInstallPath, p.Identity.Id.ToLower()); if (isScript) { var scriptXML = p.Identity.Id + "_InstalledScriptInfo.xml"; File.Move(System.IO.Path.Combine(tempModuleVersionDir, scriptXML), System.IO.Path.Combine(installPath, "InstalledScriptInfos", scriptXML)); File.Move(System.IO.Path.Combine(tempModuleVersionDir, p.Identity.Id.ToLower() + ".ps1"), System.IO.Path.Combine(newPath, p.Identity.Id + ".ps1")); } else { if (!Directory.Exists(newPath)) { Directory.Move(tempModuleVersionDir, newPath); } else { // If the module directory path already exists, Directory.Move throws an exception, so we'll just move the version directory over instead tempModuleVersionDir = System.IO.Path.Combine(tempModuleVersionDir, p.Identity.Version.ToNormalizedString()); Directory.Move(tempModuleVersionDir, System.IO.Path.Combine(newPath, p.Identity.Version.ToNormalizedString())); } } // 2) TODO: Verify that all the proper modules installed correctly // remove temp directory recursively Directory.Delete(tempInstallPath, true); pkgsLeftToInstall.Remove(n); } } } return(pkgsLeftToInstall); }
/// <summary> /// Converts an object into string /// </summary> /// <param name="Item">The arbitrary object to serialize</param> /// <returns>A string containing the serialized inputobject</returns> public static string ToString(object Item) { return(PSSerializer.Serialize(Item)); }
/// <summary> /// Converts an object into bytes /// </summary> /// <param name="Item">The arbitrary object to serialize</param> /// <param name="Depth">Overrrides the default serialization depth</param> /// <returns>A byte array containing the serialized inputobject</returns> public static byte[] ToByte(object Item, int Depth) { return(Encoding.UTF8.GetBytes(PSSerializer.Serialize(Item, Depth))); }
/// <summary> /// Converts an object into string /// </summary> /// <param name="Item">The arbitrary object to serialize</param> /// <param name="Depth">Overrrides the default serialization depth</param> /// <returns>A string containing the serialized inputobject</returns> public static string ToString(object Item, int Depth) { return(PSSerializer.Serialize(Item, Depth)); }
/// <summary> /// Validates an ARM template. /// </summary> /// <param name="resourceGroupName">The name of the resource group to validate against.</param> /// <param name="templateFilePath">Path to the ARM template file to validate.</param> /// <param name="templateParametersFilePath">Path to the ARM template parameters file to use with validation.</param> /// <returns>True if valid, and false if invalid.</returns> public static bool ValidateTemplate(string resourceGroupName, string templateFilePath, string templateParametersFilePath) { if (!Directory.Exists(_tempArmDir)) { Directory.CreateDirectory(_tempArmDir); } ArmTemplateHelper.LoadArmTemplateParameters(templateParametersFilePath); IEnumerable <string> parameterNames = ArmTemplateHelper.GetParameterNames(templateParametersFilePath); foreach (string parameterName in parameterNames) { ArmTemplateHelper.SetParameterValue( templateParametersFilePath, parameterName, ArmTemplateHelper.GetParameterValue( templateParametersFilePath, parameterName)); } string templateParameterFileName = Path.GetFileName(templateParametersFilePath); string tempParametersFilePath = $@"{_tempArmDir}\{templateParameterFileName}"; ArmTemplateHelper.SaveConfiguration(templateParametersFilePath, tempParametersFilePath); using (PowerShell powerShellInstance = PowerShell.Create()) { powerShellInstance.AddCommand("Test-AzResourceGroupDeployment"); powerShellInstance.AddParameter("-ResourceGroupName", resourceGroupName); powerShellInstance.AddParameter("-TemplateFile", templateFilePath); powerShellInstance.AddParameter("-TemplateParameterFile", tempParametersFilePath); PSDataCollection <PSObject> outputCollection = new PSDataCollection <PSObject>(); powerShellInstance.Streams.Error.DataAdded += Error_DataAdded; IAsyncResult result = powerShellInstance.BeginInvoke <PSObject, PSObject>(null, outputCollection); while (!result.IsCompleted) { Debug.WriteLine("Waiting for pipeline to finish."); Thread.Sleep(1000); } Debug.WriteLine("Execution has stopped. The pipeline state: " + powerShellInstance.InvocationStateInfo.State); string serializedOutput = PSSerializer.Serialize(outputCollection); XNamespace ns = "http://schemas.microsoft.com/powershell/2004/04"; XDocument output = XDocument.Parse(serializedOutput); List <XElement> messageElements = output.Root.Descendants(ns + "S") .Where(x => x.Attribute("N") != null && x.Attribute("N").Value == "Message") .ToList(); foreach (XElement messageElement in messageElements) { Debug.WriteLine($"ERROR: {messageElement.Value}"); } if (messageElements.Count() != 0) { return(false); } if (powerShellInstance.Streams.Error.Count() > 0) { return(false); } return(true); } }