public void ExecuteCmdletBase(PSCmdlet callingCmdlet) { using (MappingToolDatabaseDataContext dataContext = new MappingToolDatabaseDataContext(ConnectionString)) { dataContext.CommandTimeout = 180; if (DomainId != Guid.Empty) { /// Find domains by domain ID. /// Model.Domain domain = GetDomainById(dataContext, DomainId); callingCmdlet.WriteObject(domain); } else if (!string.IsNullOrEmpty(DomainName)) { /// Find domains by domain name. /// List <Model.Domain> domains = GetDomainsByName(dataContext, DomainName); callingCmdlet.WriteObject(domains, true); } else { /// Find all domains. /// List <Model.Domain> domains = GetAllDomains(dataContext); callingCmdlet.WriteObject(domains, true); } } }
public void ExecuteCmdletBase(PSCmdlet callingCmdlet) { if (Domain == null) { callingCmdlet.WriteWarning("No valid domain has been provided."); return; } if (!Domain.CheckIsValid()) { callingCmdlet.WriteWarning("An invalid domain object has been provided."); return; } Model.IDatabaseInfo dbInfo = Domain; using (MappingToolDatabaseDataContext dataContext = new MappingToolDatabaseDataContext(dbInfo.ConnectionString)) { dataContext.CommandTimeout = 180; if (MapId != Guid.Empty) { /// Find maps by ID. /// Model.Map map = GetMapById(dataContext, MapId); callingCmdlet.WriteObject(map); } else if (!string.IsNullOrEmpty(MapName)) { /// Find maps by name. /// List <Model.Map> maps = GetMapsByName(dataContext, MapName); callingCmdlet.WriteObject(maps, true); } else { /// Fine all maps. /// List <Model.Map> maps = GetAllMaps(dataContext); callingCmdlet.WriteObject(maps, true); } } }
/// <summary> /// Execute the given cmdlet in powershell with the given parameters after injecting the given exception. It is expected that the cmdlet has a runtime that can be used for receiving output /// </summary> /// <typeparam name="T"></typeparam> /// <param name="cmdlet">The cmdlet to execute</param> /// <param name="name">The name of the cmdlet</param> /// <param name="exception">The exception to inject into the error stream</param> /// <param name="cmdletParameters">The parameters to pass to the cmdlet on the pipeline</param> public static void ExecuteCmdletWithExceptionInPipeline <T>(this PSCmdlet cmdlet, string name, Exception exception, params KeyValuePair <string, object>[] cmdletParameters) { List <T> output = new List <T>(); using (System.Management.Automation.PowerShell powershell = System.Management.Automation.PowerShell.Create(RunspaceMode.NewRunspace)) { var info = new CmdletInfo(name, cmdlet.GetType()); powershell.AddCommand("Write-Error"); powershell.AddParameter("Exception", exception); powershell.Invoke(); powershell.Commands.Clear(); powershell.AddCommand(info); foreach (var pair in cmdletParameters) { if (pair.Value == null) { powershell.AddParameter(pair.Key); } else { powershell.AddParameter(pair.Key, pair.Value); } } Collection <T> result = powershell.Invoke <T>(); powershell.Streams.Error.ForEach(cmdlet.WriteError); powershell.Streams.Debug.ForEach(d => cmdlet.WriteDebug(d.Message)); powershell.Streams.Verbose.ForEach(v => cmdlet.WriteWarning(v.Message)); powershell.Streams.Warning.ForEach(w => cmdlet.WriteWarning(w.Message)); if (result != null && result.Count > 0) { result.ForEach(r => cmdlet.WriteObject(r)); } } }
public void ExecuteCmdletBase(PSCmdlet callingCmdlet) { ManagementService client = CreateManagementServiceClient(); var relyingParties = client.RelyingParties; List <string> relyingPartyRelayAddresses = new List <string>(); long relyingPartyId = -1; foreach (var relyingParty in relyingParties) { string name = relyingParty.Name; if (name == RelyingParty) { relyingPartyId = relyingParty.Id; } } foreach (RelyingPartyAddress address in client.RelyingPartyAddresses) { if (address.RelyingPartyId == relyingPartyId) { relyingPartyRelayAddresses.Add(address.Address); } } callingCmdlet.WriteObject(relyingPartyRelayAddresses, true);; }
internal static void HandleFaultedJob(PSCmdlet invokeAll, Job faultedJob, bool returnAsJobObject, bool noFileLogging = false) { LogHelper.Log(fileVerboseLogTypes, string.Format("Job: {0} is faulted.", faultedJob.ID), invokeAll, noFileLogging); if (returnAsJobObject) { invokeAll.WriteObject(faultedJob); } else { if (faultedJob.IsFaulted == true) { foreach (var e in faultedJob.Exceptions.InnerExceptions) { if (e is RemoteException re) { LogHelper.Log(fileErrorLogTypes, re.ErrorRecord, invokeAll, noFileLogging); } else { LogHelper.Log(fileErrorLogTypes, ((ActionPreferenceStopException)e).ErrorRecord, invokeAll, noFileLogging); } } } if (faultedJob.PowerShell.Streams.Error.Count > 0) { foreach (ErrorRecord errorRecord in faultedJob.PowerShell.Streams.Error) { LogHelper.Log(fileErrorLogTypes, errorRecord, invokeAll, noFileLogging); } } } }
public void Write(Verbosity verbosity, LogLevel level, string format, params object[] args) { switch (level) { case LogLevel.Error: case LogLevel.Fatal: _cmdlet.WriteWarning(string.Format(format, args)); return; case LogLevel.Warning: _cmdlet.WriteWarning(string.Format(format, args)); return; case LogLevel.Information: _cmdlet.WriteObject(string.Format(format, args)); return; case LogLevel.Verbose: _cmdlet.WriteVerbose(string.Format(format, args)); return; case LogLevel.Debug: _cmdlet.WriteDebug(string.Format(format, args)); return; default: throw new InvalidOperationException("Invalid log level."); } }
public void RunWebAppContainerPSSessionScript(PSCmdlet cmdlet, string resourceGroupName, string webSiteName, string slotName = null, bool newPSSession = false) { Version psCurrentVersion = GetPsVersion(cmdlet); Version psCore = new Version(6, 0); if (psCurrentVersion.CompareTo(psCore) < 0) { // Running on PowerShell 5.1. Assume Windows. // Validate if WSMAN Basic Authentication is enabled bool isBasicAuthEnabled = ExecuteScriptAndGetVariableAsBool(cmdlet, "${0} = (Get-Item WSMAN:\\LocalHost\\Client\\Auth\\Basic -ErrorAction SilentlyContinue).Value", false); if (!isBasicAuthEnabled) { // Ask user to enable basic auth WriteWarning(Properties.Resources.EnterCotnainerPSSessionBasicAuthWarning); return; } // Validate if we can connect given the existing TrustedHosts string defaultTrustedHostsScriptResult = "<empty or non-existent>"; string trustedHostsScriptResult = ExecuteScriptAndGetVariable(cmdlet, "${0} = (Get-Item WSMAN:\\LocalHost\\Client\\TrustedHosts -ErrorAction SilentlyContinue).Value", defaultTrustedHostsScriptResult); Regex expression = new Regex(@"^\*$|((^\*|^" + (string.IsNullOrWhiteSpace(slotName)? webSiteName : webSiteName + "-" + slotName) + ").azurewebsites.net)"); if (trustedHostsScriptResult.Split(',').Where(h => expression.IsMatch(h)).Count() < 1) { WriteWarning(string.Format(Properties.Resources.EnterContainerPSSessionFormatForTrustedHostsWarning, string.IsNullOrWhiteSpace(trustedHostsScriptResult) ? defaultTrustedHostsScriptResult: trustedHostsScriptResult) + Environment.NewLine + Environment.NewLine + string.Format(@Properties.Resources.EnterContainerPSSessionFormatForTrustedHostsSuggestion, string.IsNullOrWhiteSpace(trustedHostsScriptResult) ? string.Empty : trustedHostsScriptResult + ",", (string.IsNullOrWhiteSpace(slotName) ? webSiteName : webSiteName + "-" + slotName))); return; } } Site site = GetWebApp(resourceGroupName, webSiteName, slotName); User user = GetPublishingCredentials(resourceGroupName, webSiteName, slotName); const string webAppContainerPSSessionVarPrefix = "webAppPSSession"; string publishingUserName = user.PublishingUserName.Length <= 20 ? user.PublishingUserName : user.PublishingUserName.Substring(0, 20); string psSessionScript = string.Format("${3}User = '******' \n${3}Password = ConvertTo-SecureString -String '{1}' -AsPlainText -Force \n" + "${3}Credential = New-Object -TypeName PSCredential -ArgumentList ${3}User, ${3}Password\n" + (newPSSession ? "${3}NewPsSession = New-PSSession" : "Enter-PSSession") + " -ConnectionUri https://{2}/WSMAN -Authentication Basic -Credential ${3}Credential \n", publishingUserName, user.PublishingPassword, site.DefaultHostName, webAppContainerPSSessionVarPrefix); cmdlet.ExecuteScript <object>(psSessionScript); if (newPSSession) { cmdlet.WriteObject(cmdlet.GetVariableValue(string.Format("{0}NewPsSession", webAppContainerPSSessionVarPrefix))); } cmdlet.ExecuteScript <object>(string.Format("Clear-Variable {0}*", webAppContainerPSSessionVarPrefix)); //Clearing session variable }
public static void SafeWriteObject(this PSCmdlet psCmdlet, object sendToPipeline, bool enumerateCollection) { try { psCmdlet.WriteObject(sendToPipeline, enumerateCollection); } catch (Exception) { // Do nothing } }
/// <summary> /// Overrides OnDefault method in the generated cmdlets. /// </summary> /// <param name="cmdlet">The calling <see cref="PSCmdlet"/></param> /// <param name="responseMessage">The HTTP response message from the service.</param> /// <param name="returnNow">Determines whether the caller should return after OverrideOnDefault is called, or not. </param> public static void OverrideOnDefault(this PSCmdlet cmdlet, global::System.Net.Http.HttpResponseMessage responseMessage, ref global::System.Threading.Tasks.Task <bool> returnNow) { if (responseMessage.IsSuccessStatusCode) { if (cmdlet.MyInvocation?.BoundParameters?.ContainsKey("PassThru") == true) { cmdlet.WriteObject(true); } returnNow = global::System.Threading.Tasks.Task <bool> .FromResult(true); } }
public static void Page <T>(PSCmdlet cmdlet, params T[] items) { int resultsCount = items.Length; if (resultsCount > 0) { if (cmdlet.PagingParameters.Skip >= (ulong)resultsCount) { cmdlet.WriteWarning("No results satisfy the paging parameters"); } else { ulong firstNumber = cmdlet.PagingParameters.Skip; ulong lastNumber = firstNumber + Math.Min( cmdlet.PagingParameters.First, (ulong)resultsCount - cmdlet.PagingParameters.Skip ); for (ulong i = firstNumber; i < lastNumber; i++) { cmdlet.WriteObject(items[i]); } } if (cmdlet.PagingParameters.IncludeTotalCount) { const double accuracy = 1.0; PSObject totalCountResult = cmdlet.PagingParameters.NewTotalCount((ulong)resultsCount, accuracy); cmdlet.WriteObject("\r\n\r\n"); cmdlet.WriteObject(totalCountResult); } } else { cmdlet.WriteWarning("No results generated. The query returned 0 items."); } }
public void ExecuteCmdletBase(PSCmdlet callingCmdlet) { ManagementService client = CreateManagementServiceClient(); var relyingParties = client.RelyingParties; List <string> relyingPartyNames = new List <string>(); foreach (var relyingParty in relyingParties) { string name = relyingParty.Name; relyingPartyNames.Add(name); } callingCmdlet.WriteObject(relyingPartyNames, true); }
/// <summary> /// 各Job内のCodeを順次実行 /// </summary> /// <param name="job"></param> /// <param name="shell"></param> /// <returns></returns> private bool ProcessStartJob(Job job, PowerShell shell) { _record.PercentComplete += 100 / _jobCount; _record.StatusDescription = $"進捗 {_record.PercentComplete} % : {job.Title}"; _cmdlet.WriteProgress(_record); // CodeOptionをセット job.SetCodeOption(); // Ignoreオプションで実行しないように if (!string.IsNullOrEmpty(job.Code) && !job.CheckOption(CodeOption.Ignore)) { shell.AddScript(job.Code); PSObject lastPSObject = null; // コンソール出力する/しない if (job.CheckOption(CodeOption.ConsoleOut)) { foreach (PSObject ps in shell.Invoke()) { _cmdlet.WriteObject(ps); lastPSObject = ps; } } else { foreach (PSObject ps in shell.Invoke()) { lastPSObject = ps; } } shell.Commands.Clear(); // Stepオプションで一時停止 if (_debugMode || job.CheckOption(CodeOption.Step)) { _record.CurrentOperation = "Pause:" + job.Title; _cmdlet.WriteProgress(_record); _record.CurrentOperation = null; Console.ReadLine(); } // 最後に実行したコードの結果がfalseならば終了 // ※Code内でBoolean型を返す記述がない場合、この処理は無視 if (job.CheckOption(CodeOption.StopLastFalse) && lastPSObject != null && lastPSObject.BaseObject is Boolean) { if (!(bool)lastPSObject.BaseObject) { return(false); } } } foreach (Job subJob in job.JobList) { bool ret = ProcessStartJob(subJob, shell); if (!ret) { break; } } return(true); }
internal void Import() { CreateFileStream(); _deserializer = new Deserializer(_xr); // If total count has been requested, return a dummy object with zero confidence if (_cmdlet.PagingParameters.IncludeTotalCount) { PSObject totalCount = _cmdlet.PagingParameters.NewTotalCount(0, 0); _cmdlet.WriteObject(totalCount); } ulong skip = _cmdlet.PagingParameters.Skip; ulong first = _cmdlet.PagingParameters.First; // if paging is not specified then keep the old V2 behavior if (skip == 0 && first == ulong.MaxValue) { while (!_deserializer.Done()) { object result = _deserializer.Deserialize(); _cmdlet.WriteObject(result); } } // else try to flatten the output if possible else { ulong skipped = 0; ulong count = 0; while (!_deserializer.Done() && count < first) { object result = _deserializer.Deserialize(); PSObject psObject = result as PSObject; if (psObject != null) { ICollection c = psObject.BaseObject as ICollection; if (c != null) { foreach (object o in c) { if (count >= first) { break; } if (skipped++ >= skip) { count++; _cmdlet.WriteObject(o); } } } else { if (skipped++ >= skip) { count++; _cmdlet.WriteObject(result); } } } else if (skipped++ >= skip) { count++; _cmdlet.WriteObject(result); continue; } } } }
public void WriteLine(object message) { _cmdLet.WriteObject(new string[] { message.ToString() }); }
internal static void WriteFormattedMessage(PSCmdlet cmdlet, Message message) { if (cmdlet.Host.Name == "ConsoleHost") { var messageLines = new List <string>(); messageLines.AddRange(message.Text.Split(new[] { '\n' })); var wrappedText = new List <string>(); foreach (var messageLine in messageLines.Select(l => l == "\n" ? " \n" : l)) { wrappedText.AddRange(WordWrap(messageLine, cmdlet.Host.UI.RawUI.MaxWindowSize.Width - 8)); } var notificationColor = "\x1B[7m"; var resetColor = "\x1B[0m"; var outMessage = string.Empty; foreach (var wrappedLine in wrappedText) { var lineToAdd = string.Empty; if (wrappedLine == "") { lineToAdd = "\x00A0".PadRight(cmdlet.Host.UI.RawUI.MaxWindowSize.Width - 8); } else { lineToAdd = wrappedLine.PadRight(cmdlet.Host.UI.RawUI.MaxWindowSize.Width - 8); } outMessage += $" {lineToAdd}\n"; } switch (message.Type) { case MessageType.Message: { cmdlet.WriteObject($"{notificationColor}\n{outMessage}{resetColor}\n"); break; } case MessageType.Warning: { cmdlet.WriteWarning($"{notificationColor}\n{outMessage}{resetColor}\n"); break; } } } else { switch (message.Type) { case MessageType.Message: { cmdlet.WriteObject(message.Text); break; } case MessageType.Warning: { cmdlet.WriteWarning(message.Text); break; } } } }
/// <summary> /// Logs the message. /// </summary> /// <param name="message">The message.</param> public void LogMessage(string message) { _cmdlet.WriteObject(message); }
public void RunWebAppContainerPSSessionScript(PSCmdlet cmdlet, string resourceGroupName, string webSiteName, string slotName = null, bool newPSSession = false) { string operatingSystem = GetPsOperatingSystem(cmdlet); Version minimumVersion = new Version(6, 1, 0, 0); WriteVerbose("Operating System: {0}", operatingSystem); if (operatingSystem.IndexOf("windows", StringComparison.InvariantCultureIgnoreCase) == -1) { // If OS is not Windows, check if Ps supports 6.1.0 which is the first version to depend on NetCoreApp 2.1 List <Version> compatibleVersions = GetPsCompatibleVersions(cmdlet); foreach (Version version in compatibleVersions) { WriteVerbose("Compatible version: {0}", version.ToString()); } // if there are no compatible versions subsequent to the minimum versions, we don't continue because the command will fail if (compatibleVersions.Where(v => v.CompareTo(minimumVersion) > 0).Count() == 0) { WriteError(Properties.Resources.EnterContainerPSSessionPSCoreVersionNotSupported); return; } } // For Windows, we validate WSMAN trusted hosts settings if (operatingSystem.IndexOf("windows", StringComparison.InvariantCultureIgnoreCase) > 0) { // Validate if WSMAN Basic Authentication is enabled bool isBasicAuthEnabled = ExecuteScriptAndGetVariableAsBool(cmdlet, "${0} = (Get-Item WSMAN:\\LocalHost\\Client\\Auth\\Basic -ErrorAction SilentlyContinue).Value", false); if (!isBasicAuthEnabled) { // Ask user to enable basic auth WriteWarning(Properties.Resources.EnterCotnainerPSSessionBasicAuthWarning); return; } // Validate if we can connect given the existing TrustedHosts string defaultTrustedHostsScriptResult = "<empty or non-existent>"; string trustedHostsScriptResult = ExecuteScriptAndGetVariable(cmdlet, "${0} = (Get-Item WSMAN:\\LocalHost\\Client\\TrustedHosts -ErrorAction SilentlyContinue).Value", defaultTrustedHostsScriptResult); Regex expression = new Regex(@"^\*$|((^\*|^" + (string.IsNullOrWhiteSpace(slotName)? webSiteName : webSiteName + "-" + slotName) + ").azurewebsites.net)"); if (trustedHostsScriptResult.Split(',').Where(h => expression.IsMatch(h)).Count() < 1) { WriteWarning(string.Format(Properties.Resources.EnterContainerPSSessionFormatForTrustedHostsWarning, string.IsNullOrWhiteSpace(trustedHostsScriptResult) ? defaultTrustedHostsScriptResult: trustedHostsScriptResult) + Environment.NewLine + Environment.NewLine + string.Format(@Properties.Resources.EnterContainerPSSessionFormatForTrustedHostsSuggestion, string.IsNullOrWhiteSpace(trustedHostsScriptResult) ? string.Empty : trustedHostsScriptResult + ",", (string.IsNullOrWhiteSpace(slotName) ? webSiteName : webSiteName + "-" + slotName))); return; } } Site site = GetWebApp(resourceGroupName, webSiteName, slotName); User user = GetPublishingCredentials(resourceGroupName, webSiteName, slotName); const string webAppContainerPSSessionVarPrefix = "webAppPSSession"; string publishingUserName = user.PublishingUserName.Length <= 20 ? user.PublishingUserName : user.PublishingUserName.Substring(0, 20); string psSessionScript = string.Format("${3}User = '******' \n${3}Password = ConvertTo-SecureString -String '{1}' -AsPlainText -Force \n" + "${3}Credential = New-Object -TypeName PSCredential -ArgumentList ${3}User, ${3}Password\n" + (newPSSession ? "${3}NewPsSession = New-PSSession" : "Enter-PSSession") + " -ConnectionUri https://{2}/WSMAN -Authentication Basic -Credential ${3}Credential \n", publishingUserName, user.PublishingPassword, site.DefaultHostName, webAppContainerPSSessionVarPrefix); cmdlet.ExecuteScript <object>(psSessionScript); if (newPSSession) { cmdlet.WriteObject(cmdlet.GetVariableValue(string.Format("{0}NewPsSession", webAppContainerPSSessionVarPrefix))); } cmdlet.ExecuteScript <object>(string.Format("Clear-Variable {0}*", webAppContainerPSSessionVarPrefix)); //Clearing session variable }
internal static Job CollectJob(PSCmdlet invokeAll, Job job, bool returnAsJobObject, bool force, bool appendJobNameToResult, bool noFileLogging = false) { LogHelper.LogDebug(string.Format("Collecting JobID:{0}", job.ID), invokeAll); if (job.IsFaulted == true || job.PowerShell.HadErrors == true) { if (!force && job.ID == 1) { job.IsFaulted = true; LogHelper.Log(fileVerboseLogTypes, "There was an error from First job, will stop queueing jobs.", invokeAll, noFileLogging); if (job.Exceptions != null) { throw job.Exceptions; } else { List <Exception> jobExceptions = new List <Exception>(); foreach (ErrorRecord errorRecord in job.PowerShell.Streams.Error) { jobExceptions.Add(errorRecord.Exception); } throw new AggregateException(jobExceptions); } } else { HandleFaultedJob(invokeAll, job, returnAsJobObject); } } else { if (returnAsJobObject) { invokeAll.WriteObject(job); } else { if (job.JobTask.Result?.Count > 0) { foreach (PSObject result in job.JobTask.Result) { if (appendJobNameToResult) { result.Members.Add(new PSNoteProperty("PSJobName", job.JobName)); } invokeAll.WriteObject(result); } } else { LogHelper.Log(fileVerboseLogTypes, string.Format("JobID:{0} JobName: {1} has no result to be appened to the output. IsJobCompleted:{2}, IsJobFaulted:{3}", job.ID, job.JobName, job.JobTask.IsCompleted.ToString(), job.IsFaulted.ToString()), invokeAll, noFileLogging); } } } job.IsCollected = true; return(job); }