From ca9c890dd1c942839e805584aa5e0ffc9f7bcd0f Mon Sep 17 00:00:00 2001 From: Daniel Llewellyn Date: Wed, 31 Jan 2018 10:19:48 -0800 Subject: [PATCH] Add Environment Variable override of telemetry (#6063) Inspired by dotnet cli, and allows for Telemetry opt-out on packaging systems such as AppImage and Snapcraft where the filesystem is immutable. --- .../host/msh/Telemetry.cs | 39 ++++++++++++++++--- 1 file changed, 33 insertions(+), 6 deletions(-) diff --git a/src/Microsoft.PowerShell.ConsoleHost/host/msh/Telemetry.cs b/src/Microsoft.PowerShell.ConsoleHost/host/msh/Telemetry.cs index 58987b322a..ac035ba730 100644 --- a/src/Microsoft.PowerShell.ConsoleHost/host/msh/Telemetry.cs +++ b/src/Microsoft.PowerShell.ConsoleHost/host/msh/Telemetry.cs @@ -21,6 +21,7 @@ namespace Microsoft.PowerShell // The name of the file by when present in $PSHOME will enable telemetry. // If this file is not present, no telemetry will be sent. private const string TelemetrySemaphoreFilename = "DELETE_ME_TO_DISABLE_CONSOLEHOST_TELEMETRY"; + private const string TelemetryOptoutEnvVar = "POWERSHELL_TELEMETRY_OPTOUT"; // The path to the semaphore file which enables telemetry private static string TelemetrySemaphoreFilePath = Path.Combine( @@ -42,6 +43,28 @@ namespace Microsoft.PowerShell TelemetryConfiguration.Active.TelemetryChannel.DeveloperMode = _developerMode; } + private static bool GetEnvironmentVariableAsBool(string name, bool defaultValue) { + var str = Environment.GetEnvironmentVariable(name); + if (string.IsNullOrEmpty(str)) + { + return defaultValue; + } + + switch (str.ToLowerInvariant()) + { + case "true": + case "1": + case "yes": + return true; + case "false": + case "0": + case "no": + return false; + default: + return defaultValue; + } + } + /// /// Send the telemetry /// @@ -50,14 +73,18 @@ namespace Microsoft.PowerShell try { // if the semaphore file exists, try to send telemetry - if (Utils.NativeFileExists(TelemetrySemaphoreFilePath)) + var enabled = Utils.NativeFileExists(TelemetrySemaphoreFilePath) && !GetEnvironmentVariableAsBool(TelemetryOptoutEnvVar, false); + + if (!enabled) { - if ( _telemetryClient == null ) - { - _telemetryClient = new TelemetryClient(); - } - _telemetryClient.TrackEvent(eventName, payload, null); + return; } + + if (_telemetryClient == null) + { + _telemetryClient = new TelemetryClient(); + } + _telemetryClient.TrackEvent(eventName, payload, null); } catch (Exception) {