简体   繁体   中英

Store string variable in text file

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?

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>"
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM