VirtualBox command-line - setting up port forwarding

If the machine is powered off, you may use the modifyvm command:

VBoxManage modifyvm "VM name" --natpf1 "guestssh,tcp,,2222,,22"

If it's powered on, controlvm.


on virtual box 6+ , --natpf1 is not supported , @Lyndsy Simon's answer has just one change ('--natpf1' is just changed to simply 'natpf1') , changed command looks like this

VBoxManage controlvm "VM name" natpf1 "guestssh,tcp,,2222,,22"

obviously i am making a change in the running VM so used controlvm if the VM is power off mode , use modifyvm instead!