PowerShell低版本不支持NoNewLine参数,求替代方案
-NoNewLine Parameter Alternative for Older Versions Got it, let's fix that compatibility issue with older PowerShell versions that don't support -NoNewLine! Since that parameter was introduced in PowerShell 5.0, we need to rely on .NET framework methods that work across all supported PowerShell versions (even 2.0 and up). Here are the most reliable solutions:
1. Use [System.IO.File] Static Methods
This is the simplest approach for writing/overwriting or appending text without extra newlines. The .WriteAllText() and .AppendAllText() methods write exactly the string you pass—no automatic line breaks added.
Example for Overwriting a File:
# Your output string (from your hashtable comparison logic) $output = "All servers are all on Version 19.1.5" # Write directly to the file, no extra newline [System.IO.File]::WriteAllText("output.txt", $output)
Example for Appending to a File:
# Append your text without adding a newline [System.IO.File]::AppendAllText("output.txt", $output)
2. Use StreamWriter for Fine-Grained Control
If you need more control over file writing (like handling specific encodings or multiple sequential writes), StreamWriter is a great option. Its .Write() method avoids adding newlines, unlike .WriteLine().
# Initialize StreamWriter: second parameter $true = append, $false = overwrite $writer = [System.IO.StreamWriter]::new("output.txt", $true, [System.Text.Encoding]::UTF8) # Write your content without a newline $writer.Write("All servers are all on Version 19.1.5") # Clean up the writer (critical to avoid file locks) $writer.Close() $writer.Dispose()
3. Full Example with Your Hashtable Logic
Here's how to integrate this with your existing script that uses a hashtable to check server versions:
# Hashtable storing server versions $serverVersions = @{ "Server01" = "19.1.5" "Server02" = "19.1.5" "Server03" = "19.1.5" } # Check if all versions match $allVersionsMatch = ($serverVersions.Values | Select-Object -Unique).Count -eq 1 # Prepare output text $outputText = if ($allVersionsMatch) { "All servers are all on Version $($serverVersions.Values[0])" } else { "Some servers have mismatched versions" } # Write to file using .NET method (compatible with old PowerShell) [System.IO.File]::WriteAllText("server_version_report.txt", $outputText)
All these methods bypass the PowerShell-specific -NoNewLine parameter and use native .NET functionality, so they'll work on any PowerShell version that supports the .NET framework (which is all of them).
内容的提问来源于stack exchange,提问作者Jeremiah Williams

