How do I exit from a try-catch block in PowerShell? - powershell

I want to exit from inside a try block:
function myfunc
{
try {
# Some things
if(condition) { 'I want to go to the end of the function' }
# Some other things
}
catch {
'Whoop!'
}
# Other statements here
return $whatever
}
I tested with a break, but this doesn't work. It breaks the upper loop if any calling code is inside a loop.

An extra scriptblock around try/catch and the return in it may do this:
function myfunc($condition)
{
# Extra script block, use `return` to exit from it
.{
try {
'some things'
if($condition) { return }
'some other things'
}
catch {
'Whoop!'
}
}
'End of try/catch'
}
# It gets 'some other things' done
myfunc
# It skips 'some other things'
myfunc $true

The canonical way to do what you want is to negate the condition and put the "other things" into the "then" block.
function myfunc {
try {
# some things
if (-not condition) {
# some other things
}
} catch {
'Whoop!'
}
# other statements here
return $whatever
}

You can do like this:
function myfunc
{
try {
# Some things
if(condition)
{
goto(catch)
}
# Some other things
}
catch {
'Whoop!'
}
# Other statements here
return $whatever
}

Related

(SwiftLint) How to write the rule (maybe custom) where it is always "\n"(new line) after the "{" if there is a body?

I am using SwiftLint and I need to have a new line after the "{" if there is a body, for example, this is correct
func foo() {
if true { }
}
but this doesn't seem right
func foo() {
if true { print("This print should be on the new line") }
}
like this
func foo() {
if true {
print("This print should be on the new line")
}
}
How to do this?
UPD
Thanks, #Bram, there is such a regex
custom_rules:
newline_block:
name: "Newline Block"
regex: 'if \(?\w+\)? \{[ ]*(.+)+[ ]*\}'
message: "Statement must be on its own line"
The problem is this regex catch all the conditions with one word after the if, like this
if myCondition { }
and it doesn't matter if braces are on the next line or not, however, this regex doesn't catch conditions like this
if 0 < 1 { print() }
It appears SwiftLint is a bit flaky with the any single character (.), so the closest I got was this
custom_rules:
newline_block:
name: "Newline Block"
regex: "\\{[ ]*(\\S|( +))+[ ]*\\}"
message: "Statement must be on its own line"
The better regex would be {[ ]*(.+)+[ ]*} (unescaped), but for some reason that doens't work when I run it at Xcode.
This will work for your request with the prints, but the solution does have some drawbacks:
func foo() {
// No warning
if true {}
// Newline Block Violation: Statement must be on its own line (newline_block)
if true { }
}
And, but I'm not sure if that applies to you as well:
var connection: OpaquePointer? {
// Newline Block Violation: Statement must be on its own line
get { queue.sync { underlyingConnection } }
// Newline Block Violation: Statement must be on its own line
set { queue.sync { underlyingConnection = newValue } }
}

PowerShell - how to determine programmatically whether StrictMode is set?

I know that I can override in a script or function the StrictMode setting inherited from a higher scope. But how can I find out in a script or function what the inherited setting is?
Perhaps a small function can help:
function Get-StrictMode {
# returns the currently set StrictMode version 1, 2, 3
# or 0 if StrictMode is off.
try { $xyz = #(1); $null = ($null -eq $xyz[2])}
catch { return 3 }
try { "Not-a-Date".Year }
catch { return 2 }
try { $null = ($undefined -gt 1) }
catch { return 1 }
return 0
}
Get-StrictMode

Cant reach return statement in a boolean

I am trying to reach the second return statement. For whatever reason, the code stops after reaching the first if statement. What am I doing wrong?
function orderFood(food) {
if (true){
return 'chinese';
}
else if (false){
return 'italian';
}
}
orderFood(false);
You will never reach to the second statement. The if else statement is expecting a variable whose value to be matched. If you hard coded the true then the else if never be working. I suggest you to understand the basic of if-else.
function orderFood(food) {
//here food is a boolean variable and if else will look for this
if (food){
return 'chinese';
} else{
return 'italian';
}
}

How to run script and catch its return value

I have this simple function that return some value based on the passed argument:
function GetParam($fileName)
{
if($fileName.ToLower().Contains("yes"))
{
return 1
}
elseif($fileName.ToLower().Contains("no"))
{
return 2
}
else
{
return -1
}
}
I want to call this script from another script and get its return value, in order to decide what to do next.
How can I do that ?
You have to dot source the script where the GetParam function is defined to expose it to the other script:
getparam.ps1
function GetParam($fileName)
{
if($fileName.ToLower().Contains("yes"))
{
return 1
}
elseif($fileName.ToLower().Contains("no"))
{
return 2
}
else
{
return -1
}
}
other.ps1
. .\getparam.ps1 # load the function into the current scope.
$returnValue = GetParam -fileName "yourFilename"
Note: Consider using approved Verbs and change your function name to Get-Param. Also you can omit the return keyword.

How can I check if a User Account group exists through powershell?

Something like this :
if(GroupExists("Admins")) // <-- How can I do this line ?
{
([ADSI]"WinNT://$_/Admins,group").add($User)
}
else
{
$Group = Read-Host 'Enter the User Group :'
([ADSI]"WinNT://$_/$Group,group").add($User)
}
You can use the Exists static method as follows:
[ADSI]::Exists("WinNT://localhost/Administrators")
To get a True/False result you can wrap into try/catch statement.
$result = try { [ADSI]::Exists("WinNT://localhost/Administrators") } catch { $False }
or in a if/then statement you'll need to wrap it inside a $()
if ( $(try {[ADSI]::Exists("WinNT://localhost/Administrators")} catch {$False}) ) {
write-host "good"
}
else {
write-host "bad"
}