How can I determine the specific character file with powershell? - powershell

I have a file.
c:\\[test^!#$%&'()=~{`}_+-^[];.,] test.xlsx
but powershell test-path error.
PS C:\\> Test-Path -LiteralPath "C:\\[test^!#$%&'()=~{`}_+-^[];.,] test.xlsx" -PathType Leaf
PS C:\\> False
PS C:\\> Test-Path "C:\\[test^!#$%&'()=~{`}_+-^[];.,] test.xlsx" -PathType Leaf
PS C:\\> False
Does anyone have some ideas on how to go about this?
Thanks!

First off, having such file names is begging for trouble. They are much more trouble than help.
That being said, Powershell quoting rules explains how to work with quotes. Since there is a single quote in the file name, it must be escaped by doubling it - the usual backtick doesn't help here. Here-Strings work too. Like so,
# single quote twice
test-path -literalpath '[test^!#$%&''()=~{`}_+-^[];.,] test.xlsx'
True
# here-string
test-path -literalpath #'
>> [test^!#$%&'()=~{`}_+-^[];.,] test.xlsx
>> '#
True
# here-string in varialbe
$f =#'
>> [test^!#$%&'()=~{`}_+-^[];.,] test.xlsx
>> '#
test-path -literalpath $f
True

Related

Powershell script with a path with square brackets in a string for

I can't get my Powershell script to work with a path which has square brackets.
Input path is "c:\temp\yeah [thats it]"
param (
[string]$folderPath = $env:folderPath
)
$folderPath = $folderPath + "\"
Add-Content -Path $folderPath"01-playlist.m3u" -Value "a file name.mp3"
I looked at '-literalpath' and 'Convert-path' but I can't see how to implement that to my code.
Simply use -LiteralPath instead of -Path.
Add-Content -LiteralPath "D:\Test\yeah [thats it]\01-playlist.m3u" -Value "a file name.mp3"
Now the path is taken literally, so you cannot use wildcards as you would with Path.
By the way, your optional parameter looks strange.. Unless you have set an environment variable for it, there is no such thing as $env:folderPath
Also, to combine a path and a filename, there is a cmdlet called Join-Path. Using that is far better than using constructs like $folderPath + "\" where it is very easy to either forget backslashes or adding too many of them..
Instead, I would write
$file = Join-Path -Path $folderPath -ChildPath '01-playlist.m3u'
Add-Content -LiteralPath $file -Value "a file name.mp3"
You need to use backticks I believe. If you are doing this from a shell this works
"abc ````[123````].txt"
Note the number of back ticks changes to two if you are wrapping with single quotes.
See this answer: https://superuser.com/questions/212808/powershell-bug-in-copy-move-rename-when-filename-contains-square-bracket-charac#:~:text=Getting%20PowerShell%20to%20correctly%20recognize,four%20backticks%20to%20escape%20it.

File path with quotation mark issue of Powershell

I was trying to write a script to test the availability of the file path. One of the process is that user have to input the file path or just drag the file into the Powershell command prompt.
In this process,
User will input the file path like C:\Program Files\7-Zip\7z.exe and the string will become the value of $filePath variable which will be used as the parameter of the Test-Path command.
But sometime, user will just drag the file into the Powershell command prompt so that the string will have a pair of quotation mark included just like the picture 1.
("C:\Program Files\7-Zip\7z.exe")
Picture 1
Then you will see when I try to test the path using Test-Path command with that $filePath variable while the value(string) of the $filePath included a pair of quotation mark, the result will always be False even though the path is existing and valid.
But when I use the same Test-Path command without using variable (I mean just copy and paste the file path into the command), it works normally.
IT'S WEIRD!
I have tried typing the file path by keyboard into the variable instead of dragging the file into Powershell command prompt. (Without Quotation mark)
Then use the same method to test the filepath (using variable for the file path). It works fine.
Picture 2
I don't get it. Aren't they the same thing?
when
$filePath = "C:\Program Files\7-Zip\7z.exe"
Below 2 commands SHOULD have the same result! WHY they are not?
Test-Path -Path $filePath
Test-Path -Path "C:\Program Files\7-Zip\7z.exe"
In case of drag and drop, it looks like if the path has no spaces it will return true . If it has a space then PowerShell places quotes around it. In that case, PowerShell is literally seeing the path as "C:\Program Files\7-Zip\7z.exe"
What you can do is use the -replace operator like this -
Test-Path -path ($filepath -replace '"', "") -PathType Leaf
OR
As suggested by #Josefz in the comments, you could also use Trim() method like -
Test-Path -path ($filepath.Trim('"')) -PathType Leaf
Not exactly an explanation to your problem, but you could use this as a workaround.
If the user types a filename that contains embedded " characters, then Test-Path will return $false. Why? File names cannot contain the " character; the " character is used by parsers to indicate that an argument in a string contains whitespace. So this will of course return $false:
$filePath = '"C:\Program Files\7-Zip\7z.exe"'
Test-Path $filePath
The embedded " characters are not part of the file name; you need to omit them for the result to be $true.
What version of powershell are you using? I get true for both commands
PS C:\Users> $filePath = "C:\Program Files\7-Zip\7z.exe"
PS C:\Users> Test-Path -Path $filePath
True
PS C:\Users> Test-Path -Path "C:\Program Files\7-Zip\7z.exe"
True
PS C:\Users> $PSVersionTable.PSVersion
Major Minor Build Revision
----- ----- ----- --------
5 1 17134 48
EDIT ----------
Got it, the problem is that Read-Host will save the string literally, with the quotes. The simple solution is to remove the quotes
PS C:\Users> $filePath = Read-Host -Prompt "enter input"
enter input: "C:\Program Files\7-Zip\7z.exe"
PS C:\Users> $filePath
"C:\Program Files\7-Zip\7z.exe"
PS C:\Users> Test-Path -Path $filePath
False
PS C:\Users> Test-Path -Path $filePath.replace("`"","")
True

Set Location in PowerShell that contains a ampersand (&)

How do i set my directory using PowerShell to the below location ?
W:\B&M\Store Segmentation\Pete\Python
I tried using:
PS > Set-Location -Path W:\B"&"M\Store Segmentation\Pete\Python
While using " or ' is totally a better idea, but should be informed of PowerShell escape character:
`
Using this caracher, you can scape special characters, for example:
Set-Location C:\A`&B
You need it for example in cases that the folder name contains []:
Set-Location 'C:\A&B[1]' # Will Fail
Set-Location 'C:\A&B`[1`]' # Correct
Use " double quotes or ' apostrophes as follows:
Set-Location -Path "W:\B&M\Store Segmentation\Pete\Python"
or
Set-Location -Path 'W:\B&M\Store Segmentation\Pete\Python'
Read About Quoting Rules for explanation.

How to use Test-Path on a directory containing square brackets in the name

I have a series of directories that have been created with square brackets in their name. For some inexplicable reason, the Test-Path command returns $false when I run it against these directories, but returns $true if I run the same command against a directory without square brackets in the name.
The directories look like this:
[s]4343224D
[s]50AF43AF
The command I am running is:
Test-Path [s]50AF43AF
I have also tried:
Test-Path `[s`]50AF43AF
But this also returns $false.
Does anyone know how one might get Test-Path to return true when there really is a directory of that name?
You can use the -LiteralPath parameter for this:
Test-Path -LiteralPath '[s]50AF43AF'
Which is probably a better option than adding backticks if you're processing more than one path:
'[s]4343224D','[s]50AF43AF' | ForEach-Object { Test-Path -LiteralPath $_ }
This seems to work:
Test-Path '`[s`]50AF43AF'

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.
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