Set Location in PowerShell that contains a ampersand (&) - powershell

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.

Related

Get the current working directory or any directory with "/" instead of "\" in powershell script

In order to deliver the current working directory adress to a program. I need to provide the directory Path separated by forward slashes /. The program does not accept a string containing backslashes.
Currently, the pwd-Command delivers the following:
C:\testdir1\testdir2
I want the following string:
C:/testdir1/testdir2
Is there an easy way to transform this directory adress in a powershell script?
Thank you in advance.
Use the -replace operator[1] to perform (invariably global) string replacements (since it is regex-based, a verbatim \ must be escaped as \\); the automatic $PWD variable contains the PowerShell session's current location (which, if the underlying provider is the FileSystem provider, is a directory):
$PWD -replace '\\', '/'
If you want to ensure that the resulting path is a file-system-native path (one not based on PowerShell-only drives):
$PWD.ProviderPath -replace '\\', '/'
If there's a chance that the current location is from a provider other than the file-system (e.g., a registry-based drive such as HKLM:).
(Get-Location -PSProvider FileSystem).ProviderPath -replace '\\', '/'
[1] In this simple case, calling the [string] type's .Replace() method is an alternative, but the -replace operator is more PowerShell-idiomatic and offers superior functionality. This answer contrasts the two.
Fast code but seems to works as expected
# Original path
$Path = "C:\testdir1\testdir2"
Write-Host "Original Path is:" $Path
#Replace \ by /
$Changed = $Path -replace '\\', '/'
Write-Host "changed path:" $Changed
Output
Original Path is: C:\testdir1\testdir2
changed path: C:/testdir1/testdir2

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

Change directory in PowerShell

My PowerShell prompt's currently pointed to my C drive (PS C:\>). How do I change directory to a folder on my Q (PS Q:\>) drive?
The folder name on my Q drive is "My Test Folder".
Unlike the CMD.EXE CHDIR or CD command, the PowerShell Set-Location cmdlet will change drive and directory, both. Get-Help Set-Location -Full will get you more detailed information on Set-Location, but the basic usage would be
PS C:\> Set-Location -Path Q:\MyDir
PS Q:\MyDir>
By default in PowerShell, CD and CHDIR are alias for Set-Location.
(Asad reminded me in the comments that if the path contains spaces, it must be enclosed in quotes.)
To go directly to that folder, you can use the Set-Location cmdlet or cd alias:
Set-Location "Q:\My Test Folder"
Multiple posted answer here, but probably this can help who is newly using PowerShell
SO if any space is there in your directory path do not forgot to add double inverted commas "".
You can simply type Q: and that should solve your problem.
Set-Location -Path 'Q:\MyDir'
In PowerShell cd = Set-Location
You can also use the sl command to be able to change directories. It is Set-Location but it is much shorter.
Example:
# Too verbose
Set-Location -Path C:\
# Just the right amount of characters to type
sl C:\
If your Folder inside a Drive contains spaces In Power Shell you can Simply Type the command then drive name and folder name within Single Quotes(''):
Set-Location -Path 'E:\FOLDER NAME'
The Screenshot is attached here
On Powershell use Set-Location instead of cd.
Put path in quotes. Single quotes works for me.
Set-Location 'C:\Program Files\MongoDB\Server\6.0'

copy-item where file name is the computer hostname

Having what seems to be a basic problem in Powershell. I am doing a simple copy-item script from a UNC share to the local C:\ drive. Here is my code:
$hostname = $env:computername
Copy-Item -Path '\\server\share\$hostname.txt' -Destination 'C:\'
I can't figure out the syntax to have it retrieve the text file that matches the name of the hostname using the variable. If I put in a statically named .txt file that code works.
What do I have to put around that variable for it to work?
You need to replace your single quotes with double quotes like this:
$hostname = $env:computername
Copy-Item -Path "\\server\share\$hostname.txt" -Destination 'C:\'
Single quoted strings will not expand variables. You need a double quoted string e.g.:
Copy-Item "\\server\share\$hostname.txt" C:\
And in general, you don't need to quote string arguments to a PowerShell command unless you need variable expansion or there's a space in the string.
You could also directly embed the environment variable in double quoted string:
Copy-Item "\\server\share\$env:computername.txt" C:\