diff --git a/src/Microsoft.PowerShell.Commands.Management/commands/management/Clipboard.cs b/src/Microsoft.PowerShell.Commands.Management/commands/management/Clipboard.cs index 5ce64350fbd..45e2a183b3e 100644 --- a/src/Microsoft.PowerShell.Commands.Management/commands/management/Clipboard.cs +++ b/src/Microsoft.PowerShell.Commands.Management/commands/management/Clipboard.cs @@ -19,7 +19,8 @@ internal static class Clipboard private static string StartProcess( string tool, string args, - string stdin = "") + string stdin = "", + bool readStdout = true) { ProcessStartInfo startInfo = new(); startInfo.UseShellExecute = false; @@ -28,7 +29,7 @@ private static string StartProcess( startInfo.RedirectStandardError = true; startInfo.FileName = tool; startInfo.Arguments = args; - string stdout; + string stdout = string.Empty; using (Process process = new()) { @@ -43,15 +44,15 @@ private static string StartProcess( return string.Empty; } - if (!string.IsNullOrEmpty(stdin)) + process.StandardInput.Write(stdin); + process.StandardInput.Close(); + + if (readStdout) { - process.StandardInput.Write(stdin); - process.StandardInput.Close(); + stdout = process.StandardOutput.ReadToEnd(); } - stdout = process.StandardOutput.ReadToEnd(); process.WaitForExit(250); - _clipboardSupported = process.ExitCode == 0; } @@ -93,11 +94,6 @@ public static string GetText() public static void SetText(string text) { - if (string.IsNullOrEmpty(text)) - { - return; - } - if (_clipboardSupported == false) { _internalClipboard = text; @@ -114,7 +110,14 @@ public static void SetText(string text) else if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux)) { tool = "xclip"; - args = "-selection clipboard -in"; + if (string.IsNullOrEmpty(text)) + { + args = "-selection clipboard /dev/null"; + } + else + { + args = "-selection clipboard -in"; + } } else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX)) { @@ -126,7 +129,7 @@ public static void SetText(string text) return; } - StartProcess(tool, args, text); + StartProcess(tool, args, text, readStdout: false); if (_clipboardSupported == false) { _internalClipboard = text; diff --git a/test/powershell/Modules/Microsoft.PowerShell.Management/Clipboard.Tests.ps1 b/test/powershell/Modules/Microsoft.PowerShell.Management/Clipboard.Tests.ps1 index d28394c9f26..8cfc07b8755 100644 --- a/test/powershell/Modules/Microsoft.PowerShell.Management/Clipboard.Tests.ps1 +++ b/test/powershell/Modules/Microsoft.PowerShell.Management/Clipboard.Tests.ps1 @@ -41,5 +41,15 @@ Describe 'Clipboard cmdlet tests' -Tag CI { 'world' | Set-Clipboard -Append Get-Clipboard -Raw | Should -BeExactly "hello$([Environment]::NewLine)world" } + + It 'Set-Clipboard accepts string' -TestCases @( + @{ value = 'empty'; text = "" } + @{ value = 'null' ; text = $null } + ){ + param ($text) + + $text | Set-Clipboard + Get-Clipboard -Raw | Should -BeNullOrEmpty + } } }