Running complex PowerShell commands with spaces in WSL requires careful escaping or encoding to prevent the Linux shell from misinterpreting arguments. This guide demonstrates how to reliably execute multi-argument commands, such as using
find with specific filters, by leveraging proper quoting strategies and base64 encoding for robustness.
Understanding the Shell Boundary
When you invoke PowerShell from within WSL (Ubuntu, Debian, etc.), you are crossing a shell boundary. The WSL command line is typically Bash, while the target process is PowerShell.exe. Spaces in arguments are significant delimiters in both shells, but they are handled differently. If you simply pass a string with spaces to
powershell.exe, Bash may split the argument before PowerShell ever sees it, leading to syntax errors or unexpected behavior.
The most common mistake is assuming that wrapping the entire command in double quotes will suffice. While this works for simple cases, complex pipelines involving pipes (
|), redirections (
>), or nested quotes often break because Bash interprets these characters before passing them to PowerShell. To solve this, you must either escape every special character for Bash or use a method that bypasses Bash's parsing entirely.
Method 1: Proper Quoting and Escaping
For straightforward commands, you can use single quotes around the PowerShell script block when calling it via
-Command. Single quotes in Bash are literal; they prevent any interpretation of the contents by the outer shell.
wsl powershell.exe -Command 'Get-ChildItem -Path "C:\Users" -Recurse | Where-Object { $_.Length -gt 1MB }'
In this example, the entire PowerShell command is enclosed in single quotes. Inside those single quotes, you can freely use double quotes for file paths or string literals without worrying about Bash interfering. However, if your PowerShell command itself contains single quotes, you must escape them. In Bash, you cannot escape a single quote inside single quotes directly. Instead, you end the single-quoted string, add an escaped single quote, and start a new single-quoted string:
wsl powershell.exe -Command 'Write-Host "It'\''s working"'
This technique, known as "single-quote escaping," involves closing the current single quote, inserting a backslash followed by a single quote, and reopening the single quote. It is verbose but reliable for short scripts.
Method 2: Using -EncodedCommand for Complex Scripts
For commands with multiple pipes, complex logic, or numerous special characters, manual escaping becomes error-prone. The recommended approach is to use the
-EncodedCommand parameter, which accepts a Base64-encoded string of Unicode characters representing the PowerShell command. This completely bypasses Bash's argument parsing issues because the encoded string contains no special characters that Bash would interpret.
First, generate the Base64 string in PowerShell. You can do this interactively on your Windows machine or within WSL if you have PowerShell installed there. Here is how to encode a complex command:
# Encode the command
$command = 'Get-ChildItem -Path "C:\Temp" -Filter "*.log" | Select-Object Name, Length'
$bytes = [System.Text.Encoding]::Unicode.GetBytes($command)
$encoded = [Convert]::ToBase64String($bytes)
echo $encoded
Then, run the command in WSL using the encoded string:
wsl powershell.exe -EncodedCommand
Note that PowerShell uses UTF-16LE encoding for its commands. If you generate the Base64 string in a different environment, ensure you use the correct encoding. This method is the most robust solution for production scripts or complex one-liners where readability is secondary to reliability.
Practical Example: Finding Files with Multiple Criteria
Let us apply these concepts to a realistic scenario: searching for log files modified in the last 7 days using the
find equivalent in PowerShell. We want to avoid piping issues and handle spaces in directory names.
wsl powershell.exe -Command 'Get-ChildItem -Path "C:\Logs\Application Data" -Recurse -Filter "*.log" | Where-Object { $_.LastWriteTime -gt (Get-Date).AddDays(-7) }'
Here, we use single quotes to wrap the entire PowerShell expression. Inside, we use double quotes for the path containing spaces. The
Where-Object filter uses curly braces, which are safe inside single quotes. This command searches recursively, filters by extension, and then applies a date condition.
If you encounter errors related to permissions or access denied, remember that WSL runs as a non-administrator by default on many configurations. You may need to perform admin operations depending on your setup. For more details on permission issues, see
Performing Admin Operations on a WSL Distro Installed on a Non-Admin Windows Account.
Why Not Use Stdin?
Some tutorials suggest piping the command into PowerShell via stdin:
echo "Get-Process" | wsl powershell.exe -Command -
While this works for very simple commands, it is unreliable for complex scripts. The
-Command parameter expects a script block, and relying on stdin can lead to buffering issues or incorrect parsing of multiline input. It is better to stick with
-Command with proper quoting or
-EncodedCommand for guaranteed consistency.
Troubleshooting Common Errors
If your command fails with a "syntax error" or "unexpected token" message, check your quoting first. Ensure that all single quotes are properly closed and that any internal single quotes are escaped correctly. If you suspect encoding issues, verify that the Base64 string was generated using UTF-16LE.
Another common issue is path translation. When accessing Windows drives from WSL, use the
/mnt/c/ prefix instead of
C:\. However, when passing commands to PowerShell, it is often easier to let PowerShell handle the Windows-style paths internally, as shown in the examples above.
For issues related to removing directories or files after your search, be aware that standard
rm commands in WSL may fail if directories are not empty. See
Error: rm cannot remove 'dir-name' - Directory not empty for solutions to cleanup tasks.
Frequently Asked Questions
How do I include a single quote in a PowerShell command passed from Bash?
You must close the single-quoted string, add an escaped single quote, and reopen the string. For example, use
'Text'\''More Text' to produce
Text'More Text in PowerShell. This prevents Bash from terminating the argument prematurely.
Why does my Base64 encoded command fail in WSL?
PowerShell requires UTF-16LE encoding for
-EncodedCommand. If you generate the Base64 string using a tool that defaults to UTF-8 or ASCII, the command will fail. Always ensure your encoding matches PowerShell's expectation when creating the encoded string.
Can I use double quotes for the entire PowerShell command in Bash?
Yes, but you must escape all special Bash characters like
$, `
`
, \
, "
, and !` inside the double quotes. This is tedious and error-prone. Single quotes are preferred because they treat all content literally, except for other single quotes.
What is the difference between -Command and -File in WSL?
-Command executes a string of PowerShell code directly, making it suitable for one-liners and inline scripts.
-File executes a
.ps1 script file located on the filesystem. Use
-File for longer, more complex scripts stored in files rather than typed inline.
Does WSL support PowerShell Core or only Windows PowerShell?
WSL primarily supports running Windows PowerShell (
powershell.exe) via the compatibility layer. However, you can also install PowerShell Core (
pwsh) in the Linux distribution itself for native Linux execution. The techniques discussed here apply mainly to invoking Windows PowerShell from the Bash shell.