Ejemplo n.º 1
0
 public static IEnumerable <T> RunScript <T>(this PSCmdlet cmdlet, string script)
 => PsHelpers.RunScript <T>(cmdlet.InvokeCommand, script);
Ejemplo n.º 2
0
 internal WSManHelper(PSCmdlet cmdlet)
 {
     cmdletname = cmdlet;
 }
Ejemplo n.º 3
0
 /// <summary>
 /// Retrieves a wrapper used to invoke members of the type with name <paramref name="graphicalHostHelperTypeName"/>
 /// in Microsoft.PowerShell.GraphicalHost.dll
 /// </summary>
 /// <param name="parentCmdlet">The cmdlet requesting the wrapper (used to throw terminating errors).</param>
 /// <param name="graphicalHostHelperTypeName">The type name we want to invoke members from.</param>
 /// <returns>
 /// wrapper used to invoke members of the type with name <paramref name="graphicalHostHelperTypeName"/>
 /// in Microsoft.PowerShell.GraphicalHost.dll
 /// </returns>
 /// <exception cref="RuntimeException">When it was not possible to load Microsoft.PowerShell.GraphicalHost.dlly.</exception>
 internal static GraphicalHostReflectionWrapper GetGraphicalHostReflectionWrapper(PSCmdlet parentCmdlet, string graphicalHostHelperTypeName)
 {
     return(GraphicalHostReflectionWrapper.GetGraphicalHostReflectionWrapper(parentCmdlet, graphicalHostHelperTypeName, parentCmdlet.CommandInfo.Name));
 }
Ejemplo n.º 4
0
        /// <summary>
        /// Invokes a PowerShell command given a PowerShell instance and a PSCmdlet instance. If an error is found while invoking
        /// the command, the PSCmdlet pipeline is stopped by invoking PSCmdlet.ThrowTerminatingError with the first error found.
        /// </summary>
        /// <param name="ps">The PowerShell instance</param>
        /// <param name="psCmdlet">The PSCmdlet instance</param>
        /// <returns>An Enumerable of PSObjects representing the results of invoking the PowerShell instance</returns>
        public static IEnumerable <PSObject> InvokePowershellCommandOrThrowIfUnsuccessful(PowerShell ps, PSCmdlet psCmdlet)
        {
            var res = ps.Invoke();

            if (ps.HadErrors)
            {
                psCmdlet.ThrowTerminatingError(ps.Streams.Error[0]);
            }

            return(res);
        }
Ejemplo n.º 5
0
        /// <summary>
        /// Class constructor
        /// </summary>
        /// <param name="cmdlet"></param>
        /// <param name="className"></param>
        /// <param name="classVersion"></param>
        /// <param name="moduleVersion"></param>
        /// <param name="privateData"></param>
        public void Initialize(PSCmdlet cmdlet, string className, string classVersion, Version moduleVersion, IDictionary <string, string> privateData)
        {
            _moduleVersion = moduleVersion;

            Initialize(cmdlet, className, classVersion, privateData);
        }
Ejemplo n.º 6
0
        public void ExecuteCmdletBase(PSCmdlet callingCmdlet)
        {
            Dictionary <Guid, QueryMapNode> originalNodes         = new Dictionary <Guid, QueryMapNode>();
            List <QueryMapRelationship>     originalRelationships = new List <QueryMapRelationship>();
            List <QueryMapDescriptor>       originalDescriptors   = new List <QueryMapDescriptor>();
            List <QueryMapMetadata>         originalMetadata      = new List <QueryMapMetadata>();

            if (DestinationDomain == null || !DestinationDomain.CheckIsValid())
            {
                callingCmdlet.WriteWarning("An invalid destination domain has been provided.");

                return;
            }

            if (SourceMap == null || !SourceMap.CheckIsValid())
            {
                callingCmdlet.WriteWarning("An invalid source map has been provided.");

                return;
            }

            Model.IDatabaseInfo sourceMapDbInfo = SourceMap.Domain;

            using (MappingToolDatabaseDataContext dataContext = new MappingToolDatabaseDataContext(sourceMapDbInfo.ConnectionString))
            {
                dataContext.CommandTimeout = 180;
                var queryMapResultSets = dataContext.QueryMapMultiDepth(SourceMap.Domain.DomainId, SourceMap.NodeId, -1, false);

                var queryMapResultSet = queryMapResultSets.GetResult <QueryMapMultiDepthResult>();

                while (queryMapResultSet != null)
                {
                    foreach (var queryMapResult in queryMapResultSet)
                    {
                        if (queryMapResult.Level != null)
                        {
                            if (queryMapResult.NodeUid.HasValue && queryMapResult.NodeUid != Guid.Empty)
                            {
                                /// Make sure that we aren't copying across a domain node.
                                if (queryMapResult.NodeTypeUid.HasValue && queryMapResult.NodeTypeUid != new Guid("263754C2-2F31-4D21-B9C4-6509E00A5E94"))
                                {
                                    /// The QueryMap procedure returns ALL nodes by following relationships to max depth meaning some nodes are repeated in some of the levels multiple nodes may connect to them.
                                    if (!originalNodes.ContainsKey(queryMapResult.NodeUid.Value))
                                    {
                                        /// TODO: Need to consider copying the NodeOriginalId.
                                        QueryMapNode node = new QueryMapNode();
                                        node.NodeUid     = queryMapResult.NodeUid.Value;
                                        node.DomainUid   = DestinationDomain.DomainId;
                                        node.NodeTypeUid = queryMapResult.NodeTypeUid;
                                        node.RootMapUid  = queryMapResult.RootMapUid;
                                        node.Created     = queryMapResult.Created;
                                        node.Modified    = queryMapResult.Modified;
                                        node.CreatedBy   = queryMapResult.CreatedBy;
                                        node.ModifiedBy  = queryMapResult.ModifiedBy;

                                        originalNodes[queryMapResult.NodeUid.Value] = node;
                                    }
                                }
                            }
                        }
                        else if (queryMapResult.MetadataId != null)
                        {
                            if (queryMapResult.MetadataId.HasValue && queryMapResult.MetadataId != Guid.Empty)
                            {
                                QueryMapMetadata metadatum = new QueryMapMetadata();
                                metadatum.MetadataId        = queryMapResult.MetadataId.Value;
                                metadatum.NodeUid           = queryMapResult.NodeUid;
                                metadatum.RelationshipUid   = queryMapResult.RelationshipUid;
                                metadatum.DescriptorTypeUid = queryMapResult.DescriptorTypeUid;
                                metadatum.MetadataTypeUid   = queryMapResult.MetadataTypeUid;
                                metadatum.MetadataName      = queryMapResult.MetadataName;
                                metadatum.MetadataValue     = queryMapResult.MetadataValue;
                                metadatum.DomainUid         = queryMapResult.DomainUid;
                                metadatum.RootMapUid        = queryMapResult.RootMapUid;
                                metadatum.Created           = queryMapResult.Created;
                                metadatum.Modified          = queryMapResult.Modified;
                                metadatum.CreatedBy         = queryMapResult.CreatedBy;
                                metadatum.ModifiedBy        = queryMapResult.ModifiedBy;

                                originalMetadata.Add(metadatum);
                            }
                        }
                        else if (queryMapResult.DescriptorUid != null)
                        {
                            if (queryMapResult.DescriptorUid.HasValue && queryMapResult.DescriptorUid != Guid.Empty)
                            {
                                QueryMapDescriptor descriptor = new QueryMapDescriptor();
                                descriptor.DescriptorUid     = queryMapResult.DescriptorUid.Value;
                                descriptor.NodeUid           = queryMapResult.NodeUid;
                                descriptor.RelationshipUid   = queryMapResult.RelationshipUid;
                                descriptor.DescriptorTypeUid = queryMapResult.DescriptorTypeUid;

                                originalDescriptors.Add(descriptor);
                            }
                        }
                        else
                        {
                            if (queryMapResult.RelationshipUid.HasValue && queryMapResult.RelationshipUid != Guid.Empty)
                            {
                                /// TODO: Need to consider copying the RelationshipOriginalId.
                                QueryMapRelationship relationship = new QueryMapRelationship();
                                relationship.RelationshipUid     = queryMapResult.RelationshipUid.Value;
                                relationship.DomainUid           = DestinationDomain.DomainId;
                                relationship.RelationshipTypeUid = queryMapResult.RelationshipTypeUid;
                                relationship.RootMapUid          = queryMapResult.RootMapUid;
                                relationship.Created             = queryMapResult.Created;
                                relationship.Modified            = queryMapResult.Modified;
                                relationship.CreatedBy           = queryMapResult.CreatedBy;
                                relationship.ModifiedBy          = queryMapResult.ModifiedBy;

                                originalRelationships.Add(relationship);
                            }
                        }
                    }

                    queryMapResultSet = queryMapResultSets.GetResult <QueryMapMultiDepthResult>();
                }
            }

            int totalNodes         = originalNodes.Count;
            int totalRelationships = originalRelationships.Count;
            int totalMetadata      = originalMetadata.Count;
            int totalDescriptors   = originalDescriptors.Count;

            Dictionary <Guid, Guid> newNodeIds         = new Dictionary <Guid, Guid>();
            Dictionary <Guid, Guid> newRelationshipIds = new Dictionary <Guid, Guid>();

            Model.IDatabaseInfo destinationDomainDbInfo = DestinationDomain;

            /// The following performs the creation of nodes in the new database
            using (MappingToolDatabaseDataContext dataContext = new MappingToolDatabaseDataContext(destinationDomainDbInfo.ConnectionString))
            {
                dataContext.CommandTimeout = 180;
                int count = 0;

                callingCmdlet.WriteVerbose("Processing of nodes starting.");

                DateTime currentTime = DateTime.Now;

                WindowsIdentity currentUserIdentity = WindowsIdentity.GetCurrent();
                string          currentUserName     = "******";

                if (currentUserIdentity != null)
                {
                    currentUserName = currentUserIdentity.Name;
                }

                Guid newRootMapId = Guid.NewGuid();

                /// If it is the root map node, we want to assign it the pre-determined ID as we've been using this as the RootMapUid for everything;
                QueryMapNode sourceMapNode = originalNodes[SourceMap.NodeId];

                Node newRootMapNode = new Node();
                newRootMapNode.NodeUid     = newRootMapId;
                newRootMapNode.DomainUid   = DestinationDomain.DomainId;
                newRootMapNode.NodeTypeUid = sourceMapNode.NodeTypeUid;
                newRootMapNode.RootMapUid  = newRootMapId;
                newRootMapNode.Created     = sourceMapNode.Created;
                newRootMapNode.Modified    = currentTime;
                newRootMapNode.CreatedBy   = sourceMapNode.CreatedBy;
                newRootMapNode.ModifiedBy  = currentUserName;

                newNodeIds[sourceMapNode.NodeUid] = newRootMapNode.NodeUid;

                dataContext.Nodes.InsertOnSubmit(newRootMapNode);

                /// Iterate through all nodes in memory and change their node IDs and root map IDs so that they won't clash with the map from where they were copied.
                foreach (QueryMapNode memoryNode in originalNodes.Values)
                {
                    if (memoryNode.NodeUid == SourceMap.NodeId)
                    {
                        continue;
                    }

                    count++;

                    if (count % 10 == 0)
                    {
                        callingCmdlet.WriteVerbose(count + " / " + totalNodes + " Nodes Completed");
                    }

                    Node node = new Node();
                    node.NodeUid     = Guid.NewGuid();
                    node.DomainUid   = DestinationDomain.DomainId;
                    node.NodeTypeUid = memoryNode.NodeTypeUid;
                    node.RootMapUid  = newRootMapId;
                    node.Created     = memoryNode.Created;
                    node.Modified    = currentTime;
                    node.CreatedBy   = memoryNode.CreatedBy;
                    node.ModifiedBy  = currentUserName;

                    newNodeIds[memoryNode.NodeUid] = node.NodeUid;

                    dataContext.Nodes.InsertOnSubmit(node);
                }

                if (!newNodeIds.ContainsKey(SourceMap.NodeId))
                {
                    callingCmdlet.WriteWarning("Unexpected scenario. The source map NodeId can't be found in the list of copied nodes.");

                    return;
                }

                callingCmdlet.WriteVerbose("Committing nodes starting.");

                /// Commit node additions.
                dataContext.SubmitChanges();

                callingCmdlet.WriteVerbose("Committing nodes completed.");

                count = 0;

                callingCmdlet.WriteVerbose("Processing of relationships starting.");

                foreach (QueryMapRelationship memoryRelationship in originalRelationships)
                {
                    count++;

                    if (count % 10 == 0)
                    {
                        callingCmdlet.WriteVerbose(count + " / " + totalRelationships + " Relationships Completed");
                    }

                    Relationship relationship = new Relationship();
                    relationship.RelationshipUid     = Guid.NewGuid();
                    relationship.DomainUid           = DestinationDomain.DomainId;
                    relationship.RelationshipTypeUid = memoryRelationship.RelationshipTypeUid;
                    relationship.RootMapUid          = newRootMapId;
                    relationship.Created             = memoryRelationship.Created;
                    relationship.Modified            = currentTime;
                    relationship.CreatedBy           = memoryRelationship.CreatedBy;
                    relationship.ModifiedBy          = currentUserName;

                    newRelationshipIds[memoryRelationship.RelationshipUid] = relationship.RelationshipUid;

                    dataContext.Relationships.InsertOnSubmit(relationship);
                }

                callingCmdlet.WriteVerbose("Committing relationships starting.");

                /// Commit relationship additions.
                dataContext.SubmitChanges();

                callingCmdlet.WriteVerbose("Committing relationships completed.");

                count = 0;

                callingCmdlet.WriteVerbose("Processing of descriptors starting.");

                foreach (QueryMapDescriptor memoryDescriptor in originalDescriptors)
                {
                    count++;

                    if (count % 10 == 0)
                    {
                        callingCmdlet.WriteVerbose(count + " / " + totalDescriptors + " Descriptors Completed");
                    }

                    if (newNodeIds.ContainsKey(memoryDescriptor.NodeUid.Value) && newRelationshipIds.ContainsKey(memoryDescriptor.RelationshipUid.Value))
                    {
                        Descriptor descriptor = new Descriptor();
                        descriptor.DescriptorUid     = Guid.NewGuid();
                        descriptor.NodeUid           = newNodeIds[memoryDescriptor.NodeUid.Value];
                        descriptor.RelationshipUid   = newRelationshipIds[memoryDescriptor.RelationshipUid.Value];
                        descriptor.DescriptorTypeUid = memoryDescriptor.DescriptorTypeUid;

                        dataContext.Descriptors.InsertOnSubmit(descriptor);
                    }
                }

                callingCmdlet.WriteVerbose("Committing descriptors starting.");

                /// Commit descriptor additions.
                dataContext.SubmitChanges();

                callingCmdlet.WriteVerbose("Committing descriptors completed.");

                count = 0;

                callingCmdlet.WriteVerbose("Processing of metadata starting.");

                foreach (QueryMapMetadata memoryMetadatum in originalMetadata)
                {
                    count++;

                    if (count % 10 == 0)
                    {
                        callingCmdlet.WriteVerbose(count + " / " + totalMetadata + " Metadata Completed");
                    }

                    if (memoryMetadatum.NodeUid == null || newNodeIds.ContainsKey(memoryMetadatum.NodeUid.Value))
                    {
                        if (memoryMetadatum.RelationshipUid == null || newRelationshipIds.ContainsKey(memoryMetadatum.RelationshipUid.Value))
                        {
                            Metadata metadatum = new Metadata();
                            metadatum.MetadataId = Guid.NewGuid();

                            if (memoryMetadatum.NodeUid != null)
                            {
                                metadatum.NodeUid = newNodeIds[memoryMetadatum.NodeUid.Value];
                            }
                            else
                            {
                                metadatum.NodeUid = null;
                            }

                            if (memoryMetadatum.RelationshipUid != null)
                            {
                                metadatum.RelationshipUid = newRelationshipIds[memoryMetadatum.RelationshipUid.Value];
                            }
                            else
                            {
                                metadatum.RelationshipUid = null;
                            }

                            metadatum.DescriptorTypeUid = memoryMetadatum.DescriptorTypeUid;
                            metadatum.MetadataTypeUid   = memoryMetadatum.MetadataTypeUid;
                            metadatum.MetadataName      = memoryMetadatum.MetadataName;
                            metadatum.MetadataValue     = memoryMetadatum.MetadataValue;
                            metadatum.DomainUid         = DestinationDomain.DomainId;
                            metadatum.RootMapUid        = newRootMapId;
                            metadatum.Created           = memoryMetadatum.Created;
                            metadatum.Modified          = currentTime;
                            metadatum.CreatedBy         = memoryMetadatum.CreatedBy;
                            metadatum.ModifiedBy        = currentUserName;

                            dataContext.Metadatas.InsertOnSubmit(metadatum);
                        }
                    }
                }

                callingCmdlet.WriteVerbose("Committing metadata starting.");

                /// Commit metadata additions.
                dataContext.SubmitChanges();

                callingCmdlet.WriteVerbose("Committing metadata completed.");

                callingCmdlet.WriteVerbose("Connecting map to domain.");

                Relationship domainNodeMapRelationship = new Relationship();
                domainNodeMapRelationship.RelationshipUid     = Guid.NewGuid();
                domainNodeMapRelationship.DomainUid           = DestinationDomain.DomainId;
                domainNodeMapRelationship.RelationshipTypeUid = new Guid("4AFF46D7-87BE-48DD-B703-A93E38EF8FFB");
                domainNodeMapRelationship.RootMapUid          = newRootMapId;
                domainNodeMapRelationship.Created             = currentTime;
                domainNodeMapRelationship.Modified            = currentTime;
                domainNodeMapRelationship.CreatedBy           = currentUserName;
                domainNodeMapRelationship.ModifiedBy          = currentUserName;

                Descriptor domainNodeMapFromDescriptor = new Descriptor();
                domainNodeMapFromDescriptor.DescriptorUid     = Guid.NewGuid();
                domainNodeMapFromDescriptor.DescriptorTypeUid = new Guid("96DA1782-058C-4F9B-BB1A-31B048F8C75A");
                domainNodeMapFromDescriptor.NodeUid           = newNodeIds[SourceMap.NodeId];
                domainNodeMapFromDescriptor.RelationshipUid   = domainNodeMapRelationship.RelationshipUid;

                Descriptor domainNodeMapToDescriptor = new Descriptor();
                domainNodeMapToDescriptor.DescriptorUid     = Guid.NewGuid();
                domainNodeMapToDescriptor.DescriptorTypeUid = new Guid("07C91D35-4DAC-431B-966B-64C924B8CDAB");
                domainNodeMapToDescriptor.NodeUid           = DestinationDomain.NodeId;
                domainNodeMapToDescriptor.RelationshipUid   = domainNodeMapRelationship.RelationshipUid;

                dataContext.Relationships.InsertOnSubmit(domainNodeMapRelationship);
                dataContext.Descriptors.InsertOnSubmit(domainNodeMapFromDescriptor);
                dataContext.Descriptors.InsertOnSubmit(domainNodeMapToDescriptor);

                dataContext.SubmitChanges();

                callingCmdlet.WriteVerbose("Completed connecting map to domain.");

                callingCmdlet.WriteVerbose("Copy completed.");
            }
        }
Ejemplo n.º 7
0
 public static void RunScript(this PSCmdlet cmdlet, ScriptBlock block)
 => cmdlet.RunScript <PSObject>(block.ToString());
Ejemplo n.º 8
0
 private static bool IsScript(PSCmdlet cmdlet) => !string.IsNullOrEmpty(cmdlet.MyInvocation.ScriptName);
Ejemplo n.º 9
0
 private static bool IsISE(PSCmdlet cmdlet) => cmdlet.GetVariableValue("global:psISE") != null;
Ejemplo n.º 10
0
 private static bool ProgressSpecified(PSCmdlet cmdlet) => cmdlet.MyInvocation.BoundParameters.ContainsKey(nameof(Progress));
Ejemplo n.º 11
0
 private bool ProgressFalse(PSCmdlet cmdlet) => ProgressSpecified(cmdlet) && Progress == false;
Ejemplo n.º 12
0
 public PowerShellSessionState(PSCmdlet cmdlet)
 {
     _cmdlet = cmdlet;
 }
 public void ClearVariable(PSCmdlet cmdlet, string name)
 {
     _variables.Remove(name);
 }
 public void SetVariable(PSCmdlet cmdlet, string name, object value)
 {
     _variables[name] = value;
 }
Ejemplo n.º 15
0
        /// <summary>
        /// 
        /// </summary>
        /// <param name="cmdlet"></param>
        /// <param name="path"></param>
        /// <param name="credential"></param>
        internal UpdatableHelpSystemDrive(PSCmdlet cmdlet, string path, PSCredential credential)
        {
            for (int i = 0; i < 6; i++)
            {
                _driveName = Path.GetFileNameWithoutExtension(Path.GetRandomFileName());
                _cmdlet = cmdlet;

                // Need to get rid of the trailing \, otherwise New-PSDrive will not work...
                if (path.EndsWith("\\", StringComparison.OrdinalIgnoreCase) || path.EndsWith("/", StringComparison.OrdinalIgnoreCase))
                {
                    path = path.Remove(path.Length - 1);
                }

                PSDriveInfo mappedDrive = cmdlet.SessionState.Drive.GetAtScope(_driveName, "local");

                if (mappedDrive != null)
                {
                    if (mappedDrive.Root.Equals(path))
                    {
                        return;
                    }

                    // Remove the drive after 5 tries
                    if (i < 5)
                    {
                        continue;
                    }

                    cmdlet.SessionState.Drive.Remove(_driveName, true, "local");
                }

                mappedDrive = new PSDriveInfo(_driveName, cmdlet.SessionState.Internal.GetSingleProvider("FileSystem"),
                    path, String.Empty, credential);

                cmdlet.SessionState.Drive.New(mappedDrive, "local");

                break;
            }
        }
Ejemplo n.º 16
0
 private bool ProgressTrue(PSCmdlet cmdlet) => ProgressSpecified(cmdlet) && Progress;
Ejemplo n.º 17
0
 public FindHelper(CancellationToken cancellationToken, PSCmdlet cmdletPassedIn)
 {
     _cancellationToken = cancellationToken;
     _cmdletPassedIn    = cmdletPassedIn;
 }
Ejemplo n.º 18
0
 public TypeGetter(PSCmdlet cmdlet)
 {
     _cmdlet = cmdlet;
 }
Ejemplo n.º 19
0
 public static IEnumerable <T> RunScript <T>(this PSCmdlet cmdlet, ScriptBlock block)
 => PsHelpers.RunScript <T>(cmdlet.InvokeCommand, block.ToString());
 internal InvokeGraphRequestUserAgent(PSCmdlet cmdLet)
 {
     _cmdLet = cmdLet;
 }
        public static Endpoint GenerateCallback(this ScriptBlock endpoint, string id, PSCmdlet cmdlet, System.Management.Automation.SessionState sessionState, object[] argumentList = null)
        {
            if (endpoint == null)
            {
                return(null);
            }

            var logger = LogManager.GetLogger("CallbackCmdlet");

            var callback = new Endpoint();

            callback.Name        = id;
            callback.ScriptBlock = endpoint;

            callback.Variables    = new Dictionary <string, object>();
            callback.ArgumentList = argumentList;

            try
            {
                var variables = endpoint.Ast.FindAll(x => x is VariableExpressionAst, true).Cast <VariableExpressionAst>().Select(m => m.VariablePath.ToString());

                foreach (var variableName in variables)
                {
                    var variable = sessionState.PSVariable.Get(variableName);
                    if (variable != null && !variable.Options.HasFlag(ScopedItemOptions.Constant) && !variable.Options.HasFlag(ScopedItemOptions.ReadOnly))
                    {
                        if (!callback.Variables.ContainsKey(variable.Name))
                        {
                            callback.Variables.Add(variable.Name, sessionState.PSVariable.GetValue(variable.Name));
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                logger.Error(ex, "Failed to look up variables.");
            }

            callback.SessionId = sessionState.PSVariable.Get(Constants.SessionId)?.Value as string;
            callback.Page      = sessionState.PSVariable.Get(Constants.UDPage)?.Value as Page;

            var hostState = cmdlet.GetHostState();

            hostState.EndpointService.Register(callback);

            return(callback);
        }
Ejemplo n.º 22
0
 public static void GetCallerPreference(this PSCmdlet cmdlet)
 {
     // cmdlet.Invoke("Get-CallerPreference -Cmdlet $PSCmdlet -SessionState $ExecutionContext.SessionState");
 }
Ejemplo n.º 23
0
 public PSSyncOutputEvents(PSCmdlet cmdlet)
 {
     this.cmdlet   = cmdlet;
     this.runspace = RunspaceFactory.CreateRunspace(this.cmdlet.Host);
     this.runspace.Open();
 }
Ejemplo n.º 24
0
        public static List <string> GetAllResourcePaths(
            PSCmdlet psCmdlet,
            ScopeType?scope = null)
        {
            GetStandardPlatformPaths(
                psCmdlet,
                out string myDocumentsPath,
                out string programFilesPath);

            List <string> resourcePaths = new List <string>();

            // Path search order is PSModulePath paths first, then default paths.
            if (scope is null)
            {
                string psModulePath = Environment.GetEnvironmentVariable("PSModulePath");
                resourcePaths.AddRange(psModulePath.Split(Path.PathSeparator).ToList());
            }

            if (scope is null || scope.Value is ScopeType.CurrentUser)
            {
                resourcePaths.Add(Path.Combine(myDocumentsPath, "Modules"));
                resourcePaths.Add(Path.Combine(myDocumentsPath, "Scripts"));
            }

            if (scope is null || scope.Value is ScopeType.AllUsers)
            {
                resourcePaths.Add(Path.Combine(programFilesPath, "Modules"));
                resourcePaths.Add(Path.Combine(programFilesPath, "Scripts"));
            }

            // resourcePaths should now contain, eg:
            // ./PowerShell/Scripts
            // ./PowerShell/Modules
            // add all module directories or script files
            List <string> pathsToSearch = new List <string>();

            foreach (string path in resourcePaths)
            {
                psCmdlet.WriteVerbose(string.Format("Retrieving directories in the path '{0}'", path));

                if (path.EndsWith("Scripts"))
                {
                    try
                    {
                        pathsToSearch.AddRange(GetDirectoryFiles(path));
                    }
                    catch (Exception e)
                    {
                        psCmdlet.WriteVerbose(string.Format("Error retrieving files from '{0}': '{1}'", path, e.Message));
                    }
                }
                else
                {
                    try
                    {
                        pathsToSearch.AddRange(GetSubDirectories(path));
                    }
                    catch (Exception e)
                    {
                        psCmdlet.WriteVerbose(string.Format("Error retrieving directories from '{0}': '{1}'", path, e.Message));
                    }
                }
            }

            // resourcePaths should now contain eg:
            // ./PowerShell/Scripts/Test-Script.ps1
            // ./PowerShell/Modules/TestModule
            // need to use .ToList() to cast the IEnumerable<string> to type List<string>
            pathsToSearch = pathsToSearch.Distinct(StringComparer.InvariantCultureIgnoreCase).ToList();
            pathsToSearch.ForEach(dir => psCmdlet.WriteVerbose(string.Format("All paths to search: '{0}'", dir)));

            return(pathsToSearch);
        }
Ejemplo n.º 25
0
        private static void ReportWrongProviderType(string providerId, string errorId, PSCmdlet cmdlet)
        {
            ErrorRecord errorRecord = new(
                PSTraceSource.NewInvalidOperationException(UpdateDataStrings.UpdateData_WrongProviderError, providerId),
                errorId,
                ErrorCategory.InvalidArgument,
                null);

            cmdlet.WriteError(errorRecord);
        }
Ejemplo n.º 26
0
 public CallerProxy(PSCmdlet caller)
 {
     this.caller = caller;
 }
Ejemplo n.º 27
0
 public static IObservable <T> IgnoreException <T, TException>(this IObservable <T> source, PSCmdlet cmdlet, object targetObject) where  TException : Exception
 {
     return(source.ObserveOn(SynchronizationContext.Current)
            .Catch <T, TException>(exception => {
         cmdlet.WriteError(new ErrorRecord(exception, $"{exception.GetHashCode()}", ErrorCategory.InvalidOperation, targetObject));
         return Observable.Empty <T>();
     }));
 }
Ejemplo n.º 28
0
 public SqlDatabaseProgram(PSCmdlet owner)
 {
     _owner = owner;
 }
Ejemplo n.º 29
0
        internal static GraphicalHostReflectionWrapper GetGraphicalHostReflectionWrapper(PSCmdlet parentCmdlet, string graphicalHostHelperTypeName, string featureName)
        {
            GraphicalHostReflectionWrapper returnValue = new GraphicalHostReflectionWrapper();

            if (GraphicalHostReflectionWrapper.IsInputFromRemoting(parentCmdlet))
            {
                ErrorRecord error = new ErrorRecord(
                    new NotSupportedException(StringUtil.Format(HelpErrors.RemotingNotSupportedForFeature, featureName)),
                    "RemotingNotSupported",
                    ErrorCategory.InvalidOperation,
                    parentCmdlet);

                parentCmdlet.ThrowTerminatingError(error);
            }

            // Prepare the full assembly name.
            AssemblyName graphicalHostAssemblyName = new AssemblyName();

            graphicalHostAssemblyName.Name        = "Microsoft.PowerShell.GraphicalHost";
            graphicalHostAssemblyName.Version     = new Version(3, 0, 0, 0);
            graphicalHostAssemblyName.CultureInfo = new CultureInfo(String.Empty); // Neutral culture
            graphicalHostAssemblyName.SetPublicKeyToken(new byte[] { 0x31, 0xbf, 0x38, 0x56, 0xad, 0x36, 0x4e, 0x35 });

            try
            {
                returnValue._graphicalHostAssembly = Assembly.Load(graphicalHostAssemblyName);
            }
            catch (FileNotFoundException fileNotFoundEx)
            {
                // This exception is thrown if the Microsoft.PowerShell.GraphicalHost.dll could not be found (was not installed).
                string errorMessage = StringUtil.Format(
                    HelpErrors.GraphicalHostAssemblyIsNotFound,
                    featureName,
                    fileNotFoundEx.Message);

                parentCmdlet.ThrowTerminatingError(
                    new ErrorRecord(
                        new NotSupportedException(errorMessage, fileNotFoundEx),
                        "ErrorLoadingAssembly",
                        ErrorCategory.ObjectNotFound,
                        graphicalHostAssemblyName));
            }
            catch (Exception e)
            {
                parentCmdlet.ThrowTerminatingError(
                    new ErrorRecord(
                        e,
                        "ErrorLoadingAssembly",
                        ErrorCategory.ObjectNotFound,
                        graphicalHostAssemblyName));
            }

            returnValue._graphicalHostHelperType = returnValue._graphicalHostAssembly.GetType(graphicalHostHelperTypeName);

            Diagnostics.Assert(returnValue._graphicalHostHelperType != null, "the type exists in Microsoft.PowerShell.GraphicalHost");
            ConstructorInfo constructor = returnValue._graphicalHostHelperType.GetConstructor(
                BindingFlags.NonPublic | BindingFlags.Instance,
                null,
                new Type[] { },
                null);

            if (constructor != null)
            {
                returnValue._graphicalHostHelperObject = constructor.Invoke(new object[] { });
                Diagnostics.Assert(returnValue._graphicalHostHelperObject != null, "the constructor does not throw anything");
            }

            return(returnValue);
        }
Ejemplo n.º 30
0
 public GitClient(PSCmdlet pscmdlet)
 {
     InvocationPath = pscmdlet.MyInvocation.MyCommand.Module.Path;
 }
Ejemplo n.º 31
0
 public static void RunScript(this PSCmdlet cmdlet, string script)
 => cmdlet.RunScript <PSObject>(script);
Ejemplo n.º 32
0
        /// <summary>
        /// Loads string from the given path
        /// </summary>
        /// <param name="cmdlet">cmdlet instance</param>
        /// <param name="path">path to load</param>
        /// <param name="credential">credential</param>
        /// <returns>string loaded</returns>
        internal static string LoadStringFromPath(PSCmdlet cmdlet, string path, PSCredential credential)
        {
            Debug.Assert(path != null);

            if (credential != null)
            {
                // New PSDrive

                using (UpdatableHelpSystemDrive drive = new UpdatableHelpSystemDrive(cmdlet, Path.GetDirectoryName(path), credential))
                {
                    string tempPath = Path.Combine(Path.GetTempPath(), Path.GetFileNameWithoutExtension(Path.GetTempFileName()));

                    if (!cmdlet.InvokeProvider.Item.Exists(Path.Combine(drive.DriveName, Path.GetFileName(path))))
                    {
                        return null;
                    }

                    cmdlet.InvokeProvider.Item.Copy(new string[1] { Path.Combine(drive.DriveName, Path.GetFileName(path)) }, tempPath,
                        false, CopyContainers.CopyTargetContainer, true, true);

                    path = tempPath;
                }
            }

            if (File.Exists(path))
            {
                using (FileStream currentHelpInfoFile = new FileStream(path, FileMode.Open, FileAccess.Read))
                {
                    StreamReader reader = new StreamReader(currentHelpInfoFile);

                    return reader.ReadToEnd();
                }
            }

            return null;
        }