Skip to content

Observations

Béla Király edited this page May 28, 2019 · 2 revisions

What's this?

I'll use this page as a knowledgebase to collect the things I learn about Powershell during writing the program.

Function return value problem

It gave me a few hours headache to figure this problem out. Powershell has a bit of an unpredictable behavior with returning values from a function. The logical behavior would be to return the value, variable, whatever we explicitly say it to return at the end of the function, but it doesn't always do that. If there is something uncatched in the pipeline (and in this moment it's not clear to me what makes something uncatched according to Powershell), it will return that too. So if we want to return only a string from the function, it returns the contents of the pipeline, and puts the chosen string at the end of it. This way at the other end, the returned value is not a string, but an array, with the string we need as the last element of it.

Workaround

Either use class instead of function, which always returns ONLY the value we state it to return, or just select the last element of the returned array, which is exactly the value we needed.

Invoke-Expression of string with a variable in it

Another thing that gave me a headache for a few hours. Invoke-expression works perfectly on strings that consist commands as long as there are no variables in it that point to another variables the command needs as object, not as string. So if there is a variable in the string we want to invoke with Invoke-Expression, there is no problem. But if that variable points to a variable the command expects as an object it will give exception.

Workaround

Put escape character right before the variable we need as an object.

Try-Catch doesn't catch exceptions

One more thing that works not as expected in Powershell. Try-Catch block doesn't neccesserally catches an exception if it doesn't lead to making the program halt.

Workaround

In these cases, put $ErrorActionPreference = "Stop" in the try block before the command we expect to throw exception. This way it will get to the catch block instead of giving the built-in exception of Powershell.

Getting the name of an Enum from its value

It's not really a problem, just a little thing that can come in handy, and it took me a while to find how to do it.

Solution

[enumname]$value

Clone this wiki locally