Пример #1
0
 private PathInfo ResolvePath(string pathToResolve, bool isLiteralPath, bool allowNonexistingPaths, PSCmdlet cmdlet)
 {
     CmdletProviderContext context = new CmdletProviderContext(cmdlet) {
         SuppressWildcardExpansion = isLiteralPath
     };
     Collection<PathInfo> targetObject = new Collection<PathInfo>();
     try
     {
         foreach (PathInfo info in cmdlet.SessionState.Path.GetResolvedPSPathFromPSPath(pathToResolve, context))
         {
             targetObject.Add(info);
         }
     }
     catch (PSNotSupportedException exception)
     {
         cmdlet.ThrowTerminatingError(new ErrorRecord(exception.ErrorRecord, exception));
     }
     catch (DriveNotFoundException exception2)
     {
         cmdlet.ThrowTerminatingError(new ErrorRecord(exception2.ErrorRecord, exception2));
     }
     catch (ProviderNotFoundException exception3)
     {
         cmdlet.ThrowTerminatingError(new ErrorRecord(exception3.ErrorRecord, exception3));
     }
     catch (ItemNotFoundException exception4)
     {
         if (allowNonexistingPaths)
         {
             ProviderInfo provider = null;
             PSDriveInfo drive = null;
             string path = cmdlet.SessionState.Path.GetUnresolvedProviderPathFromPSPath(pathToResolve, context, out provider, out drive);
             PathInfo item = new PathInfo(drive, provider, path, cmdlet.SessionState);
             targetObject.Add(item);
         }
         else
         {
             cmdlet.ThrowTerminatingError(new ErrorRecord(exception4.ErrorRecord, exception4));
         }
     }
     if (targetObject.Count == 1)
     {
         return targetObject[0];
     }
     Exception exception5 = PSTraceSource.NewNotSupportedException();
     cmdlet.ThrowTerminatingError(new ErrorRecord(exception5, "NotSupported", ErrorCategory.NotImplemented, targetObject));
     return null;
 }
Пример #2
0
        /// <summary>
        /// To generate Catalog for the folder
        /// </summary>
        /// <param name="Path"> Path to folder or File </param>
        /// <param name="catalogFilePath"> Catalog File Path </param>
        /// <param name="catalogVersion"> Catalog File Path </param>
        /// <param name="cmdlet"> Instance of cmdlet calling this method  </param>
        /// <returns> true if able to generate .cat file or false </returns>
        internal static FileInfo GenerateCatalog(PSCmdlet cmdlet, Collection <string> Path, string catalogFilePath, int catalogVersion)
        {
            _cmdlet = cmdlet;
            string hashAlgorithm = GetCatalogHashAlgorithm(catalogVersion);

            if (!String.IsNullOrEmpty(hashAlgorithm))
            {
                // Generate Path for Catalog Definition File
                string cdfFilePath = System.IO.Path.Combine(System.IO.Path.GetTempPath(), System.IO.Path.GetRandomFileName());
                cdfFilePath = cdfFilePath + ".cdf";
                try
                {
                    cdfFilePath = GenerateCDFFile(Path, catalogFilePath, cdfFilePath, catalogVersion, hashAlgorithm);

                    if (!File.Exists(cdfFilePath))
                    {
                        // If we are not able to generate catalog definition file we can not continue generating catalog
                        // throw PSTraceSource.NewInvalidOperationException("catalog", CatalogStrings.CatalogDefinitionFileNotGenerated);
                        ErrorRecord errorRecord = new ErrorRecord(new InvalidOperationException(CatalogStrings.CatalogDefinitionFileNotGenerated), "CatalogDefinitionFileNotGenerated", ErrorCategory.InvalidOperation, null);
                        _cmdlet.ThrowTerminatingError(errorRecord);
                    }

                    GenerateCatalogFile(cdfFilePath);
                    if (File.Exists(catalogFilePath))
                    {
                        return(new FileInfo(catalogFilePath));
                    }
                }
                finally
                {
                    File.Delete(cdfFilePath);
                }
            }
            return(null);
        }
Пример #3
0
 internal void IncrementModuleNestingDepth(PSCmdlet cmdlet, string path)
 {
     if (++this._moduleNestingDepth > 10)
     {
         InvalidOperationException exception = new InvalidOperationException(StringUtil.Format(Modules.ModuleTooDeeplyNested, path, 10));
         ErrorRecord errorRecord             = new ErrorRecord(exception, "Modules_ModuleTooDeeplyNested", ErrorCategory.InvalidOperation, path);
         cmdlet.ThrowTerminatingError(errorRecord);
     }
 }
Пример #4
0
        internal void IncrementModuleNestingDepth(PSCmdlet cmdlet, string path)
        {
            if (++this._moduleNestingDepth <= ModuleIntrinsics.MaxModuleNestingDepth)
            {
                return;
            }
            ErrorRecord errorRecord = new ErrorRecord((Exception) new InvalidOperationException(ResourceManagerCache.FormatResourceString("Modules", "ModuleTooDeeplyNested", (object)path, (object)ModuleIntrinsics.MaxModuleNestingDepth)), "Modules_ModuleTooDeeplyNested", ErrorCategory.InvalidOperation, (object)path);

            cmdlet.ThrowTerminatingError(errorRecord);
        }
Пример #5
0
        internal static DirectoryInfo CreateModuleDirectory(PSCmdlet cmdlet, string moduleNameOrPath, bool force)
        {
            DirectoryInfo targetObject = null;

            try
            {
                string str = ModuleCmdletBase.ResolveRootedFilePath(moduleNameOrPath, cmdlet.Context);
                if (string.IsNullOrEmpty(str) && moduleNameOrPath.StartsWith(".", StringComparison.OrdinalIgnoreCase))
                {
                    str = Path.Combine(cmdlet.CurrentProviderLocation(cmdlet.Context.ProviderNames.FileSystem).ProviderPath, moduleNameOrPath);
                }
                if (string.IsNullOrEmpty(str))
                {
                    str = Path.Combine(ModuleIntrinsics.GetPersonalModulePath(), moduleNameOrPath);
                }
                targetObject = new DirectoryInfo(str);
                if (targetObject.Exists)
                {
                    if (!force)
                    {
                        ErrorDetails details     = new ErrorDetails(string.Format(CultureInfo.InvariantCulture, PathUtilsStrings.ExportPSSession_ErrorDirectoryExists, new object[] { targetObject.FullName }));
                        ErrorRecord  errorRecord = new ErrorRecord(new ArgumentException(details.Message), "ExportProxyCommand_OutputDirectoryExists", ErrorCategory.ResourceExists, targetObject);
                        cmdlet.ThrowTerminatingError(errorRecord);
                    }
                    return(targetObject);
                }
                targetObject.Create();
            }
            catch (Exception exception)
            {
                CommandProcessorBase.CheckForSevereException(exception);
                ErrorDetails details2 = new ErrorDetails(string.Format(CultureInfo.InvariantCulture, PathUtilsStrings.ExportPSSession_CannotCreateOutputDirectory, new object[] { moduleNameOrPath, exception.Message }));
                ErrorRecord  record2  = new ErrorRecord(new ArgumentException(details2.Message, exception), "ExportProxyCommand_CannotCreateOutputDirectory", ErrorCategory.ResourceExists, moduleNameOrPath);
                cmdlet.ThrowTerminatingError(record2);
            }
            return(targetObject);
        }
 internal static GraphicalHostReflectionWrapper GetGraphicalHostReflectionWrapper(PSCmdlet parentCmdlet, string graphicalHostHelperTypeName, string featureName)
 {
     GraphicalHostReflectionWrapper wrapper = new GraphicalHostReflectionWrapper();
     if (IsInputFromRemoting(parentCmdlet))
     {
         ErrorRecord errorRecord = new ErrorRecord(new NotSupportedException(StringUtil.Format(HelpErrors.RemotingNotSupportedForFeature, featureName)), "RemotingNotSupported", ErrorCategory.InvalidOperation, parentCmdlet);
         parentCmdlet.ThrowTerminatingError(errorRecord);
     }
     AssemblyName assemblyRef = new AssemblyName {
         Name = "Microsoft.PowerShell.GraphicalHost",
         Version = new Version(3, 0, 0, 0),
         CultureInfo = new CultureInfo(string.Empty)
     };
     assemblyRef.SetPublicKeyToken(new byte[] { 0x31, 0xbf, 0x38, 0x56, 0xad, 0x36, 0x4e, 0x35 });
     try
     {
         wrapper.graphicalHostAssembly = Assembly.Load(assemblyRef);
     }
     catch (FileNotFoundException exception)
     {
         string message = StringUtil.Format(HelpErrors.GraphicalHostAssemblyIsNotFound, featureName, exception.Message);
         parentCmdlet.ThrowTerminatingError(new ErrorRecord(new NotSupportedException(message, exception), "ErrorLoadingAssembly", ErrorCategory.ObjectNotFound, assemblyRef));
     }
     catch (Exception exception2)
     {
         CommandProcessorBase.CheckForSevereException(exception2);
         parentCmdlet.ThrowTerminatingError(new ErrorRecord(exception2, "ErrorLoadingAssembly", ErrorCategory.ObjectNotFound, assemblyRef));
     }
     wrapper.graphicalHostHelperType = wrapper.graphicalHostAssembly.GetType(graphicalHostHelperTypeName);
     ConstructorInfo info = wrapper.graphicalHostHelperType.GetConstructor(BindingFlags.NonPublic | BindingFlags.Instance, null, new Type[0], null);
     if (info != null)
     {
         wrapper.graphicalHostHelperObject = info.Invoke(new object[0]);
     }
     return wrapper;
 }
Пример #7
0
 internal static DirectoryInfo CreateModuleDirectory(PSCmdlet cmdlet, string moduleNameOrPath, bool force)
 {
     DirectoryInfo targetObject = null;
     try
     {
         string str = ModuleCmdletBase.ResolveRootedFilePath(moduleNameOrPath, cmdlet.Context);
         if (string.IsNullOrEmpty(str) && moduleNameOrPath.StartsWith(".", StringComparison.OrdinalIgnoreCase))
         {
             str = Path.Combine(cmdlet.CurrentProviderLocation(cmdlet.Context.ProviderNames.FileSystem).ProviderPath, moduleNameOrPath);
         }
         if (string.IsNullOrEmpty(str))
         {
             str = Path.Combine(ModuleIntrinsics.GetPersonalModulePath(), moduleNameOrPath);
         }
         targetObject = new DirectoryInfo(str);
         if (targetObject.Exists)
         {
             if (!force)
             {
                 ErrorDetails details = new ErrorDetails(string.Format(CultureInfo.InvariantCulture, PathUtilsStrings.ExportPSSession_ErrorDirectoryExists, new object[] { targetObject.FullName }));
                 ErrorRecord errorRecord = new ErrorRecord(new ArgumentException(details.Message), "ExportProxyCommand_OutputDirectoryExists", ErrorCategory.ResourceExists, targetObject);
                 cmdlet.ThrowTerminatingError(errorRecord);
             }
             return targetObject;
         }
         targetObject.Create();
     }
     catch (Exception exception)
     {
         CommandProcessorBase.CheckForSevereException(exception);
         ErrorDetails details2 = new ErrorDetails(string.Format(CultureInfo.InvariantCulture, PathUtilsStrings.ExportPSSession_CannotCreateOutputDirectory, new object[] { moduleNameOrPath, exception.Message }));
         ErrorRecord record2 = new ErrorRecord(new ArgumentException(details2.Message, exception), "ExportProxyCommand_CannotCreateOutputDirectory", ErrorCategory.ResourceExists, moduleNameOrPath);
         cmdlet.ThrowTerminatingError(record2);
     }
     return targetObject;
 }
Пример #8
0
        internal static void MasterStreamOpen(PSCmdlet cmdlet, string filePath, Encoding resolvedEncoding, bool defaultEncoding, bool Append, bool Force, bool NoClobber, out FileStream fileStream, out StreamWriter streamWriter, out FileInfo readOnlyFileInfo, bool isLiteralPath)
        {
            fileStream       = null;
            streamWriter     = null;
            readOnlyFileInfo = null;
            string path = ResolveFilePath(filePath, cmdlet, isLiteralPath);

            try
            {
                FileMode create = FileMode.Create;
                if (Append)
                {
                    create = FileMode.Append;
                }
                else if (NoClobber)
                {
                    create = FileMode.CreateNew;
                }
                if ((Force && (Append || !NoClobber)) && File.Exists(path))
                {
                    FileInfo info = new FileInfo(path);
                    if ((info.Attributes & System.IO.FileAttributes.ReadOnly) == System.IO.FileAttributes.ReadOnly)
                    {
                        readOnlyFileInfo = info;
                        info.Attributes &= ~System.IO.FileAttributes.ReadOnly;
                    }
                }
                FileShare share = Force ? FileShare.ReadWrite : FileShare.Read;
                fileStream = new FileStream(path, create, FileAccess.Write, share);
                if (defaultEncoding)
                {
                    streamWriter = new StreamWriter(fileStream);
                }
                else
                {
                    streamWriter = new StreamWriter(fileStream, resolvedEncoding);
                }
            }
            catch (ArgumentException exception)
            {
                ReportFileOpenFailure(cmdlet, path, exception);
            }
            catch (IOException exception2)
            {
                if (NoClobber && File.Exists(path))
                {
                    ErrorRecord errorRecord = new ErrorRecord(exception2, "NoClobber", ErrorCategory.ResourceExists, path)
                    {
                        ErrorDetails = new ErrorDetails(cmdlet, "PathUtilsStrings", "UtilityFileExistsNoClobber", new object[] { filePath, "NoClobber" })
                    };
                    cmdlet.ThrowTerminatingError(errorRecord);
                }
                ReportFileOpenFailure(cmdlet, path, exception2);
            }
            catch (UnauthorizedAccessException exception3)
            {
                ReportFileOpenFailure(cmdlet, path, exception3);
            }
            catch (NotSupportedException exception4)
            {
                ReportFileOpenFailure(cmdlet, path, exception4);
            }
            catch (SecurityException exception5)
            {
                ReportFileOpenFailure(cmdlet, path, exception5);
            }
        }
Пример #9
0
        internal static void MasterStreamOpen(
            PSCmdlet cmdlet,
            string filePath,
            string encoding,
            bool defaultEncoding,
            bool Append,
            bool Force,
            bool NoClobber,
            out FileStream fileStream,
            out StreamWriter streamWriter,
            out FileInfo readOnlyFileInfo)
        {
            fileStream       = (FileStream)null;
            streamWriter     = (StreamWriter)null;
            readOnlyFileInfo = (FileInfo)null;
            string   str       = PathUtils.ResolveFilePath(filePath, cmdlet);
            Encoding encoding1 = EncodingConversion.Convert((Cmdlet)cmdlet, encoding);

            try
            {
                FileMode mode = FileMode.Create;
                if (Append)
                {
                    mode = FileMode.Append;
                }
                else if (NoClobber)
                {
                    mode = FileMode.CreateNew;
                }
                if (Force && (Append || !NoClobber) && File.Exists(str))
                {
                    FileInfo fileInfo = new FileInfo(str);
                    if ((fileInfo.Attributes & FileAttributes.ReadOnly) == FileAttributes.ReadOnly)
                    {
                        readOnlyFileInfo     = fileInfo;
                        fileInfo.Attributes &= ~FileAttributes.ReadOnly;
                    }
                }
                FileShare share = Force ? FileShare.ReadWrite : FileShare.Read;
                fileStream = new FileStream(str, mode, FileAccess.Write, share);
                if (defaultEncoding)
                {
                    streamWriter = new StreamWriter((Stream)fileStream);
                }
                else
                {
                    streamWriter = new StreamWriter((Stream)fileStream, encoding1);
                }
            }
            catch (ArgumentException ex)
            {
                PathUtils.ReportFileOpenFailure((Cmdlet)cmdlet, str, (Exception)ex);
            }
            catch (IOException ex)
            {
                if (NoClobber && File.Exists(str))
                {
                    cmdlet.ThrowTerminatingError(new ErrorRecord((Exception)ex, nameof(NoClobber), ErrorCategory.ResourceExists, (object)str)
                    {
                        ErrorDetails = new ErrorDetails((Cmdlet)cmdlet, nameof(PathUtils), "UtilityFileExistsNoClobber", new object[2]
                        {
                            (object)filePath,
                            (object)nameof(NoClobber)
                        })
                    });
                }
                PathUtils.ReportFileOpenFailure((Cmdlet)cmdlet, str, (Exception)ex);
            }
            catch (UnauthorizedAccessException ex)
            {
                PathUtils.ReportFileOpenFailure((Cmdlet)cmdlet, str, (Exception)ex);
            }
            catch (NotSupportedException ex)
            {
                PathUtils.ReportFileOpenFailure((Cmdlet)cmdlet, str, (Exception)ex);
            }
            catch (SecurityException ex)
            {
                PathUtils.ReportFileOpenFailure((Cmdlet)cmdlet, str, (Exception)ex);
            }
        }
Пример #10
0
 internal static void MasterStreamOpen(PSCmdlet cmdlet, string filePath, Encoding resolvedEncoding, bool defaultEncoding, bool Append, bool Force, bool NoClobber, out FileStream fileStream, out StreamWriter streamWriter, out FileInfo readOnlyFileInfo, bool isLiteralPath)
 {
     fileStream = null;
     streamWriter = null;
     readOnlyFileInfo = null;
     string path = ResolveFilePath(filePath, cmdlet, isLiteralPath);
     try
     {
         FileMode create = FileMode.Create;
         if (Append)
         {
             create = FileMode.Append;
         }
         else if (NoClobber)
         {
             create = FileMode.CreateNew;
         }
         if ((Force && (Append || !NoClobber)) && File.Exists(path))
         {
             FileInfo info = new FileInfo(path);
             if ((info.Attributes & System.IO.FileAttributes.ReadOnly) == System.IO.FileAttributes.ReadOnly)
             {
                 readOnlyFileInfo = info;
                 info.Attributes &= ~System.IO.FileAttributes.ReadOnly;
             }
         }
         FileShare share = Force ? FileShare.ReadWrite : FileShare.Read;
         fileStream = new FileStream(path, create, FileAccess.Write, share);
         if (defaultEncoding)
         {
             streamWriter = new StreamWriter(fileStream);
         }
         else
         {
             streamWriter = new StreamWriter(fileStream, resolvedEncoding);
         }
     }
     catch (ArgumentException exception)
     {
         ReportFileOpenFailure(cmdlet, path, exception);
     }
     catch (IOException exception2)
     {
         if (NoClobber && File.Exists(path))
         {
             ErrorRecord errorRecord = new ErrorRecord(exception2, "NoClobber", ErrorCategory.ResourceExists, path) {
                 ErrorDetails = new ErrorDetails(cmdlet, "PathUtilsStrings", "UtilityFileExistsNoClobber", new object[] { filePath, "NoClobber" })
             };
             cmdlet.ThrowTerminatingError(errorRecord);
         }
         ReportFileOpenFailure(cmdlet, path, exception2);
     }
     catch (UnauthorizedAccessException exception3)
     {
         ReportFileOpenFailure(cmdlet, path, exception3);
     }
     catch (NotSupportedException exception4)
     {
         ReportFileOpenFailure(cmdlet, path, exception4);
     }
     catch (SecurityException exception5)
     {
         ReportFileOpenFailure(cmdlet, path, exception5);
     }
 }
Пример #11
0
        /// <summary>
        /// THE method for opening a file for writing.  
        /// Should be used by all cmdlets that write to a file.
        /// </summary>
        /// <param name="cmdlet">cmdlet that is opening the file (used mainly for error reporting)</param>
        /// <param name="filePath">path to the file (as specified on the command line - this method will resolve the path)</param>
        /// <param name="resolvedEncoding">encoding (this method will convert the command line string to an Encoding instance)</param>
        /// <param name="defaultEncoding">if <c>true</c>, then we will use default .NET encoding instead of the encoding specified in <paramref name="encoding"/> parameter</param>
        /// <param name="Append"></param>
        /// <param name="Force"></param>
        /// <param name="NoClobber"></param>
        /// <param name="fileStream">Result1: <see cref="FileStream"/> opened for writing</param>
        /// <param name="streamWriter">Result2: <see cref="StreamWriter"/> (inherits from <see cref="TextWriter"/>) opened for writing</param>
        /// <param name="readOnlyFileInfo">Result3: file info that should be used to restore file attributes after done with the file (<c>null</c> is this is not needed)</param>
        /// <param name="isLiteralPath">True if wildcard expansion should be bypassed.</param>
        internal static void MasterStreamOpen(
            PSCmdlet cmdlet,
            string filePath,
            Encoding resolvedEncoding,
            bool defaultEncoding,
            bool Append,
            bool Force,
            bool NoClobber,
            out FileStream fileStream,
            out StreamWriter streamWriter,
            out FileInfo readOnlyFileInfo,
            bool isLiteralPath)
        {
            fileStream = null;
            streamWriter = null;
            readOnlyFileInfo = null;

            // resolve the path and the encoding
            string resolvedPath = ResolveFilePath(filePath, cmdlet, isLiteralPath);

            try
            {
                // variable to track file open mode
                // this is controlled by append/force parameters
                FileMode mode = FileMode.Create;
                if (Append)
                {
                    mode = FileMode.Append;
                }
                else if (NoClobber)
                {
                    // throw IOException if file exists
                    mode = FileMode.CreateNew;
                }

                if (Force && (Append || !NoClobber))
                {
                    if (File.Exists(resolvedPath))
                    {
                        FileInfo fInfo = new FileInfo(resolvedPath);
                        if ((fInfo.Attributes & FileAttributes.ReadOnly) == FileAttributes.ReadOnly)
                        {
                            // remember to reset the read-only attribute later
                            readOnlyFileInfo = fInfo;
                            // Clear the read-only attribute
                            fInfo.Attributes &= ~(FileAttributes.ReadOnly);
                        }
                    }
                }

                // if the user knows what he/she is doing and uses "-Force" switch,
                // then we let more than 1 process write to the same file at the same time
                FileShare fileShare = Force ? FileShare.ReadWrite : FileShare.Read;

                // mode is controlled by force and ShouldContinue()
                fileStream = new FileStream(resolvedPath, mode, FileAccess.Write, fileShare);

                // create stream writer
                // NTRAID#Windows Out Of Band Releases-931008-2006/03/27
                // For some reason, calling this without specifying
                // the encoding is different from passing Encoding.Default.
                if (defaultEncoding)
                    streamWriter = new StreamWriter(fileStream);
                else
                    streamWriter = new StreamWriter(fileStream, resolvedEncoding);
            }
            // These are the known exceptions for File.Load and StreamWriter.ctor
            catch (ArgumentException e)
            {
                // NOTE: this call will throw
                ReportFileOpenFailure(cmdlet, resolvedPath, e);
            }
            catch (IOException e)
            {
                if (NoClobber && File.Exists(resolvedPath))
                {
                    // This probably happened because the file already exists
                    ErrorRecord errorRecord = new ErrorRecord(
                        e, "NoClobber", ErrorCategory.ResourceExists, resolvedPath);
                    errorRecord.ErrorDetails = new ErrorDetails(
                        cmdlet,
                        "PathUtilsStrings",
                        "UtilityFileExistsNoClobber",
                        filePath,
                        "NoClobber"); // prevents localization

                    // NOTE: this call will throw
                    cmdlet.ThrowTerminatingError(errorRecord);
                }
                // NOTE: this call will throw
                ReportFileOpenFailure(cmdlet, resolvedPath, e);
            }
            catch (UnauthorizedAccessException e)
            {
                // NOTE: this call will throw
                ReportFileOpenFailure(cmdlet, resolvedPath, e);
            }
            catch (NotSupportedException e)
            {
                // NOTE: this call will throw
                ReportFileOpenFailure(cmdlet, resolvedPath, e);
            }
            catch (System.Security.SecurityException e)
            {
                // NOTE: this call will throw
                ReportFileOpenFailure(cmdlet, resolvedPath, e);
            }
        } // void MasterStreamOpen
Пример #12
0
        internal static void ResetMachineAccountPassword(string domain, string localMachineName, string server, PSCredential credential, PSCmdlet cmdlet)
        {
            // Get domain directory entry and reset the password on the machine account of the local machine
            string newPassword = null;
            string domainOrServerName = server ?? domain;

            try
            {
                string dUserName = credential != null ? credential.UserName : null;
                string dPassword = credential != null ? Utils.GetStringFromSecureString(credential.Password) : null;

                using (var domainEntry = new DirectoryEntry(
                       "LDAP://" + domainOrServerName,
                       dUserName,
                       dPassword,
                       AuthenticationTypes.Secure))
                {
                    using (var searcher = new DirectorySearcher(domainEntry))
                    {
                        searcher.Filter = "(&(objectClass=computer)(|(cn=" + localMachineName + ")(dn=" + localMachineName + ")))";
                        SearchResult result = searcher.FindOne();

                        if (result == null)
                        {
                            string format = server != null
                                                ? ComputerResources.CannotFindMachineAccountFromServer
                                                : ComputerResources.CannotFindMachineAccountFromDomain;
                            string errMsg = StringUtil.Format(format, domainOrServerName);
                            ErrorRecord error = new ErrorRecord(new InvalidOperationException(errMsg), "CannotFindMachineAccount",
                                                                ErrorCategory.OperationStopped, localMachineName);
                            cmdlet.ThrowTerminatingError(error);
                        }
                        else
                        {
                            // Generate a random password of length 120, and reset the password on the machine account
                            using (var targetEntry = result.GetDirectoryEntry())
                            {
                                newPassword = ComputerWMIHelper.GetRandomPassword(PasswordLength);
                                targetEntry.Invoke("SetPassword", new object[] { newPassword });
                                targetEntry.Properties["LockOutTime"].Value = 0;
                            }
                        }
                    }
                }
            }
            catch (DirectoryServicesCOMException ex)
            {
                string errMsg = StringUtil.Format(ComputerResources.FailToResetPasswordOnDomain, ex.Message);
                ErrorRecord error = new ErrorRecord(new InvalidOperationException(errMsg), "FailToResetPasswordOnDomain",
                                                    ErrorCategory.OperationStopped, localMachineName);
                cmdlet.ThrowTerminatingError(error);
            }
            catch (TargetInvocationException ex)
            {
                string errMsg = StringUtil.Format(ComputerResources.FailToResetPasswordOnDomain, ex.InnerException.Message);
                ErrorRecord error = new ErrorRecord(new InvalidOperationException(errMsg), "FailToResetPasswordOnDomain",
                                                    ErrorCategory.OperationStopped, localMachineName);
                cmdlet.ThrowTerminatingError(error);
            }
            catch (COMException ex)
            {
                string errMsg = StringUtil.Format(ComputerResources.FailToResetPasswordOnDomain, ex.Message);
                ErrorRecord error = new ErrorRecord(new InvalidOperationException(errMsg), "FailToResetPasswordOnDomain",
                                                    ErrorCategory.OperationStopped, localMachineName);
                cmdlet.ThrowTerminatingError(error);
            }

            // Set the same password to the local machine
            Dbg.Diagnostics.Assert(newPassword != null, "the newPassword should not be null at this point");

            // A direct translation of function NetpManageMachineSecret2 in //depot/winmain/ds/netapi/netjoin/joinutl.c
            // Initialize the LSA_OBJECT_ATTRIBUTES
            var lsaAttr = new SAMAPI.LSA_OBJECT_ATTRIBUTES();
            lsaAttr.RootDirectory = IntPtr.Zero;
            lsaAttr.ObjectName = IntPtr.Zero;
            lsaAttr.Attributes = 0;
            lsaAttr.SecurityDescriptor = IntPtr.Zero;
            lsaAttr.SecurityQualityOfService = IntPtr.Zero;
            lsaAttr.Length = Marshal.SizeOf(typeof(SAMAPI.LSA_OBJECT_ATTRIBUTES));

            // Initialize the policy handle and secret handle
            IntPtr policyHandle = IntPtr.Zero;
            IntPtr secretHandle = IntPtr.Zero;

            // Initialize variables for LsaQuerySecret call
            IntPtr currentPassword = IntPtr.Zero;

            // Declare the key, newData and currentData
            var key = new SAMAPI.LSA_UNICODE_STRING { Buffer = IntPtr.Zero };
            var newData = new SAMAPI.LSA_UNICODE_STRING { Buffer = IntPtr.Zero };

            // Initialize the systemName for the localhost
            var localhost = new SAMAPI.LSA_UNICODE_STRING();
            localhost.Buffer = IntPtr.Zero;
            localhost.Length = 0;
            localhost.MaximumLength = 0;

            try
            {
                // Open the LSA policy
                uint ret = SAMAPI.LsaOpenPolicy(ref localhost, ref lsaAttr, (int)SAMAPI.LSA_ACCESS.AllAccess, out policyHandle);
                if (ret == STATUS_ACCESS_DENIED)
                {
                    string errMsg = ComputerResources.NeedAdminPrivilegeToResetPassword;
                    ErrorRecord error = new ErrorRecord(new InvalidOperationException(errMsg), "UnauthorizedAccessException",
                                                        ErrorCategory.InvalidOperation, localMachineName);
                    cmdlet.ThrowTerminatingError(error);
                }
                if (ret != 0)
                {
                    ThrowOutLsaError(ret, cmdlet);
                }

                // Initialize secret key, new secret
                SAMAPI.InitLsaString(SecretKey, ref key);
                SAMAPI.InitLsaString(newPassword, ref newData);
                bool secretCreated = false;

                // Open the secret. If the secret is not found, create the secret
                ret = SAMAPI.LsaOpenSecret(policyHandle, ref key, SECRET_SET_VALUE | SECRET_QUERY_VALUE, out secretHandle);
                if (ret == STATUS_OBJECT_NAME_NOT_FOUND)
                {
                    ret = SAMAPI.LsaCreateSecret(policyHandle, ref key, SECRET_SET_VALUE, out secretHandle);
                    secretCreated = true;
                }
                if (ret != 0)
                {
                    ThrowOutLsaError(ret, cmdlet);
                }

                SAMAPI.LSA_UNICODE_STRING currentData;
                // Get the current password
                if (secretCreated)
                {
                    // Use the new password as the current one
                    currentData = newData;
                }
                else
                {
                    // Query for the current password
                    ret = SAMAPI.LsaQuerySecret(secretHandle, out currentPassword, IntPtr.Zero, IntPtr.Zero, IntPtr.Zero);
                    if (ret != 0)
                    {
                        ThrowOutLsaError(ret, cmdlet);
                    }

                    currentData = (SAMAPI.LSA_UNICODE_STRING)Marshal.PtrToStructure(currentPassword, typeof(SAMAPI.LSA_UNICODE_STRING));
                }

                ret = SAMAPI.LsaSetSecret(secretHandle, ref newData, ref currentData);
                if (ret != 0)
                {
                    ThrowOutLsaError(ret, cmdlet);
                }
            }
            finally
            {
                // Release pointers
                if (currentPassword != IntPtr.Zero)
                {
                    int releaseResult = SAMAPI.LsaFreeMemory(currentPassword);
                    Dbg.Diagnostics.Assert(releaseResult == 0, "LsaFreeMemory returned non-zero value");
                }

                // Release handles
                if (policyHandle != IntPtr.Zero)
                {
                    int releaseResult = SAMAPI.LsaClose(policyHandle);
                    Dbg.Diagnostics.Assert(releaseResult == 0, "LsaClose returned non-zero value");
                }

                if (secretHandle != IntPtr.Zero)
                {
                    int releaseResult = SAMAPI.LsaClose(secretHandle);
                    Dbg.Diagnostics.Assert(releaseResult == 0, "LsaClose returned non-zero value");
                }

                // Release LSA_UNICODE_STRING
                SAMAPI.FreeLsaString(ref key);
                SAMAPI.FreeLsaString(ref newData);
            }
        }
        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)
            {
                CommandProcessorBase.CheckForSevereException(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;
        }
        /// <summary>
        /// Combines an array of strings or hashtables into a single string block
        /// </summary>
        internal static string CombineHashTableOrStringArray(object[] values, StreamWriter writer, PSCmdlet caller)
        {
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < values.Length; i++)
            {
                string strVal = values[i] as string;
                if (!String.IsNullOrEmpty(strVal))
                {
                    sb.Append(QuoteName(strVal));
                }
                else
                {
                    Hashtable hashVal = values[i] as Hashtable;
                    if (null == hashVal)
                    {
                        string message = StringUtil.Format(RemotingErrorIdStrings.DISCTypeMustBeStringOrHashtableArray,
                                                           ConfigFileConstants.ModulesToImport);
                        PSArgumentException e = new PSArgumentException(message);
                        caller.ThrowTerminatingError(e.ErrorRecord);
                    }
                    sb.Append(CombineHashtable(hashVal, writer));
                }

                if (i < (values.Length - 1))
                {
                    sb.Append(", ");
                }
            }

            return sb.ToString();
        }
Пример #15
0
        internal static void MasterStreamOpen(
			PSCmdlet cmdlet,
			string filePath,
			Encoding resolvedEncoding,
			bool defaultEncoding,
			bool append,
			bool force,
			bool noClobber,
			out FileStream fileStream,
			out StreamWriter streamWriter,
			out FileInfo readOnlyFileInfo,
			bool isLiteralPath)
        {
            fileStream = null;
            streamWriter = null;
            readOnlyFileInfo = null;
            var str = ResolveFilePath(filePath, cmdlet, isLiteralPath);
            try
            {
                var mode = FileMode.Create;
                if (append)
                {
                    mode = FileMode.Append;
                }
                else if (noClobber)
                {
                    mode = FileMode.CreateNew;
                }
                if (force && (append || !noClobber) && File.Exists(str))
                {
                    var fileInfo1 = new FileInfo(str);
                    if ((fileInfo1.Attributes & FileAttributes.ReadOnly) == FileAttributes.ReadOnly)
                    {
                        readOnlyFileInfo = fileInfo1;
                        var fileInfo2 = fileInfo1;
                        var num = (int) (fileInfo2.Attributes & ~FileAttributes.ReadOnly);
                        fileInfo2.Attributes = (FileAttributes) num;
                    }
                }
                var share = force ? FileShare.ReadWrite : FileShare.Read;
                fileStream = new FileStream(str, mode, FileAccess.Write, share);
                streamWriter = defaultEncoding
                    ? new StreamWriter(fileStream)
                    : new StreamWriter(fileStream, resolvedEncoding);
            }
            catch (ArgumentException ex)
            {
                ReportFileOpenFailure(cmdlet, str, ex);
            }
            catch (IOException ex)
            {
                if (noClobber && File.Exists(str))
                {
                    cmdlet.ThrowTerminatingError(
                        new ErrorRecord(ex, "NoClobber", ErrorCategory.ResourceExists, str)
                        {
                            ErrorDetails =
                                new ErrorDetails(
                                    cmdlet,
                                    "PathUtilsStrings",
                                    "UtilityFileExistsNoClobber",
                                    new object[]
                                    {
                                        filePath,
                                        "NoClobber"
                                    })
                        });
                }
                ReportFileOpenFailure(cmdlet, str, ex);
            }
            catch (UnauthorizedAccessException ex)
            {
                ReportFileOpenFailure(cmdlet, str, ex);
            }
            catch (NotSupportedException ex)
            {
                ReportFileOpenFailure(cmdlet, str, ex);
            }
            catch (SecurityException ex)
            {
                ReportFileOpenFailure(cmdlet, str, ex);
            }
        }
Пример #16
0
        /// <summary>
        /// To generate Catalog for the folder 
        /// </summary>
        ///
        /// <param name="Path"> Path to folder or File </param> 
        /// <param name="catalogFilePath"> Catalog File Path </param>        
        /// <param name="catalogVersion"> Catalog File Path </param>      
        /// <param name="cmdlet"> Instance of cmdlet calling this method  </param>
        /// <returns> true if able to generate .cat file or false </returns>
        internal static FileInfo GenerateCatalog(PSCmdlet cmdlet, Collection<string> Path, string catalogFilePath, int catalogVersion)
        {
            _cmdlet = cmdlet;
            string hashAlgorithm = GetCatalogHashAlgorithm(catalogVersion);

            if (!String.IsNullOrEmpty(hashAlgorithm))
            {
                // Generate Path for Catalog Definition File 
                string cdfFilePath = System.IO.Path.Combine(System.IO.Path.GetTempPath(), System.IO.Path.GetRandomFileName());
                cdfFilePath = cdfFilePath + ".cdf";
                try
                {
                    cdfFilePath = GenerateCDFFile(Path, catalogFilePath, cdfFilePath, catalogVersion, hashAlgorithm);

                    if (!File.Exists(cdfFilePath))
                    {
                        // If we are not able to generate catalog definition file we can not continue generating catalog 
                        // throw PSTraceSource.NewInvalidOperationException("catalog", CatalogStrings.CatalogDefinitionFileNotGenerated);                    
                        ErrorRecord errorRecord = new ErrorRecord(new InvalidOperationException(CatalogStrings.CatalogDefinitionFileNotGenerated), "CatalogDefinitionFileNotGenerated", ErrorCategory.InvalidOperation, null);
                        _cmdlet.ThrowTerminatingError(errorRecord);
                    }

                    GenerateCatalogFile(cdfFilePath);
                    if (File.Exists(catalogFilePath))
                    {
                        return new FileInfo(catalogFilePath);
                    }
                }
                finally
                {
                    File.Delete(cdfFilePath);
                }
            }
            return null;
        }
Пример #17
0
        /// <summary>
        /// Resolves the specified path to PathInfo objects
        /// </summary>
        /// 
        /// <param name="pathToResolve">
        /// The path to be resolved. Each path may contain glob characters.
        /// </param>
        /// 
        /// <param name="isLiteralPath">
        /// True if wildcard expansion should be suppressed for pathToResolve.
        /// </param>
        /// 
        /// <param name="allowNonexistingPaths">
        /// If true, resolves the path even if it doesn't exist.
        /// </param>
        /// 
        /// <param name="cmdlet">
        /// Calling cmdlet
        /// </param>
        /// 
        /// <returns>
        /// A string representing the resolved path.
        /// </returns>
        /// 
        private static PathInfo ResolvePath(
            string pathToResolve,
            bool isLiteralPath,
            bool allowNonexistingPaths,
            PSCmdlet cmdlet)
        {
            // Construct cmdletprovidercontext
            CmdletProviderContext cmdContext = new CmdletProviderContext(cmdlet);
            cmdContext.SuppressWildcardExpansion = isLiteralPath;

            Collection<PathInfo> results = new Collection<PathInfo>();

            try
            {
                // First resolve path
                Collection<PathInfo> pathInfos =
                    cmdlet.SessionState.Path.GetResolvedPSPathFromPSPath(
                        pathToResolve,
                        cmdContext);

                foreach (PathInfo pathInfo in pathInfos)
                {
                    results.Add(pathInfo);
                }
            }
            catch (PSNotSupportedException notSupported)
            {
                cmdlet.ThrowTerminatingError(
                    new ErrorRecord(
                        notSupported.ErrorRecord,
                        notSupported));
            }
            catch (System.Management.Automation.DriveNotFoundException driveNotFound)
            {
                cmdlet.ThrowTerminatingError(
                    new ErrorRecord(
                        driveNotFound.ErrorRecord,
                        driveNotFound));
            }
            catch (ProviderNotFoundException providerNotFound)
            {
                cmdlet.ThrowTerminatingError(
                    new ErrorRecord(
                        providerNotFound.ErrorRecord,
                        providerNotFound));
            }
            catch (ItemNotFoundException pathNotFound)
            {
                if (allowNonexistingPaths)
                {
                    ProviderInfo provider = null;
                    System.Management.Automation.PSDriveInfo drive = null;
                    string unresolvedPath =
                        cmdlet.SessionState.Path.GetUnresolvedProviderPathFromPSPath(
                            pathToResolve,
                            cmdContext,
                            out provider,
                            out drive);

                    PathInfo pathInfo =
                        new PathInfo(
                            drive,
                            provider,
                            unresolvedPath,
                            cmdlet.SessionState);
                    results.Add(pathInfo);
                }
                else
                {
                    cmdlet.ThrowTerminatingError(
                        new ErrorRecord(
                            pathNotFound.ErrorRecord,
                            pathNotFound));
                }
            }

            if (results.Count == 1)
            {
                return results[0];
            }
            else //if (results.Count > 1)
            {
                Exception e = PSTraceSource.NewNotSupportedException();
                cmdlet.ThrowTerminatingError(
                    new ErrorRecord(e,
                    "NotSupported",
                    ErrorCategory.NotImplemented,
                    results));
                return null;
            }
        } // ResolvePath
Пример #18
0
        internal static DirectoryInfo CreateModuleDirectory(PSCmdlet cmdlet, string moduleNameOrPath, bool force)
        {
            Dbg.Assert(cmdlet != null, "Caller should verify cmdlet != null");
            Dbg.Assert(!string.IsNullOrEmpty(moduleNameOrPath), "Caller should verify !string.IsNullOrEmpty(moduleNameOrPath)");

            DirectoryInfo directoryInfo = null;

            try
            {
                string rootedPath = Microsoft.PowerShell.Commands.ModuleCmdletBase.ResolveRootedFilePath(moduleNameOrPath, cmdlet.Context);
                if (string.IsNullOrEmpty(rootedPath) && moduleNameOrPath.StartsWith('.'))
                {
                    PathInfo currentPath = cmdlet.CurrentProviderLocation(cmdlet.Context.ProviderNames.FileSystem);
                    rootedPath = Path.Combine(currentPath.ProviderPath, moduleNameOrPath);
                }

                if (string.IsNullOrEmpty(rootedPath))
                {
                    string personalModuleRoot = ModuleIntrinsics.GetPersonalModulePath();
                    rootedPath = Path.Combine(personalModuleRoot, moduleNameOrPath);
                }

                directoryInfo = new DirectoryInfo(rootedPath);
                if (directoryInfo.Exists)
                {
                    if (!force)
                    {
                        string errorMessage = string.Format(
                            CultureInfo.InvariantCulture, // directory name should be treated as culture-invariant
                            PathUtilsStrings.ExportPSSession_ErrorDirectoryExists,
                            directoryInfo.FullName);
                        ErrorDetails details     = new ErrorDetails(errorMessage);
                        ErrorRecord  errorRecord = new ErrorRecord(
                            new ArgumentException(details.Message),
                            "ExportProxyCommand_OutputDirectoryExists",
                            ErrorCategory.ResourceExists,
                            directoryInfo);
                        cmdlet.ThrowTerminatingError(errorRecord);
                    }
                }
                else
                {
                    directoryInfo.Create();
                }
            }
            catch (Exception e)
            {
                string errorMessage = string.Format(
                    CultureInfo.InvariantCulture, // directory name should be treated as culture-invariant
                    PathUtilsStrings.ExportPSSession_CannotCreateOutputDirectory,
                    moduleNameOrPath,
                    e.Message);
                ErrorDetails details     = new ErrorDetails(errorMessage);
                ErrorRecord  errorRecord = new ErrorRecord(
                    new ArgumentException(details.Message, e),
                    "ExportProxyCommand_CannotCreateOutputDirectory",
                    ErrorCategory.ResourceExists,
                    moduleNameOrPath);
                cmdlet.ThrowTerminatingError(errorRecord);
            }

            return(directoryInfo);
        }
Пример #19
0
 /// <summary>
 /// Throw out terminating error for LSA function invocations
 /// </summary>
 /// <param name="ret"></param>
 /// <param name="cmdlet"></param>
 private static void ThrowOutLsaError(uint ret, PSCmdlet cmdlet)
 {
     var ex = new Win32Exception(SAMAPI.LsaNtStatusToWinError((int)ret));
     string errMsg = StringUtil.Format(ComputerResources.FailToResetPasswordOnLocalMachine, ex.Message);
     ErrorRecord error = new ErrorRecord(new InvalidOperationException(errMsg), "FailToResetPasswordOnLocalMachine",
                                         ErrorCategory.OperationStopped, Dns.GetHostName());
     cmdlet.ThrowTerminatingError(error);
 }
Пример #20
0
        internal static DirectoryInfo CreateModuleDirectory(PSCmdlet cmdlet, string moduleNameOrPath, bool force)
        {
            Dbg.Assert(cmdlet != null, "Caller should verify cmdlet != null");
            Dbg.Assert(!string.IsNullOrEmpty(moduleNameOrPath), "Caller should verify !string.IsNullOrEmpty(moduleNameOrPath)");

            DirectoryInfo directoryInfo = null;
            try
            {
                string rootedPath = Microsoft.PowerShell.Commands.ModuleCmdletBase.ResolveRootedFilePath(moduleNameOrPath, cmdlet.Context);
                if (string.IsNullOrEmpty(rootedPath) && moduleNameOrPath.StartsWith(".", StringComparison.OrdinalIgnoreCase))
                {
                    PathInfo currentPath = cmdlet.CurrentProviderLocation(cmdlet.Context.ProviderNames.FileSystem);
                    rootedPath = Path.Combine(currentPath.ProviderPath, moduleNameOrPath);
                }
                if (string.IsNullOrEmpty(rootedPath))
                {
                    string personalModuleRoot = ModuleIntrinsics.GetPersonalModulePath();
                    rootedPath = Path.Combine(personalModuleRoot, moduleNameOrPath);
                }

                directoryInfo = new DirectoryInfo(rootedPath);
                if (directoryInfo.Exists)
                {
                    if (!force)
                    {
                        string errorMessage = string.Format(
                            CultureInfo.InvariantCulture, // directory name should be treated as culture-invariant
                            PathUtilsStrings.ExportPSSession_ErrorDirectoryExists,
                            directoryInfo.FullName);
                        ErrorDetails details = new ErrorDetails(errorMessage);
                        ErrorRecord errorRecord = new ErrorRecord(
                            new ArgumentException(details.Message),
                            "ExportProxyCommand_OutputDirectoryExists",
                            ErrorCategory.ResourceExists,
                            directoryInfo);
                        cmdlet.ThrowTerminatingError(errorRecord);
                    }
                }
                else
                {
                    directoryInfo.Create();
                }
            }
            catch (Exception e)
            {
                CommandProcessorBase.CheckForSevereException(e);

                string errorMessage = string.Format(
                    CultureInfo.InvariantCulture, // directory name should be treated as culture-invariant
                    PathUtilsStrings.ExportPSSession_CannotCreateOutputDirectory,
                    moduleNameOrPath,
                    e.Message);
                ErrorDetails details = new ErrorDetails(errorMessage);
                ErrorRecord errorRecord = new ErrorRecord(
                    new ArgumentException(details.Message, e),
                    "ExportProxyCommand_CannotCreateOutputDirectory",
                    ErrorCategory.ResourceExists,
                    moduleNameOrPath);
                cmdlet.ThrowTerminatingError(errorRecord);
            }

            return directoryInfo;
        }
Пример #21
0
        /// <summary>
        /// Find out the Version of Catalog by reading its Meta data. We can have either version 1 or version 2 catalog
        /// </summary>
        /// <param name="catalogHandle">Handle to open catalog file.</param>
        /// <returns>Version of the catalog.</returns>
        private static int GetCatalogVersion(IntPtr catalogHandle)
        {
            int catalogVersion = -1;

            IntPtr catalogData = NativeMethods.CryptCATStoreFromHandle(catalogHandle);

            NativeMethods.CRYPTCATSTORE catalogInfo = Marshal.PtrToStructure <NativeMethods.CRYPTCATSTORE>(catalogData);

            if (catalogInfo.dwPublicVersion == catalogVersion2)
            {
                catalogVersion = 2;
            }
            // One Windows 7 this API sent version information as decimal 1 not hex (0X100 = 256)
            // so we are checking for that value as well. Reason we are not checking for version 2 above in
            // this scenario because catalog version 2 is not supported on win7.
            else if ((catalogInfo.dwPublicVersion == catalogVersion1) || (catalogInfo.dwPublicVersion == 1))
            {
                catalogVersion = 1;
            }
            else
            {
                // catalog version we don't understand
                Exception exception = new InvalidOperationException(StringUtil.Format(CatalogStrings.UnKnownCatalogVersion,
                                                                                      catalogVersion1.ToString("X"),
                                                                                      catalogVersion2.ToString("X")));

                ErrorRecord errorRecord = new ErrorRecord(exception, "UnKnownCatalogVersion", ErrorCategory.InvalidOperation, null);
                _cmdlet.ThrowTerminatingError(errorRecord);
            }

            return(catalogVersion);
        }
		internal static void ResetMachineAccountPassword(string domain, string localMachineName, string server, PSCredential credential, PSCmdlet cmdlet)
		{
			SAMAPI.LSA_UNICODE_STRING structure;
			string userName;
			string stringFromSecureString;
			string cannotFindMachineAccountFromServer;
			DirectoryEntry directoryEntry = null;
			DirectoryEntry directoryEntry1 = null;
			DirectorySearcher directorySearcher = null;
			string randomPassword = null;
			string str = server;
			string str1 = str;
			if (str == null)
			{
				str1 = domain;
			}
			string str2 = str1;
			try
			{
				try
				{
					if (credential != null)
					{
						userName = credential.UserName;
					}
					else
					{
						userName = null;
					}
					string str3 = userName;
					if (credential != null)
					{
						stringFromSecureString = Utils.GetStringFromSecureString(credential.Password);
					}
					else
					{
						stringFromSecureString = null;
					}
					string str4 = stringFromSecureString;
					directoryEntry = new DirectoryEntry(string.Concat("LDAP://", str2), str3, str4, AuthenticationTypes.Secure);
					directorySearcher = new DirectorySearcher(directoryEntry);
					string[] strArrays = new string[5];
					strArrays[0] = "(&(objectClass=computer)(|(cn=";
					strArrays[1] = localMachineName;
					strArrays[2] = ")(dn=";
					strArrays[3] = localMachineName;
					strArrays[4] = ")))";
					directorySearcher.Filter = string.Concat(strArrays);
					SearchResult searchResult = directorySearcher.FindOne();
					if (searchResult != null)
					{
						directoryEntry1 = searchResult.GetDirectoryEntry();
						randomPassword = ComputerWMIHelper.GetRandomPassword(120);
						object[] objArray = new object[1];
						objArray[0] = randomPassword;
						directoryEntry1.Invoke("SetPassword", objArray);
						directoryEntry1.Properties["LockOutTime"].Value = 0;
					}
					else
					{
						if (server != null)
						{
							cannotFindMachineAccountFromServer = ComputerResources.CannotFindMachineAccountFromServer;
						}
						else
						{
							cannotFindMachineAccountFromServer = ComputerResources.CannotFindMachineAccountFromDomain;
						}
						string str5 = cannotFindMachineAccountFromServer;
						string str6 = StringUtil.Format(str5, str2);
						ErrorRecord errorRecord = new ErrorRecord(new InvalidOperationException(str6), "CannotFindMachineAccount", ErrorCategory.OperationStopped, localMachineName);
						cmdlet.ThrowTerminatingError(errorRecord);
					}
				}
#if !MONO
				catch (DirectoryServicesCOMException directoryServicesCOMException1)
				{
					DirectoryServicesCOMException directoryServicesCOMException = directoryServicesCOMException1;
					string str7 = StringUtil.Format(ComputerResources.FailToResetPasswordOnDomain, directoryServicesCOMException.Message);
					ErrorRecord errorRecord1 = new ErrorRecord(new InvalidOperationException(str7), "FailToResetPasswordOnDomain", ErrorCategory.OperationStopped, localMachineName);
					cmdlet.ThrowTerminatingError(errorRecord1);
				}
#endif
				catch (TargetInvocationException targetInvocationException1)
				{
					TargetInvocationException targetInvocationException = targetInvocationException1;
					string str8 = StringUtil.Format(ComputerResources.FailToResetPasswordOnDomain, targetInvocationException.InnerException.Message);
					ErrorRecord errorRecord2 = new ErrorRecord(new InvalidOperationException(str8), "FailToResetPasswordOnDomain", ErrorCategory.OperationStopped, localMachineName);
					cmdlet.ThrowTerminatingError(errorRecord2);
				}
				catch (COMException cOMException1)
				{
					COMException cOMException = cOMException1;
					string str9 = StringUtil.Format(ComputerResources.FailToResetPasswordOnDomain, cOMException.Message);
					ErrorRecord errorRecord3 = new ErrorRecord(new InvalidOperationException(str9), "FailToResetPasswordOnDomain", ErrorCategory.OperationStopped, localMachineName);
					cmdlet.ThrowTerminatingError(errorRecord3);
				}
			}
			finally
			{
				if (directoryEntry != null)
				{
					directoryEntry.Close();
					directoryEntry.Dispose();
				}
				if (directorySearcher != null)
				{
					directorySearcher.Dispose();
				}
				if (directoryEntry1 != null)
				{
					directoryEntry1.Close();
					directoryEntry1.Dispose();
				}
			}
			SAMAPI.LSA_OBJECT_ATTRIBUTES zero = new SAMAPI.LSA_OBJECT_ATTRIBUTES();
			zero.RootDirectory = IntPtr.Zero;
			zero.ObjectName = IntPtr.Zero;
			zero.Attributes = 0;
			zero.SecurityDescriptor = IntPtr.Zero;
			zero.SecurityQualityOfService = IntPtr.Zero;
			zero.Length = Marshal.SizeOf(typeof(SAMAPI.LSA_OBJECT_ATTRIBUTES));
			IntPtr intPtr = IntPtr.Zero;
			IntPtr zero1 = IntPtr.Zero;
			IntPtr intPtr1 = IntPtr.Zero;
			SAMAPI.LSA_UNICODE_STRING lSAUNICODESTRING = new SAMAPI.LSA_UNICODE_STRING();
			lSAUNICODESTRING.Buffer = IntPtr.Zero;
			SAMAPI.LSA_UNICODE_STRING lSAUNICODESTRING1 = lSAUNICODESTRING;
			SAMAPI.LSA_UNICODE_STRING zero2 = new SAMAPI.LSA_UNICODE_STRING();
			zero2.Buffer = IntPtr.Zero;
			SAMAPI.LSA_UNICODE_STRING lSAUNICODESTRING2 = zero2;
			SAMAPI.LSA_UNICODE_STRING zero3 = new SAMAPI.LSA_UNICODE_STRING();
			zero3.Buffer = IntPtr.Zero;
			zero3.Length = 0;
			zero3.MaximumLength = 0;
			try
			{
				uint num = SAMAPI.LsaOpenPolicy(ref zero3, ref zero, 0xf0fff, out intPtr);
				if (num == -1073741790)
				{
					string needAdminPrivilegeToResetPassword = ComputerResources.NeedAdminPrivilegeToResetPassword;
					ErrorRecord errorRecord4 = new ErrorRecord(new InvalidOperationException(needAdminPrivilegeToResetPassword), "UnauthorizedAccessException", ErrorCategory.InvalidOperation, localMachineName);
					cmdlet.ThrowTerminatingError(errorRecord4);
				}
				if (num != 0)
				{
					ResetComputerMachinePasswordCommand.ThrowOutLsaError(num, cmdlet);
				}
				SAMAPI.InitLsaString("$MACHINE.ACC", ref lSAUNICODESTRING1);
				SAMAPI.InitLsaString(randomPassword, ref lSAUNICODESTRING2);
				bool flag = false;
				num = SAMAPI.LsaOpenSecret(intPtr, ref lSAUNICODESTRING1, 3, out zero1);
				if (num == -1073741772)
				{
					num = SAMAPI.LsaCreateSecret(intPtr, ref lSAUNICODESTRING1, 1, out zero1);
					flag = true;
				}
				if (num != 0)
				{
					ResetComputerMachinePasswordCommand.ThrowOutLsaError(num, cmdlet);
				}
				if (!flag)
				{
					num = SAMAPI.LsaQuerySecret(zero1, out intPtr1, IntPtr.Zero, IntPtr.Zero, IntPtr.Zero);
					if (num != 0)
					{
						ResetComputerMachinePasswordCommand.ThrowOutLsaError(num, cmdlet);
					}
					structure = (SAMAPI.LSA_UNICODE_STRING)Marshal.PtrToStructure(intPtr1, typeof(SAMAPI.LSA_UNICODE_STRING));
				}
				else
				{
					structure = lSAUNICODESTRING2;
				}
				num = SAMAPI.LsaSetSecret(zero1, ref lSAUNICODESTRING2, ref structure);
				if (num != 0)
				{
					ResetComputerMachinePasswordCommand.ThrowOutLsaError(num, cmdlet);
				}
			}
			finally
			{
				if (intPtr1 != IntPtr.Zero)
				{
					SAMAPI.LsaFreeMemory(intPtr1);
				}
				if (intPtr != IntPtr.Zero)
				{
					SAMAPI.LsaClose(intPtr);
				}
				if (zero1 != IntPtr.Zero)
				{
					SAMAPI.LsaClose(zero1);
				}
				SAMAPI.FreeLsaString(ref lSAUNICODESTRING1);
				SAMAPI.FreeLsaString(ref lSAUNICODESTRING2);
			}
		}
Пример #23
0
        /// <summary>
        /// THE method for opening a file for writing.
        /// Should be used by all cmdlets that write to a file.
        /// </summary>
        /// <param name="cmdlet">Cmdlet that is opening the file (used mainly for error reporting).</param>
        /// <param name="filePath">Path to the file (as specified on the command line - this method will resolve the path).</param>
        /// <param name="resolvedEncoding">Encoding (this method will convert the command line string to an Encoding instance).</param>
        /// <param name="defaultEncoding">If <see langword="true"/>, then we will use default .NET encoding instead of the encoding specified in <paramref name="encoding"/> parameter.</param>
        /// <param name="Append"></param>
        /// <param name="Force"></param>
        /// <param name="NoClobber"></param>
        /// <param name="fileStream">Result1: <see cref="FileStream"/> opened for writing.</param>
        /// <param name="streamWriter">Result2: <see cref="StreamWriter"/> (inherits from <see cref="TextWriter"/>) opened for writing.</param>
        /// <param name="readOnlyFileInfo">Result3: file info that should be used to restore file attributes after done with the file (<see langword="null"/> is this is not needed).</param>
        /// <param name="isLiteralPath">True if wildcard expansion should be bypassed.</param>
        internal static void MasterStreamOpen(
            PSCmdlet cmdlet,
            string filePath,
            Encoding resolvedEncoding,
            bool defaultEncoding,
            bool Append,
            bool Force,
            bool NoClobber,
            out FileStream fileStream,
            out StreamWriter streamWriter,
            out FileInfo readOnlyFileInfo,
            bool isLiteralPath)
        {
            fileStream       = null;
            streamWriter     = null;
            readOnlyFileInfo = null;

            // resolve the path and the encoding
            string resolvedPath = ResolveFilePath(filePath, cmdlet, isLiteralPath);

            try
            {
                // variable to track file open mode
                // this is controlled by append/force parameters
                FileMode mode = FileMode.Create;
                if (Append)
                {
                    mode = FileMode.Append;
                }
                else if (NoClobber)
                {
                    // throw IOException if file exists
                    mode = FileMode.CreateNew;
                }

                if (Force && (Append || !NoClobber))
                {
                    if (File.Exists(resolvedPath))
                    {
                        FileInfo fInfo = new FileInfo(resolvedPath);
                        if ((fInfo.Attributes & FileAttributes.ReadOnly) == FileAttributes.ReadOnly)
                        {
                            // remember to reset the read-only attribute later
                            readOnlyFileInfo = fInfo;
                            // Clear the read-only attribute
                            fInfo.Attributes &= ~(FileAttributes.ReadOnly);
                        }
                    }
                }

                // if the user knows what he/she is doing and uses "-Force" switch,
                // then we let more than 1 process write to the same file at the same time
                FileShare fileShare = Force ? FileShare.ReadWrite : FileShare.Read;

                // mode is controlled by force and ShouldContinue()
                fileStream = new FileStream(resolvedPath, mode, FileAccess.Write, fileShare);

                // create stream writer
                // NTRAID#Windows Out Of Band Releases-931008-2006/03/27
                // For some reason, calling this without specifying
                // the encoding is different from passing Encoding.Default.
                if (defaultEncoding)
                {
                    streamWriter = new StreamWriter(fileStream);
                }
                else
                {
                    streamWriter = new StreamWriter(fileStream, resolvedEncoding);
                }
            }
            // These are the known exceptions for File.Load and StreamWriter.ctor
            catch (ArgumentException e)
            {
                // NOTE: this call will throw
                ReportFileOpenFailure(cmdlet, resolvedPath, e);
            }
            catch (IOException e)
            {
                if (NoClobber && File.Exists(resolvedPath))
                {
                    // This probably happened because the file already exists
                    ErrorRecord errorRecord = new ErrorRecord(
                        e, "NoClobber", ErrorCategory.ResourceExists, resolvedPath);
                    errorRecord.ErrorDetails = new ErrorDetails(
                        cmdlet,
                        "PathUtilsStrings",
                        "UtilityFileExistsNoClobber",
                        filePath,
                        "NoClobber"); // prevents localization

                    // NOTE: this call will throw
                    cmdlet.ThrowTerminatingError(errorRecord);
                }
                // NOTE: this call will throw
                ReportFileOpenFailure(cmdlet, resolvedPath, e);
            }
            catch (UnauthorizedAccessException e)
            {
                // NOTE: this call will throw
                ReportFileOpenFailure(cmdlet, resolvedPath, e);
            }
            catch (NotSupportedException e)
            {
                // NOTE: this call will throw
                ReportFileOpenFailure(cmdlet, resolvedPath, e);
            }
            catch (System.Security.SecurityException e)
            {
                // NOTE: this call will throw
                ReportFileOpenFailure(cmdlet, resolvedPath, e);
            }
        }
Пример #24
0
        internal static DirectoryInfo CreateModuleDirectory(PSCmdlet cmdlet, string moduleNameOrPath, bool force)
        {
            Dbg.Assert(cmdlet != null, "Caller should verify cmdlet != null");
            Dbg.Assert(!string.IsNullOrEmpty(moduleNameOrPath), "Caller should verify !string.IsNullOrEmpty(moduleNameOrPath)");

            DirectoryInfo directoryInfo = null;

            try
            {
                // Even if 'moduleNameOrPath' is a rooted path, 'ResolveRootedFilePath' may return null when the path doesn't exist yet,
                // or when it contains wildcards but cannot be resolved to a single path.
                string rootedPath = ModuleCmdletBase.ResolveRootedFilePath(moduleNameOrPath, cmdlet.Context);
                if (string.IsNullOrEmpty(rootedPath) && moduleNameOrPath.StartsWith('.'))
                {
                    PathInfo currentPath = cmdlet.CurrentProviderLocation(cmdlet.Context.ProviderNames.FileSystem);
                    rootedPath = Path.Combine(currentPath.ProviderPath, moduleNameOrPath);
                }

                if (string.IsNullOrEmpty(rootedPath))
                {
                    if (Path.IsPathRooted(moduleNameOrPath))
                    {
                        rootedPath = moduleNameOrPath;
                    }
                    else
                    {
                        string personalModuleRoot = ModuleIntrinsics.GetPersonalModulePath();
                        if (string.IsNullOrEmpty(personalModuleRoot))
                        {
                            cmdlet.ThrowTerminatingError(
                                new ErrorRecord(
                                    new ArgumentException(StringUtil.Format(PathUtilsStrings.ExportPSSession_ErrorModuleNameOrPath, moduleNameOrPath)),
                                    "ExportPSSession_ErrorModuleNameOrPath",
                                    ErrorCategory.InvalidArgument,
                                    cmdlet));
                        }

                        rootedPath = Path.Combine(personalModuleRoot, moduleNameOrPath);
                    }
                }

                directoryInfo = new DirectoryInfo(rootedPath);
                if (directoryInfo.Exists)
                {
                    if (!force)
                    {
                        string errorMessage = string.Format(
                            CultureInfo.InvariantCulture, // directory name should be treated as culture-invariant
                            PathUtilsStrings.ExportPSSession_ErrorDirectoryExists,
                            directoryInfo.FullName);
                        ErrorDetails details     = new ErrorDetails(errorMessage);
                        ErrorRecord  errorRecord = new ErrorRecord(
                            new ArgumentException(details.Message),
                            "ExportProxyCommand_OutputDirectoryExists",
                            ErrorCategory.ResourceExists,
                            directoryInfo);
                        cmdlet.ThrowTerminatingError(errorRecord);
                    }
                }
                else
                {
                    directoryInfo.Create();
                }
            }
            catch (Exception e)
            {
                string errorMessage = string.Format(
                    CultureInfo.InvariantCulture, // directory name should be treated as culture-invariant
                    PathUtilsStrings.ExportPSSession_CannotCreateOutputDirectory,
                    moduleNameOrPath,
                    e.Message);
                ErrorDetails details     = new ErrorDetails(errorMessage);
                ErrorRecord  errorRecord = new ErrorRecord(
                    new ArgumentException(details.Message, e),
                    "ExportProxyCommand_CannotCreateOutputDirectory",
                    ErrorCategory.ResourceExists,
                    moduleNameOrPath);
                cmdlet.ThrowTerminatingError(errorRecord);
            }

            return(directoryInfo);
        }