Reputation: 1121
Given a string, where each path is quoted inside a double quotes, how do I split it into an array with each item is the literal substrings inside the double quotes. For example:
$input=read-host "input"; $input.Split(" ")
With input string of "D:\Path1\file1.txt" "D:\Path2\some [ weird, name.txt""D:\thispath\is_not_separated_by_space_after_quote.txt"
, it would split the string as long as it found space, not quotes-aware (don't think that's a word though). I'm expecting an output like this,
D:\Path1\file1.txt
D:\Path2\some [ weird, name.txt
D:\thispath\is_not_separated_by_space_after_quote.txt
without the double quotes. Any idea how to achieve this? Thanks in advance.
Upvotes: 1
Views: 736
Reputation: 1
None of these answers worked as expected for me with all possible string combinations, a mix of quoted and not is difficult to handle. Finally gave up and used cmd, since it's geared up to do this exactly. I know that it's a copout but really there should be a commandlet to do this. $input will be an array of all the args.
$UninstallString = "`"C:\Program Files (x86)\InstallShield Installation Information\{58C01E5D-F72B-4C0C-8025-E929D6070B6D}\setup.exe`" -runfromtemp -l0x0409 -removeonly"
$input = @(cmd /c "for %i in ($UninstallString) do @echo %~i")
$input.Count
$input
Upvotes: 0
Reputation: 59820
An alternative using -split
and regex:
$string = '"D:\Path1\file1.txt" "D:\Path2\some [ weird, name.txt""D:\thispath\is_not_separated_by_space_after_quote.txt"'
$string -split '(?<=")\s*(?=")' | ForEach-Object Trim('"')
See https://regex101.com/r/lKyxJ0/1 for details.
Upvotes: 0
Reputation: 671
EDITED This is approach for people who do not like using regex, but I believe it should work here.
$input.Replace('""','" "').replace('" "','","').split(',').replace('"','')
This way You make sure there is a space between every two neighboring quotation marks. With this addition Your approach should work?
Upvotes: 1