1

I want to create a (blank) file, and optionally store a text message in it. This is my code for doing so:

$null = new-item "$filename" -type file
write-output ("Message: <<$message>>")
if ( -not ($message= "")) {
    Add-Content "$filename" "Message: <$message>"
}

The 1st line creates the file. This works. The 2nd line visually verifies that I do in fact supply a string (say, the proverbial "hello world"). The 3rd line evaluates to $true and does execute its nested block. But the 4th line stores a message saying: Message: <>.

I can't figure out the proper syntax for passing the actual value from $message. Help?

1 Answer 1

3

You're using the wrong operator for comparing the $message value. See Get-Help about_comparison_operators.

By saying if ( -not ($message= "")), you actually set the value of $message to be an empty string.

Instead, use -eq, -ne or simply just test it:

# Option 1
if ( -not ($message -eq "")) {
    Add-Content "$filename" "Message: <$message>"
}
#Option 2
if ($message -ne "") {
    Add-Content "$filename" "Message: <$message>"
}
#Option 3
if ($message) {
    Add-Content "$filename" "Message: <$message>"
}
Sign up to request clarification or add additional context in comments.

2 Comments

Excellent, that fixed it. You probably guessed that I'm new to PS, and the syntax sometimes still seems quite round-about.
@KlaymenDK Here's some really different syntax for you: ${c:\temp\afile.txt} = "content to write to file with an assignment statement". This unusual syntax is due to PS' support of providers (help about_providers).

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.