Exemplo n.º 1
0
        public static Stream CreatePsPath(SessionState session, string filePath)
        {
            string parentPath = session.Path.ParseParent(filePath, null);
            string childName = session.Path.ParseChildName(filePath);
            var parentItems = session.InvokeProvider.Item.Get(parentPath);
            if (parentItems.Count > 1)
            {
                throw new IOException(string.Format(CultureInfo.InvariantCulture, "PowerShell path {0} is ambiguous", parentPath));
            }
            else if (parentItems.Count < 1)
            {
                throw new DirectoryNotFoundException("No such directory");
            }

            DirectoryInfo parentAsDir = parentItems[0].BaseObject as DirectoryInfo;
            if (parentAsDir != null)
            {
                return File.Create(Path.Combine(parentAsDir.FullName, childName));
            }

            DiscDirectoryInfo parentAsDiscDir = parentItems[0].BaseObject as DiscDirectoryInfo;
            if (parentAsDiscDir != null)
            {
                return parentAsDiscDir.FileSystem.OpenFile(Path.Combine(parentAsDiscDir.FullName, childName), FileMode.Create, FileAccess.ReadWrite);
            }

            throw new FileNotFoundException("Path is not a directory", parentPath);
        }
 protected override void ProcessRecord()
 {
     IBuildDefinition[] builddefinitions;
     try
     {
         if (_projectCollectionUri != null)
         {
             var uri = new Uri(_projectCollectionUri);
             var tpc = TfsTeamProjectCollectionFactory.GetTeamProjectCollection(uri);
             var buildserver = tpc.GetService<IBuildServer>();
             builddefinitions = buildserver.QueryBuildDefinitions(ProjectName);
         }
         else
         {
             var x = new SessionState();
             var currentDirectory = x.Path.CurrentLocation.Path;
             builddefinitions = Core.GetBuildDefinitionsByLocalPath(currentDirectory);
             if (builddefinitions == null)
             {
                 throw new Exception("No mapped workspace could be found at this path");
             }
         }
         WriteObject(builddefinitions, true);
     }
     catch (Exception ex)
     {
         WriteObject(ex, true);
     }
     base.ProcessRecord();
 }
Exemplo n.º 3
0
        public static InitialSessionState GenerateInitialSessionState(System.Management.Automation.SessionState sessionState)
        {
            var initialSessionState = InitialSessionState.CreateDefault2();

            var modulePaths = sessionState.InvokeCommand.InvokeScript("Get-Module").Select(m => m.BaseObject).Cast <PSModuleInfo>().Select(m => m.Path).ToArray();

            initialSessionState.ImportPSModule(modulePaths);

            var commands = sessionState.InvokeCommand.InvokeScript("Get-ChildItem -Path Function:\\").Select(m => m.BaseObject).Cast <FunctionInfo>();

            foreach (var command in commands)
            {
                initialSessionState.Commands.Add(new SessionStateFunctionEntry(command.Name, command.Definition));
            }

            var variables = sessionState.InvokeCommand.InvokeScript("Get-Variable").Select(m => m.BaseObject).Cast <PSVariable>();

            foreach (var variable in variables)
            {
                if (variable.Options.HasFlag(ScopedItemOptions.Constant) || variable.Options.HasFlag(ScopedItemOptions.ReadOnly))
                {
                    continue;
                }
                initialSessionState.Variables.Add(new SessionStateVariableEntry(variable.Name, variable.Value, variable.Description));
            }

            return(initialSessionState);
        }
Exemplo n.º 4
0
        public static SftpSession AddToSftpSessionCollection(SftpClient sftpclient, SessionState pssession)
        {
            //Set initial variables
            var obj = new SftpSession();
            var sftpSessions = new List<SftpSession>();
            var index = 0;

            // Retrive existing sessions from the globla variable.
            var sessionvar = pssession.PSVariable.GetValue("Global:SFTPSessions") as List<SftpSession>;

            // If sessions exist we set the proper index number for them.
            if (sessionvar != null)
            {
                sftpSessions.AddRange(sessionvar);
                index = sftpSessions.Count;
            }

            // Create the object that will be saved
            obj.SessionId = index;
            obj.Host = sftpclient.ConnectionInfo.Host;
            obj.Session = sftpclient;
            sftpSessions.Add(obj);

            // Set the Global Variable for the sessions.
            pssession.PSVariable.Set((new PSVariable("Global:SFTPSessions", sftpSessions, ScopedItemOptions.AllScope)));
            return obj;
        }
Exemplo n.º 5
0
 internal ProviderRuntime(SessionState sessionState, bool force, bool avoidWildcardExpansion)
     : this()
 {
     SessionState = sessionState;
     AvoidGlobbing = avoidWildcardExpansion;
     Force = force;
 }
Exemplo n.º 6
0
		private static InitialSessionState GetSessionState(SessionState sessionState)
		{
			var initialSessionState = InitialSessionState.CreateDefault2();
			CaptureVariables(sessionState, initialSessionState);
			CaptureFunctions(sessionState, initialSessionState);
			return initialSessionState;
		}
Exemplo n.º 7
0
 internal PathInfo(PSDriveInfo drive, ProviderInfo provider, Path path, SessionState sessionState)
 {
     Drive = drive;
     Provider = provider;
     _path = path;
     _sessionState = sessionState;
 }
Exemplo n.º 8
0
 internal ProviderInfo(SessionState sessionState, Type implementingType, string name, string description, string home, string helpFile, PSSnapInInfo psSnapIn)
 {
     this.helpFile = "";
     if (sessionState == null)
     {
         throw PSTraceSource.NewArgumentNullException("sessionState");
     }
     if (implementingType == null)
     {
         throw PSTraceSource.NewArgumentNullException("implementingType");
     }
     if (string.IsNullOrEmpty(name))
     {
         throw PSTraceSource.NewArgumentException("name");
     }
     if (string.IsNullOrEmpty(name))
     {
         throw PSTraceSource.NewArgumentException("name");
     }
     this.sessionState = sessionState;
     this.name = name;
     this.description = description;
     this.home = home;
     this.implementingType = implementingType;
     this.helpFile = helpFile;
     this.pssnapin = psSnapIn;
     this.hiddenDrive = new PSDriveInfo(this.FullName, this, "", "", null);
     this.hiddenDrive.Hidden = true;
 }
Exemplo n.º 9
0
		internal static bool IsCurrentDriveAD(SessionState sessionState)
		{
			PSDriveInfo current = sessionState.Drive.Current;
			ProviderInfo provider = current.Provider;
			bool flag = string.Compare(provider.Name, "ActiveDirectory", StringComparison.OrdinalIgnoreCase) == 0;
			return flag;
		}
Exemplo n.º 10
0
		internal static string GetCurrentPartitionPath(SessionState sessionState)
		{
			ADRootDSE rootDSE;
			string str = null;
			ADDriveInfo current = sessionState.Drive.Current as ADDriveInfo;
			if (current != null)
			{
				using (ADObjectSearcher aDObjectSearcher = new ADObjectSearcher(current.SessionInfo))
				{
					rootDSE = aDObjectSearcher.GetRootDSE();
					rootDSE.SessionInfo = current.SessionInfo;
				}
				string currentDriveLocation = ProviderUtils.GetCurrentDriveLocation(sessionState, current.SessionInfo);
				if (currentDriveLocation != string.Empty)
				{
					try
					{
						str = ADForestPartitionInfo.ExtractAndValidatePartitionInfo(rootDSE, currentDriveLocation);
					}
					catch (ArgumentException argumentException1)
					{
						ArgumentException argumentException = argumentException1;
						object[] objArray = new object[1];
						objArray[0] = currentDriveLocation;
						throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, StringResources.ProviderUtilInvalidDrivePath, objArray), argumentException);
					}
				}
				else
				{
					return string.Empty;
				}
			}
			return str;
		}
Exemplo n.º 11
0
        public static SshSession AddToSshSessionCollection(SshClient sshclient, SessionState pssession)
        {
            //Set initial variables
            var obj = new SshSession();
            var sshSessions = new List<SshSession>();
            var index = 0;

            // Retrieve existing sessions from the global variable.
            var sessionvar = pssession.PSVariable.GetValue("Global:SshSessions") as List<SshSession>;

            // If sessions exist we set the proper index number for them.
            if (sessionvar != null && sessionvar.Count > 0)
            {
                sshSessions.AddRange(sessionvar);

                // Get the SessionId of the last item and count + 1
                SshSession lastSession = sshSessions[sshSessions.Count - 1];
                index = lastSession.SessionId + 1;
            }

            // Create the object that will be saved
            obj.SessionId = index;
            obj.Host = sshclient.ConnectionInfo.Host;
            obj.Session = sshclient;
            sshSessions.Add(obj);

            // Set the Global Variable for the sessions.
            pssession.PSVariable.Set((new PSVariable("Global:SshSessions", sshSessions, ScopedItemOptions.AllScope)));

            return obj;
        }
Exemplo n.º 12
0
 internal void InternalDispose(bool isDisposing)
 {
     this.myInvocation = null;
     this.state = null;
     this.commandInfo = null;
     this.context = null;
 }
        //private string _projectCollectionUri;
        //[AllowNull]
        //[Parameter(ParameterSetName = "ParamByUri")]
        //public string ProjectCollectionUri
        //{
        //    get { return _projectCollectionUri; }
        //    set
        //    {
        //        if (Uri.IsWellFormedUriString(value, UriKind.Absolute))
        //        {
        //            _projectCollectionUri = value;
        //        }
        //    }
        //}
        protected override void ProcessRecord()
        {
            PendingChange[] pc;
            try
            {
                //if (_projectCollectionUri != null)
                //{
                //var uri = new Uri(_projectCollectionUri);
                //var tpc = TfsTeamProjectCollectionFactory.GetTeamProjectCollection(uri);
                //var vcs = tpc.GetService<VersionControlServer>();
                //tpc.ConfigurationServer.Connect(ConnectOptions.IncludeServices);
                //tpc.ConfigurationServer.Authenticate();

                ///builds = buildserver.QueryBuilds(ProjectName);
                //}

                var x = new SessionState();
                var currentDirectory = x.Path.CurrentLocation.Path;
                var wk = Core.GetWorkspaceByLocalPath(currentDirectory);
                pc = wk.GetPendingChanges();
                if (pc == null)
                {
                    throw new Exception("No mapped workspace could be found at this path");
                }
                WriteObject(pc, true);
            }
            catch (Exception ex)
            {
                WriteObject(ex, true);
            }
            base.ProcessRecord();
        }
Exemplo n.º 14
0
 public ExecutionContext(PSHost host, RunspaceConfiguration config)
     : this()
 {
     RunspaceConfiguration = config;
     LocalHost = host;
     SessionStateGlobal = new SessionStateGlobal(this);
     SessionState = new SessionState(SessionStateGlobal);
 }
Exemplo n.º 15
0
 internal LocationGlobber(SessionState sessionState)
 {
     if (sessionState == null)
     {
         throw PSTraceSource.NewArgumentNullException("sessionState");
     }
     this.sessionState = sessionState;
 }
Exemplo n.º 16
0
 internal SessionState(SessionState sessionState)
 {
     SessionStateGlobal = sessionState.SessionStateGlobal;
     Drive = sessionState.Drive;
     Path = sessionState.Path;
     Provider = sessionState.Provider;
     PSVariable = sessionState.PSVariable;
 }
Exemplo n.º 17
0
        internal static PSObject GetPsObject(SessionState provider, Notification notification)
        {
            var psobj = PSObject.AsPSObject(notification);

            psobj.Properties.Add(new PSNoteProperty("Type", notification.GetType().Name));

            return psobj;
        }
Exemplo n.º 18
0
        /// <summary>
        /// Gets an provider path for the given component key path.
        /// </summary>
        /// <param name="session">The <see cref="SessionState"/> for resolving key paths.</param>
        /// <param name="path">The component key path to resolve.</param>
        /// <returns>A provider path for the given component path.</returns>
        public static string ResolveKeyPath(SessionState session, string path)
        {
            if (session != null)
            {
                return session.Path.GetUnresolvedPSPathFromKeyPath(path);
            }

            return null;
        }
        public IAzureHDInsightConnectionSessionManager Create(SessionState sessionState)
        {
            if (singleton == null)
            {
                singleton = new AzureHDInsightConnectionSessionManagerSimulator();
            }

            return singleton;
        }
            /// <summary>
            ///
            /// </summary>
            /// <param name="literalPath"></param>
            /// <param name="session"></param>
            internal UnresolvedPscxPathImpl(string literalPath, SessionState session)
            {
                PscxArgumentException.ThrowIfIsNullOrEmpty(literalPath);
                PscxArgumentException.ThrowIfIsNull(session);

                _providerPath = session.Path.GetUnresolvedProviderPathFromPSPath(literalPath, out _providerInfo, out _driveInfo);
                _isUnresolved = true;
                _sourcePath = literalPath;
            }
Exemplo n.º 21
0
		internal static ADSessionInfo GetCurrentDriveSessionInfo(SessionState sessionState)
		{
			ADSessionInfo aDSessionInfo = null;
			ADDriveInfo current = sessionState.Drive.Current as ADDriveInfo;
			if (current != null)
			{
				aDSessionInfo = current.SessionInfo.Copy();
			}
			return aDSessionInfo;
		}
Exemplo n.º 22
0
 internal ProviderInfo(SessionState sessionState, Type implementingType, string name, string description, string home, string helpFile, PSSnapInInfo psSnapIn)
 {
     _sessionState = sessionState;
     PSSnapIn = psSnapIn;
     Name = name;
     Description = description;
     Home = home;
     ImplementingType = implementingType;
     Capabilities = GetCapabilities(implementingType);
     HelpFile = helpFile;
 }
Exemplo n.º 23
0
        private ExecutionContext()
        {
            // TODO: create a "Global Session state"
            if (_sessionStateGlobal == null)
                _sessionStateGlobal = new SessionStateGlobal(this);

            // TODO: initialize all the default settings
            _pipelineStack = new Stack<Pipeline>();
            _variables = new Dictionary<string, PSVariable>(StringComparer.CurrentCultureIgnoreCase);
            SessionState = new SessionState(_sessionStateGlobal);
        }
Exemplo n.º 24
0
 protected ProviderInfo(ProviderInfo providerInfo)
 {
     _sessionState = providerInfo._sessionState;
     PSSnapIn = providerInfo.PSSnapIn;
     Name = providerInfo.Name;
     Description = providerInfo.Description;
     Home = providerInfo.Home;
     ImplementingType = providerInfo.ImplementingType;
     Capabilities = providerInfo.Capabilities;
     HelpFile = providerInfo.HelpFile;
 }
Exemplo n.º 25
0
 internal PSModuleInfo(string path, string name, SessionState sessionState)
 {
     HasExplicitExports = false;
     Path = path;
     Name = name;
     SessionState = sessionState;
     ExportedVariables = new Dictionary<string, PSVariable>();
     ExportedFunctions = new Dictionary<string, FunctionInfo>();
     ExportedAliases = new Dictionary<string, AliasInfo>();
     ExportedCmdlets = new Dictionary<string, CmdletInfo>();
 }
Exemplo n.º 26
0
        private PSModuleInfo LoadModuleByPath(Path path)
        {
            // ALWAYS derive from global scope: the Scope parameter only defines where stuff is imported to
            var sessionState = new SessionState(_executionContext.SessionStateGlobal.RootSessionState);
            sessionState.IsScriptScope = true;
            sessionState.PSVariable.Set("PSScriptRoot", path.GetDirectory());
            var moduleInfo = new PSModuleInfo(path, path.GetFileNameWithoutExtension(), sessionState);
            sessionState.SetModule(moduleInfo);

            LoadFileIntoModule(moduleInfo, path);
            return moduleInfo;
        }
		/// <summary>
		/// Retrieve the dictonary with all connections from session
		/// </summary>
		/// <param name="sessionState">
		/// </param>
		/// <returns>
		/// The <see cref="Dictionary"/>.
		/// </returns>
		private static Dictionary<string, ComputeServiceConnection> GetComputeServiceConnectionsFromSession(
			SessionState sessionState)
		{
			if (sessionState == null)
				throw new ArgumentNullException("sessionState");

			PSVariable connectionsVariable = sessionState.PSVariable.Get(VariableNames.ComputeSessions);
			if (connectionsVariable == null)
				return null;

			var connections = (Dictionary<string, ComputeServiceConnection>) connectionsVariable.Value;
			return connections;
		}
Exemplo n.º 28
0
		private static IEnumerable<FunctionInfo> GetFunctions(SessionState sessionState)
		{
			try
			{
				var functionDrive = sessionState.InvokeProvider.Item.Get("function:");
				return (Dictionary<string, FunctionInfo>.ValueCollection)functionDrive[0].BaseObject;

			}
			catch (DriveNotFoundException)
			{
				return new FunctionInfo[] { };
			}
		}
Exemplo n.º 29
0
        //internal static PSObject GetPSObject(CmdletProvider provider, Item item)
        internal static PSObject GetPsObject(SessionState provider, Item item)
        {
            PSObject psobj = PSObject.AsPSObject(item);

            List<string> propertySet;
            if (allPropertySets.ContainsKey(item.TemplateID))
            {
                propertySet = allPropertySets[item.TemplateID];
            }
            else
            {
                item.Fields.ReadAll();
                propertySet = new List<string>(item.Fields.Count);
                foreach (Field field in item.Fields)
                {
                    if (field.Name != "ID") // don't map - native property
                    {
                        propertySet.Add(field.Name);
                    }
                }
                allPropertySets.Add(item.TemplateID, propertySet);
            }

            foreach (string field in propertySet)
            {
                if (!String.IsNullOrEmpty(field))
                {
                    bool duplicate = psobj.Properties[field] == null;
                    string getter = item.Fields[field] != null && item.Fields[field].TypeKey == "datetime"
                                        ? String.Format("[Sitecore.DateUtil]::IsoDateToDateTime($this[\"{0}\"])", field)
                                        : String.Format("$this[\"{0}\"]", field);
                    string setter =
                        String.Format("[{0}]::Modify($this, \"{1}\", $Args );",
                                      typeof (ItemShellExtensions).FullName, field);

                    psobj.Properties.Add(new PSScriptProperty(
                                             duplicate ? field : String.Format("_{0}", field),
                                             provider.InvokeCommand.NewScriptBlock(getter),
                                             provider.InvokeCommand.NewScriptBlock(setter)));
                }
            }

            foreach (string customGetter in customGetters.Keys)
            {
                psobj.Properties.Add(new PSScriptProperty(
                                         customGetter,
                                         provider.InvokeCommand.NewScriptBlock(customGetters[customGetter])));
            }

            return psobj;
        }
Exemplo n.º 30
0
        public static bool TryTranslatePSPath(SessionState session, string psPath, out string path, out bool? exists, out string errorMessage)
        {
            if (String.IsNullOrEmpty(psPath)) {
                throw new ArgumentException(
                    String.Format(
                        CultureInfo.CurrentCulture,
                        CommonResources.Argument_Cannot_Be_Null_Or_Empty, "psPath"));
            }

            bool succeeded = false;

            path = null;
            exists = null;
            errorMessage = null;

            if (!session.Path.IsValid(psPath)) {
                errorMessage = String.Format(
                    CultureInfo.CurrentCulture,
                    Resources.Cmdlet_InvalidPathSyntax, psPath);
            }
            else {
                try {
                    // we do not glob wildcards (literalpath.)
                    exists = session.InvokeProvider.Item.Exists(psPath, force: false, literalPath: true);

                    ProviderInfo provider;
                    PSDriveInfo drive;

                    // translate pspath, not trying to glob.
                    path = session.Path.GetUnresolvedProviderPathFromPSPath(psPath, out provider, out drive);

                    // ensure path is on the filesystem (not registry, certificate, variable etc.)
                    if (provider.ImplementingType != typeof (FileSystemProvider)) {
                        errorMessage = Resources.Cmdlet_InvalidProvider;
                    }
                    else {
                        succeeded = true;
                    }
                }
                catch (ProviderNotFoundException) {
                    errorMessage = Resources.Cmdlet_InvalidProvider;
                }
                catch (DriveNotFoundException ex) {
                    errorMessage = String.Format(
                        CultureInfo.CurrentCulture,
                        Resources.Cmdlet_InvalidPSDrive, ex.ItemName);
                }
            }
            return succeeded;
        }
Exemplo n.º 31
0
 internal static void ValidateAbsolutePath(SessionState state, string key, string[] paths, string filePath)
 {
     if (paths != null)
     {
         foreach (string str2 in paths)
         {
             string str;
             if (!state.Path.IsPSAbsolute(str2, out str))
             {
                 throw new InvalidOperationException(StringUtil.Format(RemotingErrorIdStrings.DISCPathsMustBeAbsolute, new object[] { key, str2, filePath }));
             }
         }
     }
 }
Exemplo n.º 32
0
        public static Endpoint TryGenerateEndpoint(this object obj, string id, System.Management.Automation.SessionState sessionState, object[] argumentList = null)
        {
            if (obj == null)
            {
                return(null);
            }

            if (obj is Endpoint endpoint)
            {
                endpoint.Name = id;
                return(endpoint);
            }

            if (obj is ScriptBlock scriptBlock)
            {
                return(GenerateCallback(scriptBlock, id, sessionState));
            }

            throw new Exception($"Expected UDEndpoint or ScriptBlock but got {obj.GetType()}");
        }
        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);
        }
Exemplo n.º 34
0
        internal PSModuleInfo CreateModule(string path, ExternalScriptInfo scriptInfo, IScriptExtent scriptPosition, SessionState ss, object privateData, params object[] arguments)
        {
            ArrayList list;

            return(this.CreateModuleImplementation(GetModuleName(path), path, scriptInfo, scriptPosition, ss, privateData, out list, arguments));
        }
Exemplo n.º 35
0
 internal PathInfo(PSDriveInfo drive, string path, SessionState sessionState)
 {
     Drive    = drive;
     Provider = drive == null ? null : drive.Provider;
     SetPathTypes(path, sessionState);
 }
Exemplo n.º 36
0
 internal ProviderInfo(SessionState sessionState, Type implementingType, string name, string description,
                       string home, string helpFile, PSSnapInInfo psSnapIn)
     : this(sessionState, implementingType, name, description, home, helpFile, psSnapIn, null)
 {
 }
Exemplo n.º 37
0
 internal ChildItemCmdletProviderIntrinsics(SessionState sessionState) : base(sessionState)
 {
 }
Exemplo n.º 38
0
        private PSModuleInfo CreateModuleImplementation(
            string name,
            string path,
            object moduleCode,
            Token callerToken,
            SessionState ss,
            out ArrayList result,
            params object[] arguments)
        {
            if (ss == null)
            {
                ss = new SessionState(this._context.EngineSessionState, true, true);
            }
            SessionStateInternal engineSessionState = this._context.EngineSessionState;
            PSModuleInfo         psModuleInfo       = new PSModuleInfo(name, path, this._context, ss);

            ss.Internal.Module = psModuleInfo;
            bool flag = false;
            int  num  = 0;

            try
            {
                ArrayList resultList = (ArrayList)null;
                this._context.EngineSessionState = ss.Internal;
                this._context.EngineSessionState.SetVariableValue("PSScriptRoot", (object)Path.GetDirectoryName(path), CommandOrigin.Internal);
                switch (moduleCode)
                {
                case ExternalScriptInfo externalScriptInfo:
                    this._context.EngineSessionState.SetVariableValue("MyInvocation", (object)new InvocationInfo((CommandInfo)externalScriptInfo, callerToken), CommandOrigin.Internal);
                    scriptBlock = externalScriptInfo.ScriptBlock;
                    break;

                case ScriptBlock scriptBlock:
                    scriptBlock = scriptBlock.Clone(true);
                    scriptBlock.SessionState = ss;
                    break;

                case string _:
                    scriptBlock = ScriptBlock.Create(this._context, (string)moduleCode);
                    break;
                }
                if (scriptBlock == null)
                {
                    throw ModuleIntrinsics.tracer.NewInvalidOperationException();
                }
                scriptBlock.SessionStateInternal = ss.Internal;
                try
                {
                    if (arguments == null)
                    {
                        scriptBlock.InvokeWithPipe(false, true, (object)AutomationNull.Value, (object)AutomationNull.Value, (object)AutomationNull.Value, (Pipe)null, ref resultList);
                    }
                    else
                    {
                        scriptBlock.InvokeWithPipe(false, true, (object)AutomationNull.Value, (object)AutomationNull.Value, (object)AutomationNull.Value, (Pipe)null, ref resultList, arguments);
                    }
                }
                catch (ExitException ex)
                {
                    num  = (int)ex.Argument;
                    flag = true;
                }
                result = resultList;
            }
            finally
            {
                this._context.EngineSessionState = engineSessionState;
            }
            if (flag)
            {
                this._context.SetVariable("global:LASTEXITCODE", (object)num);
            }
            return(psModuleInfo);
        }
Exemplo n.º 39
0
 /// <summary>
 /// Initializes a new instance of the LocationChangedEventArgs class.
 /// </summary>
 /// <param name="sessionState">
 /// The public session state instance associated with this runspace.
 /// </param>
 /// <param name="oldPath">
 /// The path we changed locations from.
 /// </param>
 /// <param name="newPath">
 /// The path we change locations to.
 /// </param>
 internal LocationChangedEventArgs(SessionState sessionState, PathInfo oldPath, PathInfo newPath)
 {
     SessionState = sessionState;
     OldPath      = oldPath;
     NewPath      = newPath;
 }
Exemplo n.º 40
0
 internal DriveManagementIntrinsics(SessionState sessionState, SessionStateScope <PSDriveInfo> driveScope)
 {
     _sessionState = sessionState;
     _scope        = driveScope;
 }
Exemplo n.º 41
0
 public bool MoveNext()
 {
     this._currentMatch = null;
     if (this.currentState == SearchState.SearchingAliases)
     {
         this._currentMatch = this.SearchForAliases();
         if ((this._currentMatch != null) && SessionState.IsVisible(this._commandOrigin, this._currentMatch))
         {
             return(true);
         }
         this._currentMatch = null;
         this.currentState  = SearchState.SearchingFunctions;
     }
     if (this.currentState == SearchState.SearchingFunctions)
     {
         this._currentMatch = this.SearchForFunctions();
         if (this._currentMatch != null)
         {
             return(true);
         }
         this.currentState = SearchState.SearchingCmdlets;
     }
     if (this.currentState == SearchState.SearchingCmdlets)
     {
         this._currentMatch = this.SearchForCmdlets();
         if (this._currentMatch != null)
         {
             return(true);
         }
         this.currentState = SearchState.SearchingBuiltinScripts;
     }
     if (this.currentState == SearchState.SearchingBuiltinScripts)
     {
         this._currentMatch = this.SearchForBuiltinScripts();
         if (this._currentMatch != null)
         {
             return(true);
         }
         this.currentState = SearchState.StartSearchingForExternalCommands;
     }
     if (this.currentState == SearchState.StartSearchingForExternalCommands)
     {
         if ((this.commandTypes & (CommandTypes.Application | CommandTypes.ExternalScript)) == 0)
         {
             return(false);
         }
         if ((this._commandOrigin == System.Management.Automation.CommandOrigin.Runspace) && (this.commandName.IndexOfAny(_pathSeparators) >= 0))
         {
             bool flag = false;
             if (((this._context.EngineSessionState.Applications.Count == 1) && this._context.EngineSessionState.Applications[0].Equals("*", StringComparison.OrdinalIgnoreCase)) || ((this._context.EngineSessionState.Scripts.Count == 1) && this._context.EngineSessionState.Scripts[0].Equals("*", StringComparison.OrdinalIgnoreCase)))
             {
                 flag = true;
             }
             else
             {
                 foreach (string str in this._context.EngineSessionState.Applications)
                 {
                     if (checkPath(str, this.commandName))
                     {
                         flag = true;
                         break;
                     }
                 }
                 if (!flag)
                 {
                     foreach (string str2 in this._context.EngineSessionState.Scripts)
                     {
                         if (checkPath(str2, this.commandName))
                         {
                             flag = true;
                             break;
                         }
                     }
                 }
             }
             if (!flag)
             {
                 return(false);
             }
         }
         this.currentState  = SearchState.PowerShellPathResolution;
         this._currentMatch = this.ProcessBuiltinScriptState();
         if (this._currentMatch != null)
         {
             this.currentState = SearchState.QualifiedFileSystemPath;
             return(true);
         }
     }
     if (this.currentState == SearchState.PowerShellPathResolution)
     {
         this.currentState  = SearchState.QualifiedFileSystemPath;
         this._currentMatch = this.ProcessPathResolutionState();
         if (this._currentMatch != null)
         {
             return(true);
         }
     }
     if ((this.currentState == SearchState.QualifiedFileSystemPath) || (this.currentState == SearchState.PathSearch))
     {
         this._currentMatch = this.ProcessQualifiedFileSystemState();
         if (this._currentMatch != null)
         {
             return(true);
         }
     }
     if (this.currentState == SearchState.PathSearch)
     {
         this.currentState  = SearchState.PowerShellRelativePath;
         this._currentMatch = this.ProcessPathSearchState();
         if (this._currentMatch != null)
         {
             return(true);
         }
     }
     return(false);
 }
Exemplo n.º 42
0
 internal PathIntrinsics(SessionState sessionState)
 {
     _sessionState       = sessionState;
     _sessionStateGlobal = sessionState.SessionStateGlobal;
 }
Exemplo n.º 43
0
 internal ProviderHelpProvider(HelpSystem helpSystem) : base(helpSystem)
 {
     this._helpFiles    = new Hashtable();
     this._sessionState = helpSystem.ExecutionContext.SessionState;
 }
Exemplo n.º 44
0
        /// <summary>
        /// Constructor for the ProviderInfo class.
        /// </summary>
        ///
        /// <param name="sessionState">
        /// The instance of session state that the provider is being added to.
        /// </param>
        ///
        /// <param name="implementingType">
        /// The type that implements the provider
        /// </param>
        ///
        /// <param name="name">
        /// The alternate name to use for the provider instead of the one specified
        /// in the .cmdletprovider file.
        /// </param>
        ///
        /// <param name="description">
        /// The description of the provider.
        /// </param>
        ///
        /// <param name="home">
        /// The home path for the provider. This must be an MSH path.
        /// </param>
        ///
        /// <param name="helpFile">
        /// The help file for the provider.
        /// </param>
        ///
        /// <param name="psSnapIn">
        /// The Snap-In for the provider.
        /// </param>
        ///
        /// <exception cref="ArgumentNullException">
        /// If <paramref name="implementingType"/> or <paramref name="sessionState"/> is null.
        /// </exception>
        ///
        /// <exception cref="ArgumentException">
        /// If <paramref name="name"/> is null or empty.
        /// </exception>
        ///
        internal ProviderInfo(
            SessionState sessionState,
            Type implementingType,
            string name,
            string description,
            string home,
            string helpFile,
            PSSnapInInfo psSnapIn)
        {
            // Verify parameters
            if (sessionState == null)
            {
                throw PSTraceSource.NewArgumentNullException("sessionState");
            }

            if (implementingType == null)
            {
                throw PSTraceSource.NewArgumentNullException("implementingType");
            }

            if (String.IsNullOrEmpty(name))
            {
                throw PSTraceSource.NewArgumentException("name");
            }


            if (String.IsNullOrEmpty(name))
            {
                throw PSTraceSource.NewArgumentException("name");
            }

            _sessionState = sessionState;

            Name = name;
            Description = description;
            Home = home;
            ImplementingType = implementingType;
            HelpFile = helpFile;
            PSSnapIn = psSnapIn;

#if SUPPORTS_CMDLETPROVIDER_FILE
            LoadProviderFromPath(path);
#endif
            // Create the hidden drive. The name doesn't really
            // matter since we are not adding this drive to a scope.

            _hiddenDrive =
                new PSDriveInfo(
                    this.FullName,
                    this,
                    "",
                    "",
                    null);

            _hiddenDrive.Hidden = true;

            // TODO:PSL
            // this is probably not right here
            if (implementingType == typeof(Microsoft.PowerShell.Commands.FileSystemProvider) && !Platform.IsWindows)
            {
                VolumeSeparatedByColon = false;
            }
        }
Exemplo n.º 45
0
 internal PSModuleInfo(string path, ExecutionContext context, SessionState sessionState)
     : this((string)null, path, context, sessionState)
 {
 }
Exemplo n.º 46
0
        private PSModuleInfo CreateModuleImplementation(string name, string path, object moduleCode, IScriptExtent scriptPosition, SessionState ss, object privateData, out ArrayList result, params object[] arguments)
        {
            if (ss == null)
            {
                ss = new SessionState(this._context, true, true);
            }
            SessionStateInternal engineSessionState = this._context.EngineSessionState;
            PSModuleInfo         info = new PSModuleInfo(name, path, this._context, ss);

            ss.Internal.Module = info;
            info.PrivateData   = privateData;
            bool flag     = false;
            int  newValue = 0;

            try
            {
                ScriptBlock scriptBlock;
                this._context.EngineSessionState = ss.Internal;
                ExternalScriptInfo scriptCommandInfo = moduleCode as ExternalScriptInfo;
                if (scriptCommandInfo != null)
                {
                    scriptBlock = scriptCommandInfo.ScriptBlock;
                    this._context.Debugger.RegisterScriptFile(scriptCommandInfo);
                }
                else
                {
                    scriptBlock = moduleCode as ScriptBlock;
                    if (scriptBlock != null)
                    {
                        PSLanguageMode?languageMode = scriptBlock.LanguageMode;
                        scriptBlock = scriptBlock.Clone(true);
                        scriptBlock.LanguageMode = languageMode;
                        scriptBlock.SessionState = ss;
                    }
                    else if (moduleCode is string)
                    {
                        scriptBlock = ScriptBlock.Create(this._context, (string)moduleCode);
                    }
                }
                if (scriptBlock == null)
                {
                    throw PSTraceSource.NewInvalidOperationException();
                }
                scriptBlock.SessionStateInternal = ss.Internal;
                InvocationInfo invocationInfo = new InvocationInfo(scriptCommandInfo, scriptPosition);
                info._definitionExtent = scriptBlock.Ast.Extent;
                ArrayList resultList = new ArrayList();
                try
                {
                    Pipe outputPipe = new Pipe(resultList);
                    scriptBlock.InvokeWithPipe(false, ScriptBlock.ErrorHandlingBehavior.WriteToCurrentErrorPipe, AutomationNull.Value, AutomationNull.Value, AutomationNull.Value, outputPipe, invocationInfo, arguments ?? new object[0]);
                }
                catch (ExitException exception)
                {
                    newValue = (int)exception.Argument;
                    flag     = true;
                }
                result = resultList;
            }
            finally
            {
                this._context.EngineSessionState = engineSessionState;
            }
            if (flag)
            {
                this._context.SetVariable(SpecialVariables.LastExitCodeVarPath, newValue);
            }
            return(info);
        }
Exemplo n.º 47
0
 // creates a new scope and sets the parent session state's scope as predecessor
 internal SessionState(SessionState parentSession)
     : this(parentSession.SessionStateGlobal, parentSession)
 {
 }
Exemplo n.º 48
0
 internal PSModuleInfo CreateModule(string name, string path, ScriptBlock scriptBlock, SessionState ss, out ArrayList results, params object[] arguments)
 {
     return(this.CreateModuleImplementation(name, path, scriptBlock, null, ss, null, out results, arguments));
 }
Exemplo n.º 49
0
        public static Endpoint GenerateCallback(this ScriptBlock endpoint, string id, System.Management.Automation.SessionState sessionState)
        {
            var logger = LogManager.GetLogger("CallbackCmdlet");

            var callback = new Endpoint();

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

            try
            {
                var variables = sessionState.InvokeCommand.InvokeScript("Get-Variable")
                                .Select(m => m.BaseObject)
                                .OfType <PSVariable>()
                                .Where(m =>
                                       !SkippedVariables.Any(x => x.Equals(m.Name, StringComparison.OrdinalIgnoreCase)) &&
                                       m.GetType().Name != "SessionStateCapacityVariable" &&
                                       m.GetType().Name != "NullVariable" &&
                                       m.GetType().Name != "QuestionMarkVariable" &&
                                       !((m.Options & ScopedItemOptions.AllScope) == ScopedItemOptions.AllScope || (m.Options & ScopedItemOptions.Constant) == ScopedItemOptions.Constant || (m.Options & ScopedItemOptions.ReadOnly) == ScopedItemOptions.ReadOnly))
                                .Select(m => new KeyValuePair <string, object>(m.Name, sessionState.PSVariable.GetValue(m.Name)))
                                .ToArray();

                // var property = sessionState.GetType().GetProperty("Internal", System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance);
                // var internalVariables = property.GetValue(sessionState, null);
                // var variableTable = internalVariables.GetType().GetMethod("GetVariableTable", System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance);
                // var variableTableInstance = variableTable.Invoke(internalVariables, null);

                callback.Variables = new Dictionary <string, object>();
                foreach (var variable in variables)
                {
                    if (callback.Variables.ContainsKey(variable.Key))
                    {
                        callback.Variables[variable.Key] = variable.Value;
                    }
                    else
                    {
                        callback.Variables.Add(variable.Key, variable.Value);
                    }
                }

                callback.Modules = sessionState.InvokeCommand.InvokeScript("Get-Module")
                                   .Select(m => m.BaseObject)
                                   .OfType <PSModuleInfo>()
                                   .Select(m => m.Path)
                                   .ToList();
            }
            catch (Exception ex)
            {
                logger.Error(ex, "Failed to look up variables.");
            }

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

            var dashboardService = sessionState.PSVariable.Get("DashboardService")?.Value as DashboardService;

            if (dashboardService != null)
            {
                dashboardService.EndpointService.Register(callback);
            }

            return(callback);
        }
Exemplo n.º 50
0
 internal ProviderInfo(SessionState sessionState, Type implementingType, string name, string helpFile, PSSnapInInfo psSnapIn) : this(sessionState, implementingType, name, string.Empty, string.Empty, helpFile, psSnapIn)
 {
 }
        public static Endpoint GenerateCallback(this ScriptBlock endpoint, string id, 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.InvokeCommand.InvokeScript($"Get-Variable -Name '{variableName}' -ErrorAction SilentlyContinue").Select(m => m.BaseObject).OfType <PSVariable>().FirstOrDefault();
                    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 dashboardService = sessionState.PSVariable.Get("DashboardService")?.Value as DashboardService;

            if (dashboardService != null)
            {
                dashboardService.EndpointService.Register(callback);
            }

            return(callback);
        }
Exemplo n.º 52
0
 // creates a new scope and sets the parent session state's scope as predecessor
 internal SessionState(SessionState parentSession)
     : this(parentSession.SessionStateGlobal, parentSession._functionScope,
            parentSession._variableScope, parentSession._driveScope, parentSession._aliasScope)
 {
 }
Exemplo n.º 53
0
 internal AliasHelpProvider(HelpSystem helpSystem) : base(helpSystem)
 {
     this._sessionState     = helpSystem.ExecutionContext.SessionState;
     this._commandDiscovery = helpSystem.ExecutionContext.CommandDiscovery;
     this._context          = helpSystem.ExecutionContext;
 }
Exemplo n.º 54
0
        public bool MoveNext()
        {
            bool flag1 = false;

            this._currentMatch = (CommandInfo)null;
            if (this.currentState == CommandSearcher.SearchState.Reset)
            {
                this._currentMatch = this.ProcessResetState();
                if (this._currentMatch != null && SessionState.IsVisible(this._commandOrigin, this._currentMatch))
                {
                    flag1 = true;
                    goto label_48;
                }
                else
                {
                    this.currentState = CommandSearcher.SearchState.AliasResolution;
                }
            }
            if (this.currentState == CommandSearcher.SearchState.AliasResolution)
            {
                this._currentMatch = this.ProcessAliasState();
                if (this._currentMatch != null)
                {
                    flag1 = true;
                    goto label_48;
                }
                else
                {
                    this.currentState = CommandSearcher.SearchState.FunctionResolution;
                }
            }
            if (this.currentState == CommandSearcher.SearchState.FunctionResolution)
            {
                this._currentMatch = this.ProcessFunctionState();
                if (this._currentMatch != null)
                {
                    flag1 = true;
                    goto label_48;
                }
                else
                {
                    this.currentState = CommandSearcher.SearchState.CmdletResolution;
                }
            }
            if (this.currentState == CommandSearcher.SearchState.CmdletResolution)
            {
                this._currentMatch = this.ProcessCmdletState();
                if (this._currentMatch != null)
                {
                    flag1 = true;
                    goto label_48;
                }
                else
                {
                    this.currentState = CommandSearcher.SearchState.BuiltinScriptResolution;
                }
            }
            if (this.currentState == CommandSearcher.SearchState.BuiltinScriptResolution)
            {
                if ((this.commandTypes & (CommandTypes.ExternalScript | CommandTypes.Application)) == (CommandTypes)0)
                {
                    flag1 = false;
                    goto label_48;
                }
                else
                {
                    if (this._commandOrigin == CommandOrigin.Runspace && this.commandName.IndexOfAny(this._pathSeparators) >= 0)
                    {
                        bool flag2 = false;
                        if (this._context.EngineSessionState.Applications.Count == 1 && this._context.EngineSessionState.Applications[0].Equals("*", StringComparison.OrdinalIgnoreCase) || this._context.EngineSessionState.Scripts.Count == 1 && this._context.EngineSessionState.Scripts[0].Equals("*", StringComparison.OrdinalIgnoreCase))
                        {
                            flag2 = true;
                        }
                        else
                        {
                            foreach (string application in this._context.EngineSessionState.Applications)
                            {
                                if (this.checkPath(application, this.commandName))
                                {
                                    flag2 = true;
                                    break;
                                }
                            }
                            if (!flag2)
                            {
                                foreach (string script in this._context.EngineSessionState.Scripts)
                                {
                                    if (this.checkPath(script, this.commandName))
                                    {
                                        flag2 = true;
                                        break;
                                    }
                                }
                            }
                        }
                        if (!flag2)
                        {
                            flag1 = false;
                            goto label_48;
                        }
                    }
                    this.currentState  = CommandSearcher.SearchState.PowerShellPathResolution;
                    this._currentMatch = this.ProcessBuiltinScriptState();
                    if (this._currentMatch != null)
                    {
                        this.currentState = CommandSearcher.SearchState.QualifiedFileSystemPath;
                        flag1             = true;
                        goto label_48;
                    }
                }
            }
            if (this.currentState == CommandSearcher.SearchState.PowerShellPathResolution)
            {
                this.currentState  = CommandSearcher.SearchState.QualifiedFileSystemPath;
                this._currentMatch = this.ProcessPathResolutionState();
                if (this._currentMatch != null)
                {
                    flag1 = true;
                    goto label_48;
                }
            }
            if (this.currentState == CommandSearcher.SearchState.QualifiedFileSystemPath || this.currentState == CommandSearcher.SearchState.PathSearch)
            {
                this._currentMatch = this.ProcessQualifiedFileSystemState();
                if (this._currentMatch != null)
                {
                    flag1 = true;
                    goto label_48;
                }
            }
            if (this.currentState == CommandSearcher.SearchState.PathSearch)
            {
                this.currentState  = CommandSearcher.SearchState.PowerShellRelativePath;
                this._currentMatch = this.ProcessPathSearchState();
                if (this._currentMatch != null)
                {
                    flag1 = true;
                }
            }
label_48:
            return(flag1);
        }