I'm trying to enhance my PowerShell script for establishing VNC connections. I've provided the script below, but I'm not sure if it's up to par. One of my goals is to use 'vncviewer -via host' with VNC_VIA_CMD, but I can't quite figure that out. Here's my current script:
```powershell
$config_path = ".config.json"
if (-not (Test-Path $config_path)) {
Write-Error "Config not found: $config_path"
exit
}
$config = Get-Content -Path $config_path | ConvertFrom-Json
if (-not (Test-Path $config.ssh_path)) {
Write-Error "SSH not found: $($config.ssh_path)"
exit
} elseif (-not (Test-Path $config.vnc_path)) {
Write-Error "VNC not found: $($config.vnc_path)"
exit
}
Start-Process -FilePath "$($config.ssh_path)" -ArgumentList "-L $($config.local_port):localhost:$($config.remote_port) -l $($config.user) $($config.host) -i $($config.key) -p $($config.ssh_port) -N" -NoNewWindow
Start-Sleep -Seconds 10
Start-Process -FilePath "$($config.vnc_path)" -ArgumentList "localhost::$($config.local_port)"
```
2 Answers
Here are a few optimization tips:
1. `Get-Content` has good error messages already, so you might not need to check for path existence explicitly.
2. Instead of using `exit`, try `-ErrorAction stop` with `Write-Error` to handle errors.
3. Use separate `if` statements instead of `elseif` for checking SSH and VNC paths, as they are independent.
4. Splatting your `Start-Process` parameters can make your code cleaner and more readable!
Great advice! It can simplify your script significantly.
I noticed that your script defines `$config` later in your script, which can cause issues if you're trying to access it earlier. Make sure the variable is declared at the start. Also, consider adding some error handling like try/catch blocks in case file reading fails. It can save a lot of headaches!
Thanks for spotting that! I'll move the declaration up.
Exactly, and using try/catch will help you debug if any files aren't opening as expected!

That's really helpful. I'll definitely implement splatting!