Use PowerShell to determine size of a string in bytes

Question:

I’m using PowerShell to write messages to a message queue, which has a message size limit on it. Before writing a message to the queue, I need to know how many bytes a string is.

How can I figure out how many bytes the string is, so I can perform a size comparison, before writing to the queue?

Answer:

The answer to this depends on the text encoding you’re using.

You can use the static method GetByteCount() on a few different text encodings. Assuming you’re using UTF-8 text encoding, you can reference the UTF8 static property on the System.Text.Encoding class, to obtain a reference to the UTF8Encoding class.

Here’s an example, where we retrieve a System.Diagnostics.Process object, convert it to a JSON representation, and then determine how many bytes it uses, given a UTF8 encoding.

Here’s the same example, but changing the text encoding to ASCII.

If your input string doesn’t contain any Unicode characters, you should get the same result for both ASCII and UTF-8 byte counts.

NOTE: The System.Text.Encoding base class declares a virtual method named GetByteCount(), however it’s up to the child classes (eg. UTF8Encoding) to actually implement this method.

https://msdn.microsoft.com/en-us/library/w3739zdy(v=vs.110).aspx

Source:

Use PowerShell to determine size of a string in bytes by licensed under CC BY-SA | With most appropriate answer!

Leave a Reply