Home > Software engineering >  Random newline in powershell script
Random newline in powershell script

Time:11-07

Here is a script I have that is finding the name and password of a wifi network when shows it on the screen:

$CmdL = @("Command1", "Command2", "WIFI NAME")
Trap  [System.Management.Automation.RuntimeException] {
    Write-Color "No such WiFi exists" -Color "Red"
    Continue
}
$S = $Null
$E = Get-AllWifiPasswords
Write-Host
$S = ($E | sls ($CmdL[2])).ToString().Trim()
Write-Color $S -Color "Green"
Write-Host

However, if it can't find the name of the network then it adds a trailing newline to the end:

(newline)
No such WiFi exists
(newline)
(newline)

I have no idea why that newline is there, as it should not be. How can I remove it so that the error output is as follows:

(newline)
No such WiFi exists
(newline)

CodePudding user response:

The extra newline comes from the fact that Write-Color $S -Color "Green" also executes when an error occurred, in which case $S has no value, resulting in an empty line.

While trap is still supported, the try / catch / finally statement that was introduced later offers more flexibility and clarity of control flow:

$CmdL = "Command1", "Command2", "WIFI NAME"
$S = $Null
$E = Get-AllWifiPasswords
Write-Host
try {
  # If the next statement causes a terminating error, 
  # which happens if the `sls` (`Select-String`) call has no output,
  # control is transferred to the `catch` block.
  $S = ($E | sls ($CmdL[2])).ToString().Trim()
  Write-Color $S -Color "Green"
}
catch {
  Write-Color "No such WiFi exists" -Color "Red"
}
Write-Host
  • Related