PowerShell functions returning true / false

I'm new to using PowerShell, and I was wondering if anyone had any input when trying to return PowerShell functions to values.

I want to create some function that will return a value:

Function Something { # Do a PowerShell cmd here: if the command succeeded, return true # If not, then return false } 

Then execute the second function, which will only work if the above function is correct:

  Function OnlyTrue { # Do a PowerShell cmd here... } 
+7
source share
3 answers

You can use return statements in PowerShell:

 Function Do-Something { $return = Test-Path c:\dev\test.txt return $return } Function OnlyTrue { if (Do-Something) { "Success" } else { "Fail" } } OnlyTrue 

Conclusion: Success if the file exists, and Fail if it does not.

One warning: PowerShell functions return everything that has not been written. For example, if I change the Do-Something code to:

 Function Do-Something { "Hello" $return = Test-Path c:\dev\test.txt return $return } 

Then the return will always be successful, because even when the file does not exist, the Do-Something function returns an array of objects ("Hello", False). Take a look at booleans and operators for more information on booleans in PowerShell.

+7
source

You would do something like this. The Test command uses the automatic variable '$?'. It returns true / false if the last command completed successfully (for more details see about_Automatic_Variables Topic):

 Function Test-Something { Do-Something $? } Function OnlyTrue { if(Test-Something) { ... } } 
+5
source

A very late response, but the same issue occurred in PowerShell 5. You can use 1 and 0 as return values. then you can convert it to a boolean or just use "-eq 1" or 0

 Function Test { if (Test-Path c:\test.txt){ return 0 }else{ return 1 } } [bool](Test) 
0
source

Source: https://habr.com/ru/post/1496165/


All Articles