简体   繁体   中英

Powershell set-content adding hidden characters

Following scenario:

Set-Content $healthStatusFileName "a 'r'n a"  
$previousHealthStatus=$(Get-Content $healthStatusFileName )  
$errorMessage = "a 'r'n a" 


If ($previousHealthStatus -eq $errorMessage)

Now for some reason the if statement always returns false, why? It only happens when having the carriage return line feed in the string. Also, doing this before the If does not help:

$previousHealthStatus = $previousHealthStatus -replace "'t|'n|'r",""
$errorMessage = $errorMessage -replace "'t|'n|'r",""

Get-Content returns an array, so you are comparing a string with an array. Join the array with

`r`n

so you get the equivalent of your initial string.

Set-Content $healthStatusFileName "a `r`n a"  
$previousHealthStatus=$(Get-Content $healthStatusFileName ) -join "`r`n"
$errorMessage = "a `r`n a" 
($previousHealthStatus -eq $errorMessage)

result is:

True

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