Powershell Copy-Item going up few directories - powershell

I am trying to provide a path to Copy-Item cmdlet in Powershell which goes up few directories but I am getting error
"ERROR - failed with error: "A positional parameter cannot be found
that accepts argument '......\'."
The command I am trying to execute is
Copy-Item $Source + "..\..\..\" + ($environment) + "\*.config" $destination
Can anyone please guide me how can I go up few directories while providing a path to Copy-Item

You need to parenthese the first argument (source):
Copy-Item ($Source + "..\..\..\" + ($environment) + "\*.config") $destination
Consider using the Join-Path cmdlet when combining a path. You could also write something like:
$sourceDir = Join-Path (Get-Item $Source).Parent.Parent.Parent $environment
Get-ChildItem -Path $sourceDir -Filter '*.config' | Copy-Item -Destination $destination

I just had to put double quotes around the whole path rather than concatenating.
Copy-Item "$Source\..\..\..\$environment\*.config" $destination

Related

Powershell Copy-Item not copying even when folder exists

I have two consecutive calls to Copy-Item but the second one is not copying the file. Both are copying the same file to two different folders. Both folders exist. But the second one never copies. I tried commenting out the first one, but the second one still does not copy.
$deliveryFolder = "C:\Users\administrator.GTCS\Desktop\Delivery\1.5.6.1140\"
$localFolder = "C:\WebServerGateway\"
$fileSharingServerManifestFileName = "GTCS_GCS_FileSharingServer_Manifest.xml"
Copy-item -Path $localFolder$fileSharingServerManifestFileName -Destination $deliveryFolder"GcsData\Configurations\Platforms\DEV\Web Server Gateway" -Force
Copy-item -Path $localFolder$fileSharingServerManifestFileName -Destination $deliveryFolder"GcsData\Configurations\Platforms\INT\Web Server Gateway" -Force
If you are going to combine strings in this manner you need to wrap them in double quotes, to expand the variables:
$deliveryFolder = "C:\Users\administrator.GTCS\Desktop\Delivery\1.5.6.1140\"
$localFolder = "C:\WebServerGateway\"
$fileSharingServerManifestFileName = "GTCS_GCS_FileSharingServer_Manifest.xml"
Copy-item -Path "$localFolder$fileSharingServerManifestFileName" -Destination "$($deliveryFolder)GcsData\Configurations\Platforms\DEV\Web Server Gateway" -Force
Copy-item -Path "$localFolder$fileSharingServerManifestFileName" -Destination "$($deliveryFolder)GcsData\Configurations\Platforms\INT\Web Server Gateway" -Force
Notice I uses a subexpression $() in the -Destination argument. Because in your case the parser may have trouble determining where the variable name ends, therefore the string may not expand properly.
That said, neither of the arguments are particularly pretty/readable so I'd advise against this syntax. concatenating or better yet using Join-Path to derive the arguments are better choices:
$Path = $localFolder + $fileSharingServerManifestFileName
$Dest = $deliveryFolder + "GcsData\Configurations\Platforms\INT\Web Server Gateway"
Note: Concatenation forces you to pay attention to backslashes separating what would be the -Parent/-Child arguments in Join-Path
Or:
$Path = Join-Path $localFolder $fileSharingServerManifestFileName
$Dest = Join-Path $deliveryFolder "GcsData\Configurations\Platforms\INT\Web Server Gateway"
Then simply modify the commands:
Copy-item -Path $Path -Destination $Dest -Force
Copy-item -Path $Path -Destination $Dest -Force

Moving folders with the files with exceptions

I'm trying to move data from the "file" folder and exclude the Users folder. but in the end, the exception does not work.
Move-Item -Path $env:SystemDrive\$env:computername\File\* -exclude $env:SystemDrive\$env:computername\File\Users\* -Destination $env:SystemDrive\UserOld\
It is necessary to transfer the data and exclude the Users folder.
I tried using move-item in order to move folders while excluding a single folder and it doesnt seem like you need to include the entire path in the exclude.
I tried this:
Move-Item -Path C:\Users\D.Baier\Desktop\testenvironment\Source -Exclude mit-1 -Destination C:\Users\D.Baier\Desktop\testenvironment\Target\
and it seemed to work perfectly, just threw an error which seems to be a known issue, at least as far as I understand it.
The error was the following btw:
Move-Item : The Element cannot be moved, since the Element, located at "C:\Users\D.Baier\Desktop\testenvironment\Source\mit-1" does not exist.
In Line:1 Charakter:1
+ Move-Item -Path C:\Users\D.Baier\Desktop\testenvironment\Source \* -Exclu ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [Move-Item], PSInvalidOperationException
+ FullyQualifiedErrorId : InvalidOperation,Microsoft.PowerShell.Commands.MoveItemCommand
Hope that was helpful!
Edit: Sorry, my PC is set to German. I translated the error message as well as I can, however I doubt it is the exact same one one would get if you were to run this code on an English machine. I also apologize for any spelling mistakes I may have made.
First thing I want to touch on is how you're creating your paths. You shouldn't create them the way you are, you should instead use the Join-Path command :)
This is how I might approach your current problem:
#Creating path to source folder
$source = Join-Path -Path "$env:SystemDrive\$env:COMPUTERNAME" -ChildPath "File"
#Creating path to destination folder
$destination = Join-Path -Path $env:SystemDrive -ChildPath "UserOld"
#Looping through all the folders in the source
Get-ChildItem -Path $source -Directory -Recurse | ForEach-Object{
#Only moving the folder if the name isn't "Users"
if ($_.Name -ne "Users"){
Write-Host "Currently Moving: $_.Name"
#Copy-Item -Path $_.FullName -Destination $destination
}
}
Let me know how you get on, I've left the actual moving part commented out as I would encourage you to do more testing :)
carelessness
#Creating path to source folder
$source = Join-Path -Path "$env:SystemDrive\$env:COMPUTERNAME" -ChildPath "\File\C$\"
#Creating path to destination folder
$destination = Join-Path -Path $env:SystemDrive -ChildPath "UserOld"
$h = "Users", "Windows", "ProgramData"
#Looping through all the folders in the source
Get-ChildItem -Path $source -Recurse | ForEach-Object{
#Only moving the folder if the name isn't "Users"
if ($_.Name -ne "$h"){
Write-Host "Currently Moving: $_.Name"
}
Move-Item -Path $_.FullName -Exclude $h -Destination $destination
}
This option moves the Users folder without content.
For this reason, the combined answers.
#Creating path to destination folder
$destination = Join-Path -Path $env:SystemDrive -ChildPath "UserOld"
#Move with the exception
Move-Item -Path $env:SystemDrive\$env:computername\USMT\File\C$\* -Exclude "Users", "Windows","ProgramData","Program Files","Program Files (x86)" -Destination $destination

Copy Files on Same Directory using Powershell

I am trying to write powershell Script which will create backupfolder on same Path where Application exist and need to copy the folders & files into backupfolder before deploying. Below are the command was using to perform but am getting error
$Source = "C:\XYZ"
$BackupFolder = New-Item -ItemType Directory -Force -Path $source_$(Get-Date)
Copy-Item -Path $Source\* $BackupFolder -Force
Error: Cannot copy item C:\XYZ\Backup_18-02-2017 on to itself
Try:
Copy-Item $Source\* $BackupFolder -Exclude $BackupFolder
That will eliminate the folder that you are copying into as a source that is being copied from.
Variables can contain underscores. The following works and displays the string "asdf"
$a_ = "adsf"; $a_
Your New-Item cmdlet call should have failed since $source_ is not a variable and would return null. This is default behavior for PowerShell. When I run your code as is I get the following:
New-Item : Cannot find drive. A drive with the name '02/18/2017 22' does not exist.At line:1 char:1
+ New-Item -ItemType Directory -Force -Path "$source_$(Get-Date)" -what ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : ObjectNotFound: (02/18/2017 22:String) [New-Item], DriveNotFoundException
+ FullyQualifiedErrorId : DriveNotFound,Microsoft.PowerShell.Commands.NewItemCommand
So I would have expected your folder variable to be null. wOxxOm brings this up in comment as well
Several options to address what I am sure is the partial source of your issue.
$BackupFolder = New-Item -ItemType Directory -Force -Path "$source`_$(Get-Date)"
$BackupFolder = New-Item -ItemType Directory -Force -Path "$($source)_$(Get-Date)"
$BackupFolder = New-Item -ItemType Directory -Force -Path ("{0}_{1} -f "$source, Get-Date)
You will still have to try and exclude this folder from the copy as well like Keith Hill's answer is telling you
Copy-Item $Source\* $BackupFolder -Exclude $BackupFolder
try Something like this
$Source = "C:\XYZ"
$Destination="{0}{1:yyyyMMdd}" -f $source, (Get-Date)
New-Item -ItemType Directory -Force -Path $Destination
Copy-Item -Path $Source\* $Destination -Recurse -Force
If I understand the question correctly. You want to take "C:\XYZ" and backup into the same directory called "C:\XYZ\backup_$DATE". What you will actually do is create a loop that will break once it reaches the max 248 characters. If we use the -exclude option then we can exclude the backup directory "C:\XYZ\backup_$DATE".
This function will do the trick and also gives you error handling.
Function Get-CopyDirectory{
#####################
# Dynamic Variables #
#####################
$Date = Get-Date -format ddMM-yyyy
$Exclude="Backup*"
####################
# Static Variables #
####################
$AppPath = "F:\Test\"
$BackupPath = "$AppPath\BACKUP_$Date\"
if (Test-Path $BackupPath) {
Write-Host "Backup Exist" -f Cyan
}
else
{
Copy-Item "$AppPath\*" $BackupPath -Exclude $Exclude -recurse -verbose
}
}
CLS
Get-CopyDirectory

Test-Path Move-Item Problems

I run this PowerShell script, and it works fine on PowerShell 4.0. But I now have PowerShell 5.0 and the script does work but it throws an error:
The Script:
$path = "X"
$destination = "Y"
while (Test-Path -Path $path) {
Move-Item -Path "$path\*zip" -Destination "$destination"
}
The error I get is:
Move-Item : The process cannot access the file because it is being
used by another process.
The title of the question: "Test-Path Move-Item Problems" implies that one cmdlet might be impacting the other. That doesn't make sense to me as Test-Path is checking the folder's existence and Move-Item is working on child items within that folder.
Personally I would not use a while loop for this use case as, once you have determined that the path exists you don't need to keep testing it:
if(Test-Path -Path $path){
Move-Item -Path $path\*zip -Destination $destination
}
just do it
Move-Item -Path "$path\*zip" -Destination "$destination" -ErrorAction Ignore

PowerShell: Copy-Item Cannot find path

I'm trying to get PowerShell to copy files from a remote computer (on which I have admin rights through AD) to the local computer.
It fails in the strangest place. Here's a snippet of the script:
$configs = Get-ChildItem -Recurse -ErrorAction SilentlyContinue -Filter "*.config" $serverUNCPath
foreach($config in $configs){
$config_target_dir = $dest.Path + $config.Directory.FullName.Replace($serverUNCPath,"")
if(Test-Path -Path $config_target_dir){
Copy-Item $config -Destination $config_target_dir
}
}
It fails with the message
Cannot find path 'D:\ServerDeploy\TestMachine1\website\web.config' because it does not exist.
At :line:39 char:12
+ Copy-Item <<<< $config -Destination $config_target_dir
The path D:\ServerDeploy\TestMachine1\website exists. I'm going mad over this.
What can I do to fix it?
Eeeeh.... OK?
If I replaced the line
Copy-Item $config -Destination $config_target_dir
with
Copy-Item $config.FullName $config_target_dir
it suddenly magically worked....
What gives?