Reputation: 724
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?
Upvotes: 1
Views: 150
Reputation: 22831
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>"
}
Upvotes: 3