本文整理汇总了C#中System.Management.Automation.PSCmdlet.ThrowTerminatingError方法的典型用法代码示例。如果您正苦于以下问题:C# PSCmdlet.ThrowTerminatingError方法的具体用法?C# PSCmdlet.ThrowTerminatingError怎么用?C# PSCmdlet.ThrowTerminatingError使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类System.Management.Automation.PSCmdlet
的用法示例。
在下文中一共展示了PSCmdlet.ThrowTerminatingError方法的14个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: ResolvePath
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: GetGraphicalHostReflectionWrapper
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;
}
示例3: CreateModuleDirectory
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;
}
示例4: ResetMachineAccountPassword
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
//.........这里部分代码省略.........
示例5: ThrowOutLsaError
/// <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);
}
示例6: ResolvePath
/// <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));
}
}
//.........这里部分代码省略.........
示例7: MasterStreamOpen
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);
}
}
示例8: ResetMachineAccountPassword
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
{
//.........这里部分代码省略.........
示例9: GetGraphicalHostReflectionWrapper
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;
}
示例10: CombineHashTableOrStringArray
/// <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();
}
示例11: MasterStreamOpen
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);
}
}
示例12: GenerateCatalog
/// <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;
}
示例13: MasterStreamOpen
//.........这里部分代码省略.........
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
示例14: CreateModuleDirectory
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;
}