copy-item where file name is the computer hostname - powershell

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:\

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 can I use spaces in a fully qualified pathname in Powershell?

I have a script that copies a number of files from different sources to a single directory for backup. The only step of the script the errors out has a space in both the path and file names: \\server\Network Shares\Transfer\tu3\tu3 Code.mdb
I get the error copy-item : Cannot find path '\\server\Network Shares\Transfer\tu3\tu3 Code.mdb' because it does not exist. and I'm assuming it's because of the spaces in either the path or filename. Does PowerShell allow spaces in a fully qualified path? If not, how can I get at the file?
Here's the relevant code (My$Destis defined as a global variable for the script):
$TU3CodeUpdatedPathname = "\\server\Network Shares\Transfer\tu3\"
$TU3CodeUpdatedFilename = "tu3 Code.mdb"
$TU3CodeUpdated = $TU3CodeUpdatedPathname + $TU3CodeUpdatedFilename
#
$Source = $TU3CodeUpdated
$Dest = $VMShareSpacePathname
#
copy-item $Source $Dest
Try being more explicit, and wrap the parameter values in quotes. Adding -Verbose might help with debugging. If it's complaining the file doesn't exist, maybe double check that the file is indeed accessible when your script runs under the account, if it's not the same as your user account.
Copy-Item -Path "$Source" -Destination "$Dest"
Just to ensure, you might have mixed up the variable names TU3/HS3?
$TU3CodeUpdatedPathname = "\\server\Network Shares\Transfer\tu3\"
$TU3CodeUpdatedFilename = "tu3 Code.mdb"
$TU3CodeUpdated = Join-Path -Path $TU3CodeUpdatedPathname -ChildPath $TU3CodeUpdatedFilename
Otherwise I can't see anything wrong with your code.
Spaces are just fine within quotes as you did write it.
I would guess the running user from the script does not have access rights to the file/share.
This post might help in that case.
This worked for me to copy folder with space in its name. I am using powershell 4.0
$Source = "D:\test\Test cases"
$Dest = "D:\bck\Test cases"
Copy-Item -Path "$Source" "$Dest" -Recurse

path as parameter powershell

I have problem with path. I need to copy all files from directory I add as 1st parameter in Powershell command.
Now I have:
Copy-Item -Path "$args[0]/" -Filter*.*
So it will copy to location I am now (and it's ok, I don't want other location) but it doesn't copy anything. Please help.
Pretty sure the issue is that the 0 element in $args is not expanding in the string creating an invalid path. Wrap the variable in $() to allow it to expand inside a double quoted string. Else you would end up trying to copy the folder C:\TEST[0]/ which obviously is not correct.
Copy-Item -Path "$($args[0])/" -Filter *.* -Recurse
Not yet sure why you have a forward slash in there since Windows pathing uses backslashes.
function Copy-Something(){
test-Path "$($args[0])/"
test-path "$($args[0])"
}
Copy-Something C:\temp
With what little you have provided the output shows that it might be redundant to have the slash there. Would also recommend calling Test-Path on the argument anyway as it might have caught this for you.
True
True
From Question Comment
You are looking for the -Recurse parameter if you also want folder contents.
From Answer Comment
If you want the contents and not the folder you should be able to do something like this:
Copy-Item -Path "$($args[0])\*" -Filter *.* -Recurse
When in doubt, Get-Help Command.
PS C:\> Get-Help Copy-Item -ShowWindow
-------------------------- EXAMPLE 3 --------------------------
This command copies the contents of the C:\Logfiles directory
to the C:\Drawings\Logs directory. It creates the \Logs
subdirectory if it does not already exist.
Windows PowerShell
PS C:\> Copy-Item C:\Logfiles -Destination C:\Drawings\Logs -Recurse