protected override void NewItem(string path, string type, object newItem) { using (SessionStateProviderBase.tracer.TraceMethod(path, new object[0])) { if (string.IsNullOrEmpty(path)) { this.WriteError(new ErrorRecord((Exception)SessionStateProviderBase.tracer.NewArgumentException(nameof(path)), "NewItemNullPath", ErrorCategory.InvalidArgument, (object)path)); } else if (newItem == null) { this.WriteError(new ErrorRecord((Exception)SessionStateProviderBase.tracer.NewArgumentNullException("value"), "NewItemValueNotSpecified", ErrorCategory.InvalidArgument, (object)path)); } else if (this.ItemExists(path) && !(bool)this.Force) { PSArgumentException argumentException = SessionStateProviderBase.tracer.NewArgumentException(nameof(path), "SessionStateStrings", "NewItemAlreadyExists", (object)path); this.WriteError(new ErrorRecord(argumentException.ErrorRecord, (Exception)argumentException)); } else { string resourceString = ResourceManagerCache.GetResourceString("SessionStateProviderBaseStrings", "NewItemAction"); if (!this.ShouldProcess(string.Format((IFormatProvider)this.Host.CurrentCulture, ResourceManagerCache.GetResourceString("SessionStateProviderBaseStrings", "NewItemResourceTemplate"), (object)path, (object)type, newItem), resourceString)) { return; } this.SetItem(path, newItem); } } }
private CommandInfo GetOutDefaultCommandInfo(string moduleName, ref List <ErrorRecord> errors) { CommandInfo info = null; Assembly executingAssembly = Assembly.GetExecutingAssembly(); byte[] publicKeyToken = executingAssembly.GetName().GetPublicKeyToken(); if (publicKeyToken.Length == 0) { PSArgumentException exception = PSTraceSource.NewArgumentException("PublicKeyToken", "MshSnapinInfo", "PublicKeyTokenAccessFailed", new object[0]); errors.Add(new ErrorRecord(exception, "PublicKeyTokenAccessFailed", ErrorCategory.InvalidOperation, null)); return(info); } string str = PSSnapInReader.ConvertByteArrayToString(publicKeyToken); string str2 = "neutral"; string str3 = "MSIL"; if (LoadAssemblyHelper(string.Format(CultureInfo.InvariantCulture, "{0}, Version={1}, Culture={2}, PublicKeyToken={3}, ProcessorArchitecture={4}", new object[] { "Microsoft.PowerShell.Commands.Utility", executingAssembly.GetName().Version, str2, str, str3 }), ref errors) != null) { Exception exception2; Type implementingType = LanguagePrimitives.ConvertStringToType("Microsoft.PowerShell.Commands.OutDefaultCommand", out exception2); if (exception2 != null) { errors.Add(new ErrorRecord(exception2, "CmdletNotFoundWhileLoadingModulesOnRunspaceOpen", ErrorCategory.InvalidType, null)); } if (implementingType != null) { return(new CmdletInfo("Out-Default", implementingType, null, null, this._engine.Context)); } errors.Add(new ErrorRecord(PSTraceSource.NewInvalidOperationException("RunspaceStrings", "CmdletNotFoundWhileLoadingModulesOnRunspaceOpen", new object[] { moduleName }), "CmdletNotFoundWhileLoadingModulesOnRunspaceOpen", ErrorCategory.InvalidOperation, null)); } return(info); }
private object CreateComObject() { Type t = null; PSArgumentException exception = null; try { t = Type.GetTypeFromCLSID(this.comObjectClsId); if (t == null) { exception = PSTraceSource.NewArgumentException("ComObject", "NewObjectStrings", "CannotLoadComObjectType", new object[] { this.comObject }); base.ThrowTerminatingError(new ErrorRecord(exception, "CannotLoadComObjectType", ErrorCategory.InvalidType, null)); } return(this.SafeCreateInstance(t, this.arguments)); } catch (COMException exception2) { if (exception2.ErrorCode == -2147417850) { this.createInfo = new ComCreateInfo(); Thread thread = new Thread(new ParameterizedThreadStart(this.STAComCreateThreadProc)); thread.SetApartmentState(ApartmentState.STA); thread.Start(this.createInfo); thread.Join(); if (this.createInfo.success) { return(this.createInfo.objectCreated); } base.ThrowTerminatingError(new ErrorRecord(this.createInfo.e, "NoCOMClassIdentified", ErrorCategory.ResourceUnavailable, null)); return(null); } base.ThrowTerminatingError(new ErrorRecord(exception2, "NoCOMClassIdentified", ErrorCategory.ResourceUnavailable, null)); return(null); } }
private string CombineHashTableOrStringArray(object[] values, StreamWriter writer) { StringBuilder builder = new StringBuilder(); for (int i = 0; i < values.Length; i++) { string str = values[i] as string; if (!string.IsNullOrEmpty(str)) { builder.Append(QuoteName(str)); } else { Hashtable table = values[i] as Hashtable; if (table == null) { PSArgumentException exception = new PSArgumentException(StringUtil.Format(RemotingErrorIdStrings.DISCTypeMustBeStringOrHashtableArray, ConfigFileContants.ModulesToImport)); base.ThrowTerminatingError(exception.ErrorRecord); } builder.Append(this.CombineHashtable(table, writer)); } if (i < (values.Length - 1)) { builder.Append(", "); } } return(builder.ToString()); }
private void STAComCreateThreadProc(object createstruct) { ComCreateInfo info = (ComCreateInfo)createstruct; try { Type t = null; PSArgumentException exception = null; t = Type.GetTypeFromCLSID(this.comObjectClsId); if (t == null) { exception = PSTraceSource.NewArgumentException("ComObject", "NewObjectStrings", "CannotLoadComObjectType", new object[] { this.comObject }); info.e = exception; info.success = false; } else { info.objectCreated = this.SafeCreateInstance(t, this.arguments); info.success = true; } } catch (Exception exception2) { CommandProcessorBase.CheckForSevereException(exception2); info.e = exception2; info.success = false; } }
protected override void NewItem(string path, string type, object newItem) { if (string.IsNullOrEmpty(path)) { Exception exception = PSTraceSource.NewArgumentException("path"); base.WriteError(new ErrorRecord(exception, "NewItemNullPath", ErrorCategory.InvalidArgument, path)); } else if (newItem == null) { ArgumentNullException exception2 = PSTraceSource.NewArgumentNullException("value"); base.WriteError(new ErrorRecord(exception2, "NewItemValueNotSpecified", ErrorCategory.InvalidArgument, path)); } else if (this.ItemExists(path) && (base.Force == 0)) { PSArgumentException replaceParentContainsErrorRecordException = PSTraceSource.NewArgumentException("path", "SessionStateStrings", "NewItemAlreadyExists", new object[] { path }); base.WriteError(new ErrorRecord(replaceParentContainsErrorRecordException.ErrorRecord, replaceParentContainsErrorRecordException)); } else { string newItemAction = SessionStateProviderBaseStrings.NewItemAction; string newItemResourceTemplate = SessionStateProviderBaseStrings.NewItemResourceTemplate; string target = string.Format(base.Host.CurrentCulture, newItemResourceTemplate, new object[] { path, type, newItem }); if (base.ShouldProcess(target, newItemAction)) { this.SetItem(path, newItem); } } }
private void STAComCreateThreadProc(object createstruct) { ComCreateInfo info = (ComCreateInfo)createstruct; try { Type type = null; PSArgumentException mshArgE = null; type = Type.GetTypeFromCLSID(_comObjectClsId); if (type == null) { mshArgE = PSTraceSource.NewArgumentException( "ComObject", NewObjectStrings.CannotLoadComObjectType, ComObject); info.e = mshArgE; info.success = false; return; } info.objectCreated = SafeCreateInstance(type, ArgumentList); info.success = true; } catch (Exception e) { info.e = e; info.success = false; } }
private void ThrowSubscriptionNotFoundError(string tenant, string subscription) { PSArgumentException exception = new PSArgumentException(string.Format(Resources.SubscriptionNotFoundError, subscription, tenant)); exception.Data[AzurePSErrorDataKeys.ErrorKindKey] = ErrorKind.UserError; throw exception; }
protected override void ProcessRecord() { try { PathInfo pathInfo = base.SessionState.Path.PopLocation(this.stackName); if (this.PassThru) { base.WriteObject(pathInfo); } } catch (DriveNotFoundException driveNotFoundException1) { DriveNotFoundException driveNotFoundException = driveNotFoundException1; base.WriteError(new ErrorRecord(driveNotFoundException.ErrorRecord, driveNotFoundException)); } catch (ProviderNotFoundException providerNotFoundException1) { ProviderNotFoundException providerNotFoundException = providerNotFoundException1; base.WriteError(new ErrorRecord(providerNotFoundException.ErrorRecord, providerNotFoundException)); } catch (PSArgumentException pSArgumentException1) { PSArgumentException pSArgumentException = pSArgumentException1; base.WriteError(new ErrorRecord(pSArgumentException.ErrorRecord, pSArgumentException)); } catch (ItemNotFoundException itemNotFoundException1) { ItemNotFoundException itemNotFoundException = itemNotFoundException1; base.WriteError(new ErrorRecord(itemNotFoundException.ErrorRecord, itemNotFoundException)); } }
private object CreateComObject() { Type type = null; PSArgumentException mshArgE = null; try { type = Marshal.GetTypeFromCLSID(_comObjectClsId); if (type == null) { mshArgE = PSTraceSource.NewArgumentException("ComObject", NewObjectStrings.CannotLoadComObjectType, ComObject); ThrowTerminatingError( new ErrorRecord(mshArgE, "CannotLoadComObjectType", ErrorCategory.InvalidType, null)); } return(SafeCreateInstance(type, ArgumentList)); } catch (COMException e) { // Check Error Code to see if Error is because of Com apartment Mismatch. if (e.HResult == RPC_E_CHANGED_MODE) { #if CORECLR ThrowTerminatingError( new ErrorRecord( new COMException(StringUtil.Format(NewObjectStrings.ApartmentNotSupported, e.Message), e), "NoCOMClassIdentified", ErrorCategory.ResourceUnavailable, null)); #else createInfo = new ComCreateInfo(); Thread thread = new Thread(new ParameterizedThreadStart(STAComCreateThreadProc)); thread.SetApartmentState(ApartmentState.STA); thread.Start(createInfo); thread.Join(); if (createInfo.success == true) { return(createInfo.objectCreated); } ThrowTerminatingError( new ErrorRecord(createInfo.e, "NoCOMClassIdentified", ErrorCategory.ResourceUnavailable, null)); #endif } else { ThrowTerminatingError( new ErrorRecord( e, "NoCOMClassIdentified", ErrorCategory.ResourceUnavailable, null)); } return(null); } }
/// <summary> /// Terminating error. /// </summary> /// <param name="parameterName"></param> /// <param name="description"></param> /// <param name="reason"></param> /// <param name="pscxPath"></param> protected virtual void OnPscxPathError(string parameterName, string description, PscxPathState reason, PscxPathInfo pscxPath) { string errorMessage = String.Format("{0}'s {1} parameter has an invalid path of '{2}': {3}", this.CmdletName, parameterName, pscxPath.SourcePath, description); var exception = new PSArgumentException(errorMessage, parameterName); this.ThrowTerminatingError( new ErrorRecord(exception, reason.ToString(), ErrorCategory.InvalidArgument, parameterName)); }
internal void ThrowConflictParameterWasSet(string operationName, string parameterName, string conflictParameterName) { object[] objArray = new object[2]; objArray[0] = parameterName; objArray[1] = conflictParameterName; string str = string.Format(CultureInfo.CurrentUICulture, Strings.ConflictParameterWasSet, objArray); PSArgumentException pSArgumentException = new PSArgumentException(str, parameterName); this.ThrowTerminatingError(pSArgumentException, operationName); }
private void ProcessParameter(MshParameter p, PSObject inputObject, List <PSNoteProperty> result) { string entry = p.GetEntry("name") as string; MshExpression re = p.GetEntry("expression") as MshExpression; List <MshExpressionResult> list = new List <MshExpressionResult>(); foreach (MshExpression expression2 in re.ResolveNames(inputObject)) { if ((this.exclusionFilter == null) || !this.exclusionFilter.IsMatch(expression2)) { List <MshExpressionResult> values = expression2.GetValues(inputObject); if (values != null) { foreach (MshExpressionResult result2 in values) { list.Add(result2); } } } } if (list.Count == 0) { list.Add(new MshExpressionResult(null, re, null)); } else if (!string.IsNullOrEmpty(entry) && (list.Count > 1)) { ErrorRecord errorRecord = new ErrorRecord(new InvalidOperationException(SelectObjectStrings.RenamingMultipleResults), "RenamingMultipleResults", ErrorCategory.InvalidOperation, inputObject); base.WriteError(errorRecord); return; } foreach (MshExpressionResult result3 in list) { if ((this.exclusionFilter == null) || !this.exclusionFilter.IsMatch(result3.ResolvedExpression)) { PSNoteProperty property; if (string.IsNullOrEmpty(entry)) { string str3 = result3.ResolvedExpression.ToString(); if (string.IsNullOrEmpty(str3)) { PSArgumentException exception = PSTraceSource.NewArgumentException("Property", this.ResourcesBaseName, "EmptyScriptBlockAndNoName", new object[0]); base.ThrowTerminatingError(new ErrorRecord(exception, "EmptyScriptBlockAndNoName", ErrorCategory.InvalidArgument, null)); } property = new PSNoteProperty(str3, result3.Result); } else { property = new PSNoteProperty(entry, result3.Result); } result.Add(property); } } }
/// <summary> /// Throw conflict parameter error /// </summary> /// <param name="operationName"></param> /// <param name="parameterName"></param> /// <param name="conflictParameterName"></param> internal void ThrowConflictParameterWasSet( string operationName, string parameterName, string conflictParameterName) { string message = String.Format(CultureInfo.CurrentUICulture, Strings.ConflictParameterWasSet, parameterName, conflictParameterName); PSArgumentException exception = new PSArgumentException(message, parameterName); ThrowTerminatingError(exception, operationName); }
protected override void CopyItem(string path, string copyPath, bool recurse) { if (string.IsNullOrEmpty(path)) { Exception exception = PSTraceSource.NewArgumentException("path"); base.WriteError(new ErrorRecord(exception, "CopyItemNullPath", ErrorCategory.InvalidArgument, path)); } else if (string.IsNullOrEmpty(copyPath)) { this.GetItem(path); } else { object item = null; try { item = this.GetSessionStateItem(path); } catch (SecurityException exception2) { base.WriteError(new ErrorRecord(exception2, "CopyItemSecurityException", ErrorCategory.ReadError, path)); return; } if (item != null) { string copyItemAction = SessionStateProviderBaseStrings.CopyItemAction; string copyItemResourceTemplate = SessionStateProviderBaseStrings.CopyItemResourceTemplate; string target = string.Format(base.Host.CurrentCulture, copyItemResourceTemplate, new object[] { path, copyPath }); if (!base.ShouldProcess(target, copyItemAction)) { return; } try { this.SetSessionStateItem(copyPath, this.GetValueOfItem(item), true); return; } catch (SessionStateException exception3) { base.WriteError(new ErrorRecord(exception3.ErrorRecord, exception3)); return; } catch (PSArgumentException exception4) { base.WriteError(new ErrorRecord(exception4.ErrorRecord, exception4)); return; } } PSArgumentException replaceParentContainsErrorRecordException = PSTraceSource.NewArgumentException("path", "SessionStateStrings", "CopyItemDoesntExist", new object[] { path }); base.WriteError(new ErrorRecord(replaceParentContainsErrorRecordException.ErrorRecord, replaceParentContainsErrorRecordException)); } }
protected override void CopyItem(string path, string copyPath, bool recurse) { using (SessionStateProviderBase.tracer.TraceMethod(path, new object[0])) { if (string.IsNullOrEmpty(path)) { this.WriteError(new ErrorRecord((Exception)SessionStateProviderBase.tracer.NewArgumentException(nameof(path)), "CopyItemNullPath", ErrorCategory.InvalidArgument, (object)path)); } else if (string.IsNullOrEmpty(copyPath)) { this.GetItem(path); } else { object sessionStateItem; try { sessionStateItem = this.GetSessionStateItem(path); } catch (SecurityException ex) { this.WriteError(new ErrorRecord((Exception)ex, "CopyItemSecurityException", ErrorCategory.ReadError, (object)path)); return; } if (sessionStateItem != null) { string resourceString = ResourceManagerCache.GetResourceString("SessionStateProviderBaseStrings", "CopyItemAction"); if (!this.ShouldProcess(string.Format((IFormatProvider)this.Host.CurrentCulture, ResourceManagerCache.GetResourceString("SessionStateProviderBaseStrings", "CopyItemResourceTemplate"), (object)path, (object)copyPath), resourceString)) { return; } try { this.SetSessionStateItem(copyPath, this.GetValueOfItem(sessionStateItem), true); } catch (SessionStateException ex) { this.WriteError(new ErrorRecord(ex.ErrorRecord, (Exception)ex)); } catch (PSArgumentException ex) { this.WriteError(new ErrorRecord(ex.ErrorRecord, (Exception)ex)); } } else { PSArgumentException argumentException = SessionStateProviderBase.tracer.NewArgumentException(nameof(path), "SessionStateStrings", "CopyItemDoesntExist", (object)path); this.WriteError(new ErrorRecord(argumentException.ErrorRecord, (Exception)argumentException)); } } } }
protected override void EndProcessing() { if (!Path.EndsWith(".ps1", StringComparison.OrdinalIgnoreCase)) { var exMessage = "Path needs to end with a .ps1 file. Example: C:/Users/john/x/MyScript.ps1"; var ex = new ArgumentException(exMessage); var InvalidPathError = new ErrorRecord(ex, "InvalidPath", ErrorCategory.InvalidArgument, null); ThrowTerminatingError(InvalidPathError); } var resolvedPaths = SessionState.Path.GetResolvedPSPathFromPSPath(Path); if (resolvedPaths.Count != 1) { var exMessage = "Error: Could not resolve provided Path argument into a single path."; var ex = new PSArgumentException(exMessage); var InvalidPathArgumentError = new ErrorRecord(ex, "InvalidPathArgumentError", ErrorCategory.InvalidArgument, null); ThrowTerminatingError(InvalidPathArgumentError); } var resolvedPath = resolvedPaths[0].Path; if (!File.Exists(resolvedPath)) { var exMessage = "A .ps1 file does not exist at the location specified."; var ex = new ArgumentException(exMessage); var FileDoesNotExistError = new ErrorRecord(ex, "FileDoesNotExistAtPath", ErrorCategory.InvalidArgument, null); ThrowTerminatingError(FileDoesNotExistError); } bool isValidScript = PSScriptFileInfo.TryTestPSScriptFile( scriptFileInfoPath: resolvedPath, parsedScript: out PSScriptFileInfo _, errors: out ErrorRecord[] errors, out string[] verboseMsgs); if (!isValidScript) { foreach (ErrorRecord error in errors) { WriteVerbose("The .ps1 script file passed in was not valid due to: " + error.Exception.Message); } } foreach (string msg in verboseMsgs) { WriteVerbose(msg); } WriteObject(isValidScript); }
/// <summary> /// Given the tokenized path, the relative path elements are removed. /// </summary> /// <param name="tokenizedPathStack"> /// A stack containing path elements where the leaf most element is at /// the bottom of the stack and the most ancestral parent is on the top. /// Generally this stack comes from TokenizePathToStack(). /// </param> /// <param name="path"> /// The path being normalized. Just used for error reporting. /// </param> /// <param name="basePath"> /// The base path to make the path relative to. Just used for error reporting. /// </param> /// <param name="allowNonExistingPaths"> /// Determines whether to throw an exception on non-existing paths. /// </param> /// <returns> /// A stack in reverse order with the path elements normalized and all relative /// path tokens removed. /// </returns> private static Stack <string> NormalizeThePath( Stack <string> tokenizedPathStack, string path, string basePath, bool allowNonExistingPaths) { Stack <string> normalizedPathStack = new Stack <string>(); while (tokenizedPathStack.Count > 0) { string childName = tokenizedPathStack.Pop(); providerBaseTracer.WriteLine("childName = {0}", childName); // Ignore the current directory token if (childName.Equals(".", StringComparison.OrdinalIgnoreCase)) { // Just ignore it and move on. continue; } // Make sure we don't have if (childName.Equals("..", StringComparison.OrdinalIgnoreCase)) { if (normalizedPathStack.Count > 0) { // Pop the result and continue processing string poppedName = normalizedPathStack.Pop(); providerBaseTracer.WriteLine("normalizedPathStack.Pop() : {0}", poppedName); continue; } else { if (!allowNonExistingPaths) { PSArgumentException e = (PSArgumentException) PSTraceSource.NewArgumentException( "path", SessionStateStrings.NormalizeRelativePathOutsideBase, path, basePath); throw e; } } } providerBaseTracer.WriteLine("normalizedPathStack.Push({0})", childName); normalizedPathStack.Push(childName); } return(normalizedPathStack); }
protected override void BeginProcessing() { base.BeginProcessing(); if (!this.specifiedPath && !this.isLiteralPath) { PSArgumentException exception = new PSArgumentException(StringUtil.Format(HelpDisplayStrings.CannotSpecifyDestinationPathAndLiteralPath, new object[0])); base.ThrowTerminatingError(exception.ErrorRecord); } else if ((this.specifiedPath || this.isLiteralPath) && !(this.specifiedPath ^ this.isLiteralPath)) { PSArgumentException exception2 = new PSArgumentException(StringUtil.Format(HelpDisplayStrings.CannotSpecifyDestinationPathAndLiteralPath, new object[0])); base.ThrowTerminatingError(exception2.ErrorRecord); } }
/// <summary> /// Processes a module with potential globbing /// </summary> /// <param name="name">Module name with globbing.</param> private void ProcessModuleWithGlobbing(string name) { if (string.IsNullOrEmpty(name)) { PSArgumentException e = new PSArgumentException(StringUtil.Format(HelpDisplayStrings.ModuleNameNullOrEmpty)); WriteError(e.ErrorRecord); return; } foreach (KeyValuePair <Tuple <string, Version>, UpdatableHelpModuleInfo> module in GetModuleInfo(name, null, false)) { ProcessModule(module.Value); } }
protected override string NormalizeRelativePath(string path, string basePath) { var normPath = new Path(path).NormalizeSlashes(); var normBase = new Path(basePath).NormalizeSlashes(); if (!normPath.StartsWith(normBase)) { var ex = new PSArgumentException("Path is outside of base path!", "PathOutsideBasePath", ErrorCategory.InvalidArgument); WriteError(ex.ErrorRecord); return(null); } return(new Path(path.Substring(basePath.Length)).TrimStartSlash().ToString()); }
private void ProcessModuleWithGlobbing(string name) { if (string.IsNullOrEmpty(name)) { PSArgumentException exception = new PSArgumentException(StringUtil.Format(HelpDisplayStrings.ModuleNameNullOrEmpty, new object[0])); base.WriteError(exception.ErrorRecord); } else { foreach (KeyValuePair <string, UpdatableHelpModuleInfo> pair in this.GetModuleInfo(name, false, false)) { this.ProcessModule(pair.Value); } } }
/// <summary> /// Main cmdlet logic. /// </summary> protected override void ProcessRecord() { try { // Module and FullyQualifiedModule should not be specified at the same time. // Throw out terminating error if this is the case. if (Module != null && FullyQualifiedModule != null) { string errMsg = StringUtil.Format(SessionStateStrings.GetContent_TailAndHeadCannotCoexist, "Module", "FullyQualifiedModule"); ErrorRecord error = new ErrorRecord(new InvalidOperationException(errMsg), "ModuleAndFullyQualifiedModuleCannotBeSpecifiedTogether", ErrorCategory.InvalidOperation, null); ThrowTerminatingError(error); } if (!_isInitialized) { if (_path == null && Recurse.IsPresent) { PSArgumentException e = new PSArgumentException(StringUtil.Format(HelpDisplayStrings.CannotSpecifyRecurseWithoutPath)); ThrowTerminatingError(e.ErrorRecord); } _isInitialized = true; } base.Process(_module, FullyQualifiedModule); // Reset the per-runspace help cache foreach (HelpProvider provider in Context.HelpSystem.HelpProviders) { if (_stopping) { break; } provider.Reset(); } } finally { ProgressRecord progress = new ProgressRecord(activityId, HelpDisplayStrings.UpdateProgressActivityForModule, HelpDisplayStrings.UpdateProgressInstalling); progress.PercentComplete = 100; progress.RecordType = ProgressRecordType.Completed; WriteProgress(progress); } }
protected override void ProcessRecord() { string[] name = this.Name; for (int i = 0; i < (int)name.Length; i++) { string str = name[i]; try { List <PSDriveInfo> matchingDrives = base.GetMatchingDrives(str, this.PSProvider, this.Scope); if (matchingDrives.Count <= 0) { if (!WildcardPattern.ContainsWildcardCharacters(str)) { DriveNotFoundException driveNotFoundException = new DriveNotFoundException(str, "DriveNotFound", SessionStateStrings.DriveNotFound); base.WriteError(new ErrorRecord(driveNotFoundException, "GetDriveNoMatchingDrive", ErrorCategory.ObjectNotFound, str)); } } else { base.WriteObject(matchingDrives, true); } } catch (DriveNotFoundException driveNotFoundException2) { DriveNotFoundException driveNotFoundException1 = driveNotFoundException2; ErrorRecord errorRecord = new ErrorRecord(driveNotFoundException1, "GetLocationNoMatchingDrive", ErrorCategory.ObjectNotFound, str); base.WriteError(errorRecord); } catch (ProviderNotFoundException providerNotFoundException1) { ProviderNotFoundException providerNotFoundException = providerNotFoundException1; ErrorRecord errorRecord1 = new ErrorRecord(providerNotFoundException, "GetLocationNoMatchingDrive", ErrorCategory.ObjectNotFound, this.PSProvider); base.WriteError(errorRecord1); } catch (PSArgumentOutOfRangeException pSArgumentOutOfRangeException1) { PSArgumentOutOfRangeException pSArgumentOutOfRangeException = pSArgumentOutOfRangeException1; base.WriteError(new ErrorRecord(pSArgumentOutOfRangeException.ErrorRecord, pSArgumentOutOfRangeException)); } catch (PSArgumentException pSArgumentException1) { PSArgumentException pSArgumentException = pSArgumentException1; base.WriteError(new ErrorRecord(pSArgumentException.ErrorRecord, pSArgumentException)); } } }
protected override void BeginProcessing() { // Verify all arguments // Check if exe file exists in the directory string executablePath = Path.Combine(_jobDataDirectoryPath, _executableFileName); if (!File.Exists(executablePath)) { PSArgumentException ex = new PSArgumentException("File " + _executableFileName + " doesn't exist in the folder " + _jobDataDirectoryPath + ". Processing can't continue"); WriteError(new ErrorRecord(ex, "Argument Exception", ErrorCategory.OpenError, executablePath)); return; } _parametersValid = true; }
public static bool TryCreateValidUrl( string uriString, PSCmdlet cmdletPassedIn, out Uri uriResult, out ErrorRecord errorRecord) { errorRecord = null; if (Uri.TryCreate(uriString, UriKind.Absolute, out uriResult)) { return(true); } Exception ex; try { // This is needed for a relative path urlstring. Does not throw error for an absolute path. var filePath = cmdletPassedIn.SessionState.Path.GetResolvedPSPathFromPSPath(uriString)[0].Path; if (Uri.TryCreate(filePath, UriKind.Absolute, out uriResult)) { return(true); } ex = new PSArgumentException($"Invalid Uri file path: {uriString}"); } catch (Exception e) { ex = e; } errorRecord = new ErrorRecord( new PSArgumentException( $"The provided Uri is not valid: {uriString}. It must be of Uri Scheme: HTTP, HTTPS, FTP or a file path", ex), "InvalidUri", ErrorCategory.InvalidArgument, cmdletPassedIn); return(false); }
protected override void BeginProcessing() { // Does XML exist? // SessionState.Path contains the path from where the cmdlet was executed if (!Path.IsPathRooted(_xmlFilePath)) { _xmlFilePath = Path.Combine(SessionState.Path.CurrentFileSystemLocation.Path, _xmlFilePath); } if (!File.Exists(_xmlFilePath)) { PSArgumentException ex = new PSArgumentException("Configuration XML at path: " + _xmlFilePath + " doesn't exist. Processing can't continue"); WriteError(new ErrorRecord(ex, "Argument Exception", ErrorCategory.OpenError, _xmlFilePath)); return; } else { ReadConfigurationXML(_xmlFilePath); } // Validate XML parameters if (_subscriptionId.Length == 0 | _pathToManagementCertificate.Length == 0 | _mgmtCertificateEncryptedPassword.Length == 0 | _storageAccountName.Length == 0 | _affinityGroupName.Length == 0 | _storageAccountKey.Length == 0 ) { PSArgumentException ex = new PSArgumentException("Configuration XML file contains invalid data. Processing can't continue"); WriteError(new ErrorRecord(ex, "Argument Exception", ErrorCategory.InvalidData, _xmlFilePath)); return; } _parametersValid = true; }
protected override void ProcessRecord() { try { if (!this.isInitialized) { if ((this.specifiedPath || this.isLiteralPath) && !(this.specifiedPath ^ this.isLiteralPath)) { PSArgumentException exception = new PSArgumentException(StringUtil.Format(HelpDisplayStrings.CannotSpecifySourcePathAndLiteralPath, new object[0])); base.ThrowTerminatingError(exception.ErrorRecord); } if ((this._path == null) && this.Recurse.IsPresent) { PSArgumentException exception2 = new PSArgumentException(StringUtil.Format(HelpDisplayStrings.CannotSpecifyRecurseWithoutPath, new object[0])); base.ThrowTerminatingError(exception2.ErrorRecord); } this.isInitialized = true; } base.Process(this._module); foreach (HelpProvider provider in base.Context.HelpSystem.HelpProviders) { if (base._stopping) { return; } provider.Reset(); } } finally { ProgressRecord progressRecord = new ProgressRecord(base.activityId, HelpDisplayStrings.UpdateProgressActivityForModule, HelpDisplayStrings.UpdateProgressInstalling) { PercentComplete = 100, RecordType = ProgressRecordType.Completed }; base.WriteProgress(progressRecord); } }
protected override void ProcessRecord() { try { /* Retrieve domain SID of the current user. */ SecurityIdentifier domainSid; // TODO: Domain name to SID translation Cache // TODO: Get default domain from server switch (this.ParameterSetName) { case ParameterSetByLogonName: // TODO: Extract as resource: this.WriteVerbose(string.Format("Setting password hash on account {0}\\{1}.", this.Domain, this.SamAccountName)); if (this.Domain.Contains(".")) { // This is not a hard check, because dots are actually allowed in NetBIOS names, although not recommended. // TODO: Extract as a resource this.WriteWarning("The domain name supplied appears to be a DNS name instead of NetBIOS name."); } // We need to translate domain name to SID: domainSid = this.SamServer.LookupDomain(this.Domain); break; case ParameterSetBySid: if (!this.Sid.IsAccountSid()) { // Allow the processing to continue on this error: // TODO: Extract as resource: PSArgumentException ex = new PSArgumentException("The SID provided is not a account SID.", "Sid"); this.WriteError(ex.ErrorRecord); } // TODO: Extract as resource: this.WriteVerbose(string.Format("Setting password hash on account {0}.", this.Sid)); // We already know the SID: domainSid = this.Sid.AccountDomainSid; break; default: // This should never happen: throw new PSInvalidOperationException(Resources.InvalidParameterSetMessage); } /* Connect to the domain. */ using (SamDomain domain = this.SamServer.OpenDomain(domainSid, SamDomainAccessMask.Lookup)) { /* Retrieve RID of the current user. */ int userId = (this.ParameterSetName == ParameterSetBySid) ? this.Sid.GetRid() : domain.LookupUser(this.SamAccountName); /* Open the user account and reset password: */ using (SamUser user = domain.OpenUser(userId, SamUserAccessMask.ForcePasswordChange)) { user.SetPasswordHash(this.NTHash, this.LMHash); } } } catch (Win32Exception ex) { ErrorCategory category = ((Win32ErrorCode)ex.NativeErrorCode).ToPSCategory(); object identity = (this.Sid != null) ? this.Sid.ToString() : this.SamAccountName; ErrorRecord error = new ErrorRecord(ex, "WinAPIErrorProcess", category, identity); // Allow the processing to continue on this error: this.WriteError(error); } }
/// <summary> /// Saves the current console info into a file. /// </summary> protected override void ProcessRecord() { // Get filename.. string file = GetFileName(); // if file is null or empty..prompt the user for filename if (string.IsNullOrEmpty(file)) { file = PromptUserForFile(); } // if file is still empty..write error and back out.. if (string.IsNullOrEmpty(file)) { PSArgumentException ae = PSTraceSource.NewArgumentException("file", ConsoleInfoErrorStrings.FileNameNotResolved); ThrowError(file, "FileNameNotResolved", ae, ErrorCategory.InvalidArgument); } if (WildcardPattern.ContainsWildcardCharacters(file)) { ThrowError(file, "WildCardNotSupported", PSTraceSource.NewInvalidOperationException(ConsoleInfoErrorStrings.ConsoleFileWildCardsNotSupported, file), ErrorCategory.InvalidOperation); } // Ofcourse, you cant write to a file from HKLM: etc.. string resolvedPath = ResolveProviderAndPath(file); // If resolvedPath is empty just return.. if (string.IsNullOrEmpty(resolvedPath)) { return; } // Check whether the file ends with valid extension if (!resolvedPath.EndsWith(StringLiterals.PowerShellConsoleFileExtension, StringComparison.OrdinalIgnoreCase)) { // file does not end with proper extension..create one.. resolvedPath = resolvedPath + StringLiterals.PowerShellConsoleFileExtension; } if (!ShouldProcess(this.Path)) // should this be resolvedPath? { return; } //check if destination file exists. if (File.Exists(resolvedPath)) { if (NoClobber) { string message = StringUtil.Format( ConsoleInfoErrorStrings.FileExistsNoClobber, resolvedPath, "NoClobber"); // prevents localization Exception uae = new UnauthorizedAccessException(message); ErrorRecord errorRecord = new ErrorRecord( uae, "NoClobber", ErrorCategory.ResourceExists, resolvedPath); // NOTE: this call will throw ThrowTerminatingError(errorRecord); } // Check if the file is read-only System.IO.FileAttributes attrib = System.IO.File.GetAttributes(resolvedPath); if ((attrib & System.IO.FileAttributes.ReadOnly) == System.IO.FileAttributes.ReadOnly) { if (Force) { RemoveFileThrowIfError(resolvedPath); // Note, we do not attempt to set read-only on the new file } else { ThrowError(file, "ConsoleFileReadOnly", PSTraceSource.NewArgumentException(file, ConsoleInfoErrorStrings.ConsoleFileReadOnly, resolvedPath), ErrorCategory.InvalidArgument); } } } try { if (this.Runspace != null) { this.Runspace.SaveAsConsoleFile(resolvedPath); } else if (InitialSessionState != null) { this.InitialSessionState.SaveAsConsoleFile(resolvedPath); } else { Dbg.Assert(false, "Both RunspaceConfiguration and InitialSessionState should not be null"); throw PSTraceSource.NewInvalidOperationException(ConsoleInfoErrorStrings.CmdletNotAvailable); } } catch (PSArgumentException mae) { ThrowError(resolvedPath, "PathNotAbsolute", mae, ErrorCategory.InvalidArgument); } catch (PSArgumentNullException mane) { ThrowError(resolvedPath, "PathNull", mane, ErrorCategory.InvalidArgument); } catch (ArgumentException ae) { ThrowError(resolvedPath, "InvalidCharactersInPath", ae, ErrorCategory.InvalidArgument); } // looks like saving succeeded. // Now try changing $console Exception e = null; try { //Update $Console variable Context.EngineSessionState.SetConsoleVariable(); } catch (ArgumentNullException ane) { e = ane; } catch (ArgumentOutOfRangeException aor) { e = aor; } catch (ArgumentException ae) { e = ae; } catch (SessionStateUnauthorizedAccessException sue) { e = sue; } catch (SessionStateOverflowException sof) { e = sof; } catch (ProviderNotFoundException pnf) { e = pnf; } catch (System.Management.Automation.DriveNotFoundException dnfe) { e = dnfe; } catch (NotSupportedException ne) { e = ne; } catch (ProviderInvocationException pin) { e = pin; } if (e != null) { throw PSTraceSource.NewInvalidOperationException(e, ConsoleInfoErrorStrings.ConsoleVariableCannotBeSet, resolvedPath); } }