Home > front end >  How to run PowerShell.exe command from bash as root in WSL2
How to run PowerShell.exe command from bash as root in WSL2

Time:05-27

I'm using WSL2 with Ubuntu 20.04 on Windows 10. I have a disk that is not automatically connected to the WSL2 on its startup. The letter under which the disk is registered on Windows can change, I only know the name of the volume. I've written a bash script to find the disk letter and then mount it on the WSL2

#!/bin/bash

BACKUP_FOLDER=/mnt/autobackup
mkdir -p $BACKUP_FOLDER
VOLUME_LETTER="$(powershell.exe -Command '(Get-Volume -FriendlyName AUTOBACKUP | Select-Object -Index 0).DriveLetter' | awk -v RS='\r\n' '{ print $0 }')"
VOLUME_LETTER=$(echo "${VOLUME_LETTER}:\\")
sudo mount -t drvfs $(echo $VOLUME_LETTER) $(echo $BACKUP_FOLDER)

The script works fine when I run it as a normal user, asking me for my password. However, it raises an error when trying to run it as root (which is what I want because I want to put the script into /etc/init.d to run at startup)

./wsl_startup.sh: line 5: powershell.exe: command not found
mount: /mnt/autobackup: special device :\ does not exist.
<3>init: (1058) ERROR: UtilCreateProcessAndWait:501: /bin/mount failed with status 0x2000
<3>init: (1058) ERROR: MountPlan9:493: mount cache=mmap,rw,trans=fd,rfdno=3,wfdno=3,msize=65536,aname=drvfs;path=:\;symlinkroot=/mnt/ failed 2
No such file or directory

How to make root see the powershell.exe command? Or should I do it another way?

CodePudding user response:

When running as root, $PATH contains only a minimal set of entries that doesn't include Windows file-system directories such as the one where powershell.exe is located.

Thus, you'll have to invoke powershell.exe by its full path:

VOLUME_LETTER="$(/mnt/c/WINDOWS/System32/WindowsPowerShell/v1.0/powershell.exe -Command '(Get-Volume -FriendlyName AUTOBACKUP | Select-Object -Index 0).DriveLetter' | awk -v RS='\r\n' '{ print $0 }')"
  • Related