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
Related
I am trying to copy latest 30days files to the folder by this code:
$month = (get-date).AddDays(-30).ToString("yyyMM")
$lastmonthfiles = Write-Host (-join('DCP_', $month,"*.csv"))
Copy-Item -Path Write-Host (-join ("C:\DC+\History\", $lastmonthfiles)) -Destination C:\DC+\History\Backup
but I am having a problem in path in copy-item instruction, which is
Copy-Item : A positional parameter cannot be found that accepts argument 'C:\DC+\History\'.
At line:5 char:1
+ Copy-Item -Path Write-Host (-join ("C:\DC+\History\", $lastmonthfiles ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidArgument: (:) [Copy-Item], ParameterBindingException
+ FullyQualifiedErrorId : PositionalParameterNotFound,Microsoft.PowerShell.Commands.CopyItemCommand
I am new in PowerShell, and programming so, I could not understand, how can I update and achieve a goal.
Try this:
$Source = Get-Item "C:\Games"
$Destination = "E:\Backup"
$LogFile = "C:\Copy-LogFile.txt"
Copy-Item -Path $( $Source | Where LastWriteTime -LE (Get-Date).AddDays(-30) ) -Destination $Destination -Recurse -PassThru |
Out-File $LogFile -Force
This takes care of your copy function and generates an output log.
Sorry, but your code makes no sense to me...
If it is your aim to copy files to a subfolder in a backup path, try this:
# get the date to use as subfolder to copy to and also to filter the last 30 days files
$refDate = (Get-Date).AddDays(-30).Date # .Date sets it to midnight
# set this variable to the folder where the csv are to be found
$sourceFolder = 'X:\Path\To\Where\The\Files\Are'
# create a destination path to copy to (just a string)
$destination = Join-Path -Path 'C:\DC+\History\Backup' -ChildPath ($refDate.ToString("yyyMM"))
# create this destination folder
$null = New-Item -Path $destination -ItemType Directory -Force
# get the files and copy them to the destination folder
Get-ChildItem -Path $sourceFolder -Filter '*.csv' -File | # filter on CSV fies only
Where-Object { $_.LastWriteTime -ge $refDate } | # filter on date 'last 30 days'
Copy-Item -Destination $destination -Force
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
Trying to run the following, but getting a message path is denied
I am new to powershell
Set-Location -Path "C:\work\test
$newFILEStest=(1..100)
foreach($f in $newFILEStest)
{
$newFiletest1="business" +$f + ".txt"
new-item $newfiletest1 -path $source_businesspath
}
$source_businesspath = "C:\work\test\$(Get-Date -Format "yyyy-MM-dd")\business
Goal is: loop generate files such as business.txt inside of the subfolder: business.
Be able to run the ps1 file outside of PS command line
I've fixed the many quoting and logic problems here.
$source_businesspath = "work\test\$(Get-Date -Format 'yyyy-MM-dd')\business"
mkdir $source_businesspath
$newFILEStest=(1..10)
foreach($f in $newFILEStest)
{
$newFiletest1="business" +$f + ".txt"
new-item -name $newfiletest1 -path $source_businesspath
}
You need to make sure that your destination path exists before you create items in it. A simple Test-Path will be able to validate that the directory exists.
Obviously, you also need to have permission to create the directory and files.
$source_businesspath = "C:\Work\Test\$(Get-Date -Format 'yyyy-MM-dd')\business"
if (-not (Test-Path -Path $source_businesspath)) {
New-Item -Path $source_businesspath -ItemType Directory -Force
}
$newFILEStest = (1..10)
foreach ($f in $newFILEStest) {
$newFiletest1 = "business" + $f + ".txt"
New-Item -Path $source_businesspath -Name $newfiletest1
}
the paths are like this and none of these directory exist:
"D:\temp\test\abc.txt"
"D:\temp2\test2\abc2.txt"
"D:\temp1\abc.txt"
I am trying to split the path and create directories only.
I am trying below:
New-Item -Path "D:\temp\testing\abc.txt" -ItemType file
Split-Path -Path "D:\temp\testing\abc.txt" -Resolve –IsAbsolute
[edit - didn't see the comment by Tuttu. [*blush*] i will leave this here, but that one is the 1st answer.]
i think what you are looking for is the Split-Path cmdlet. [grin] something like this ...
$PathList = #(
'c:\temp\test1\abc.txt'
'c:\temp\test2\subtest2-1\abc2.txt'
'c:\temp\test3\subtest3-1\subtest3-1-1\abc.txt'
)
foreach ($PL_Item in $PathList)
{
$NewDir = Split-Path -Path $PL_Item -Parent
if (-not (Test-Path -LiteralPath $NewDir))
{
$Null = New-Item -Path $NewDir -ItemType Directory -Force
}
}
that made 3 new directories, two of them with sub-directories.
note that this does NOT take into account any input path that has no terminating file ... you will always get the parent path.
I am trying to script a solution copying some files from one location to another..
I have a list of files in a .csv format, with headers
"ParentFolder, Name, FullName, lastwritetime."
Content of file is, which has hundreds of lines, and different paths, but same drive letter:
"X:\clients\A90\201AA3.05\","2012.08 RAP Proposal.xlsm","X:\clients\A90\201AA3.05\2012.08 RAP Proposal.xlsm","20/05/2016 10:41:08"
What i would like to do is copy the above..
"X:\clients\A90\201AA3.05\2012.08 RAP Proposal.xlsm" to a new location with differnet drive, but same directory structure. So in the csv file i have the filename and path, but am unsure how to split the drive from there and make a variable.
I have a foreach loop..
$ToCopy = Import-Csv "c:\temp\log.csv"
foreach($Line in $ToCopy)
{
$FullPath = $Line.ParentFolder
$File = $Line.Name
$FullName = $Line.FullName
$file = "$FullPath\$FullName"
$DestPath = Split-Path $FullPath -NoQualifier
Copy-Item "$FullName" -Destination c:\test\$DestPath
}
Error message that i am getting is :
+ CategoryInfo : NotSpecified: (:) [Copy-Item], DirectoryNotFoundException
+ FullyQualifiedErrorId : System.IO.DirectoryNotFoundException,Microsoft.PowerShell.Commands.CopyItemCommand
Copy-Item : Could not find a part of the path 'C:\test\clients\A90\Support\_index0901\'.
At line:9 char:9
+ Copy-Item "$FullName" -Destination c:\test\$DestPath
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [Copy-Item], DirectoryNotFoundException
+ FullyQualifiedErrorId : System.IO.DirectoryNotFoundException,Microsoft.PowerShell.Commands.CopyItemCommand
You get the error because the directory structure of your target path probably does not exist
To solve that you can create a 'temporary' file with New-Item ... -Force which creates the missing directories if necessary and then overwrite that file with Copy-Item like so
$ToCopy = Import-Csv "c:\temp\log.csv"
foreach($Line in $ToCopy)
{
$FullPath = $Line.ParentFolder
$File = $Line.Name
$FullName = $Line.FullName
$file = "$FullPath\$FullName"
$DestPath = Split-Path $FullPath -NoQualifier
$DestFile = c:\test\$DestPath
New-Item -ItemType File -Force $DestFile
Copy-Item "$FullName" -Destination $DestFile -Force
}
You need to create the folders before attempting to copy files in them.
Here's a way to do it, simplified from what you have, but with an added line to take care of the folders' creation.
foreach($File in $ToCopy)
{
$DestPath = Join-Path -Path 'c:\test' -ChildPath ( Split-Path $File.ParentFolder -NoQualifier )
If ( -not ( Test-Path -Path $DestPath ) ) { New-Item -Path $DestPath -Force -ItemType Directory }
Copy-Item $File.FullName -Destination $DestPath -WhatIf
}
(Be careful, I change the iteration variable from $Line to $File)
You are trying to copy files into c:\test\ directory which does not exist. Create this directory before loop:
mkdir c:\test\
or, in case directory may exist
mkdir c:\test\ -Force