3

I have a powershell script that is hashing the MAC address, then posting it into a file and a clipboard.

$hash = [System.BitConverter]::ToString($md5.ComputeHash($utf8.GetBytes($MAC)))
$hash | clip
$hash | Out-File $Env:USERPROFILE\Desktop\this.txt 

The issue I am having is that a carriage return is being exported to the clipboard. I don't want that.

Is there a way of stopping that happening?

Additional info - When I paste the text that is on the clipboard into a hex editor I see 0D0A

The clipboard function would be fine if I could just loose that some how? Thanks

1
  • By the way, that's actually two characters: CR (carriage return) and LF (line feed). In other words, a Windows new line.
    – Bob
    Jul 19, 2013 at 6:06

3 Answers 3

1

If you can use PowerShell 5.0 or higher, Set-Clipboard is available. It does not add any newline characters. So, your example would become:

$hash = [System.BitConverter]::ToString($md5.ComputeHash($utf8.GetBytes($MAC)))
$hash | Set-Clipboard
$hash | Out-File $Env:USERPROFILE\Desktop\this.txt
1
  • If you're like me and keep forgetting: Set-Alias clip Set-Clipboard
    – Vimes
    Oct 10, 2017 at 15:49
0

$Hash.TrimEnd() should clear any unicode whitespace at the end of the string. http://msdn.microsoft.com/en-us/library/system.string.trimend.aspx

1
  • 2
    That does not actually work. My theory is that clip itself inserts the newline.
    – Bob
    Jul 19, 2013 at 6:04
0

Unfortunately, it looks like clip itself appends the newline. So, let's do it the .NET way!

Here's a function that takes stdin and puts it in the clipboard:

function Out-ClipboardText
{
    param(  
        [Parameter(
            Position=0, 
            Mandatory=$true, 
            ValueFromPipeline=$true)
        ]
        [String]$text
    ) 

    process
    {
        powershell -sta -noprofile -command "add-type -an system.windows.forms; [System.Windows.Forms.Clipboard]::SetText('$text')"
    }
}

Adapted from http://brianreiter.org/2010/09/03/copy-and-paste-with-clipboard-from-powershell/ and https://stackoverflow.com/a/887406/1030702

Use it like so:

$hash | Out-ClipboardText

It uses the .NET clipboard function to set the text. Unfortunately, it's also a little slow and complicated because it needs to start a new PowerShell process in STA mode, as required for Clipboard (source).

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .