Table of Contents
Trim Quotes From Read-Host Path Stored as a Variable
We have a simple Powershell script to get items in a folder. We use the Read-Host cmdlet that catch the folder path input from the user and store path as as strings in a variable. This makes life easier as we can drag and drop rather than full typing the path.
The problem is that PowerShell keeps throwing errors, saying it can’t find the drive. This seems to be being caused by the quotes around the path. If we remove them after dragging and dropping works fine.
$path = Read-Host "Enter the path"
Write-Host "The path you've entered: $path" -ForegroundColor Green
Get-ChildItem -Path $path | Select-Object Name
As you can see, PowerShell though all string from Read-Host to the variable. So, the Get-ChildItem will return error becase the path is not valid.
Removing the double quotes
To fix it, after store the strings from Read-Host to the variable. We need to remove the double quotes from the variable before using it in the Get-ChildItem.
$path = Read-Host "Enter the path"
$path = ($path).trim('"')
Write-Host "The path you've entered: $path" -ForegroundColor Green
Get-ChildItem -Path $path | Select-Object Name
As you can see, the script works as expected.
Removing the single quote
In some cases, user rounds the path with a single quote instead of double quotes. The error comes again.
To make it work, we need an addition step to remove the single quote from the variable as follows:
$path = Read-Host "Enter the path"
$path = ($path).trim('"')
$path = ($path).trim("'")
Write-Host "The path you've entered: $path" -ForegroundColor Green
Get-ChildItem -Path $path | Select-Object Name
Now, regardless user input the path with a single quote or double quotes. The script will work normally.
Not a reader? Watch this related video tutorial: