Search code examples
powershellpathrenamequotestrim

Trim quotes from read-host directory stored as variable


I have a small Powershell script I wrote to help rename folders of files, based off the filenames in another folder.

I have two read-host lines that catch the input from the user and store the input as the source folder and destination folder as strings. This makes life easier as I 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 "X: This seems to be being caused by the quotes around the path, as removing them after dragging and dropping works fine.

Here is how it is captured:

$source = Read-Host "Source folder"
$destination = Read-Host "Destination folder"
[array]$a = Get-ChildItem $source
[array]$b = Get-ChildItem $destination

What is the easiest way to remove the quotes from those strings, before running the Get-ChildItem command? I have tried things like $source.replace, $_. trim and also $source -replace ('"', "")

Can't seem to get this to work.


Solution

  • Use single quotes, like so:

    PS C:\> $foo = 'x:\"some weird\path"'
    PS C:\> $foo
    x:\"some weird\path"
    PS C:\> $foo.Replace('"', '')
    x:\some weird\path
    PS C:\> $foo -replace '"', ''
    x:\some weird\path