1

When developping applications I run a server on WSL2 and I need to connect to it from browser on windows host. To do this, I need to bind some ports and create firewall rules every time WSL is started. It is done with a powershell script that is located on windows machine. For now I have a task in task scheduler that runs this script when I login to windows. It works fine, but it doesn't fire when I restart WSL manually which I sometimes do. To run a script on startup in WSL I could invoke it in .profile or .bashrc, but I want to run it on Windows, not in WSL. Is there a way to do this?

1 Answer 1

3

You're on the right track. Just run the PowerShell script in your .profile using the Windows (not Linux) PowerShell interpreter:

/mnt/c/Windows/System32/WindowsPowerShell/v1.0/powershell.exe "C:\myscript.ps1"

It probably doesn't need to be fully qualified, but it's probably safer to do so.

You can also convert paths from WSL to Windows if needed, e.g. powershell.exe $(wslpath -w script/myscript.ps1) if you want to store the script on the WSL ext4 filesystem (e.g. perhaps you want it relative to your home directory).

Of course, substitute pwsh.exe if are using PowerShell core. And fully qualify it if it is either (a) not in your path or (b) you have the Linux PowerShell core version installed as well.

Since you are using the PowerShell interpreter running on Windows, all of the commands (port forwarding, firewall rules) will be run against the Windows host.

1
  • Awesome, thank you a lot! Jan 4, 2021 at 10:59

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .