Utilities.cs (2618B)
1 // ----------------------------------------------------------------------------- 2 // <copyright file="Utilities.cs" company="Microsoft Corporation"> 3 // Copyright (c) Microsoft Corporation. Licensed under the MIT License. 4 // </copyright> 5 // ----------------------------------------------------------------------------- 6 7 namespace Microsoft.WinGet.Configuration.Helpers 8 { 9 using System; 10 using System.Linq; 11 using System.Management.Automation; 12 using Microsoft.PowerShell; 13 14 /// <summary> 15 /// Utilities for this cmdlets. 16 /// </summary> 17 internal static class Utilities 18 { 19 /// <summary> 20 /// Gets the execution policy. 21 /// </summary> 22 /// <returns>ExecutionPolicy.</returns> 23 public static ExecutionPolicy GetExecutionPolicy() 24 { 25 var ps = PowerShell.Create(RunspaceMode.CurrentRunspace); 26 return ps.AddCommand("Get-ExecutionPolicy").Invoke<ExecutionPolicy>().First(); 27 } 28 29 /// <summary> 30 /// Determine if telemetry can be used. It follows the same telemetry rules as PowerShell. 31 /// To opt-out of this telemetry, set the environment variable $env:POWERSHELL_TELEMETRY_OPTOUT to true, yes, or 1. 32 /// This method is the same as GetEnvironmentVariableAsBool from PowerShell but only for POWERSHELL_TELEMETRY_OPTOUT. 33 /// </summary> 34 /// <returns>If telemetry can be used.</returns> 35 public static bool CanUseTelemetry() 36 { 37 var str = Environment.GetEnvironmentVariable("POWERSHELL_TELEMETRY_OPTOUT"); 38 if (string.IsNullOrEmpty(str)) 39 { 40 return true; 41 } 42 43 var boolStr = str.AsSpan(); 44 45 if (boolStr.Length == 1) 46 { 47 if (boolStr[0] == '1') 48 { 49 return false; 50 } 51 } 52 53 if (boolStr.Length == 3 && 54 (boolStr[0] == 'y' || boolStr[0] == 'Y') && 55 (boolStr[1] == 'e' || boolStr[1] == 'E') && 56 (boolStr[2] == 's' || boolStr[2] == 'S')) 57 { 58 return false; 59 } 60 61 if (boolStr.Length == 4 && 62 (boolStr[0] == 't' || boolStr[0] == 'T') && 63 (boolStr[1] == 'r' || boolStr[1] == 'R') && 64 (boolStr[2] == 'u' || boolStr[2] == 'U') && 65 (boolStr[3] == 'e' || boolStr[3] == 'E')) 66 { 67 return false; 68 } 69 70 return true; 71 } 72 } 73 }