3

Sometimes I need to check if a pathname ends with "\" adding it if necessary, the code is pretty simple, something like this

if ($destFolder[-1] -ne '\') {
    $destFolder += '\';
}

Is there a way to evaluate an if statement inside () so that I can use it in variable assignement? I mean something like this

$finalName = $destFolder + (if ($destFolder[-1] -ne '\') { '\' } ) + $fileName

Given that if is not a cmdlet I get this error

if : The term 'if' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again.

2 Answers 2

6

You need a subexpression here ($()):

$finalName = $destFolder + $(if ($destFolder[-1] -ne '\') { '\' }) + $fileName

The expression operator (() without the $) only allows simple statements/expressions.

Sign up to request clarification or add additional context in comments.

Comments

2

For the sake if readability, you could assign the entire result of your if statement to a variable:

$finalName = if ($destfolder[-1] -ne '\') {
    $destfolder + '\' 
} else {
    $destfolder
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.