I have this type of code in a backup script.
while($true){
$time = Get-Date -Format HH:mm:ss
$dateCheck = (Get-Date).AddDays(-0).ToString('dd-MM-yyyy')
[int]$check = $check
Get-ChildItem 'C:\fleet-integrator-installer-DHL2\work\matilda\14\done' -File |
Sort-Object -Property CreationTime -Descending |
Select-Object -First 1 |
Copy-Item -Destination \\Ict_nas\dhl\$dateCheck -Force
if($time -eq ('23:59:00')){
$check = $check - $check
}
if($time -eq ('23:59:30') -and $check -eq 0){
New-Item -ItemType "directory" -Path "\\Ict_nas\dhl" -Name $dateCheck | Out-Null
$check++
}
if($time -eq ('00:00:00')){
$fileCount = ( Get-ChildItem C:\fleet-integrator-installer-DHL2\work\matilda\14\done ).Count;
$EmailFrom = "..."
$EmailTo = "..."
$Subject = "Backup DHL Integrator -> IT NAS"
$Body = "The backup was succesful, $fileCount files are copied to the NAS"
$SMTPServer = "smtp.gmail.com"
$SMTPClient = New-Object Net.Mail.SmtpClient($SmtpServer, 587)
$SMTPClient.EnableSsl = $true
$SMTPClient.Credentials = New-Object System.Net.NetworkCredential("", "")
$SMTPClient.Send($EmailFrom, $EmailTo, $Subject, $Body)
Get-ChildItem -Path C:\fleet-integrator-installer-DHL2\work\matilda\14\done -Include *.* -File -Recurse | foreach { $_.Delete()}
}
}
It is creating automaticly an folder with the date of today on a NAS.
When i run the code separate it is working fine but in the script it is just creating a file with the date of today...
Anyone tips?
Thanks
You are copying to the directory before creating it:
Copy-Item -Destination \\Ict_nas\dhl\$dateCheck -Force
Because the directory does not exist (yet), the destination is interpreted as a file name. So the source file is copied to a file of that name.
I am not sure what your $check logic is supposed to do, but basically you have 2 options:
A) Create the directory first, before copying to it
New-Item "\\Ict_nas\dhl\$dateCheck" -Type Directory | Out-Null
Get-ChildItem 'C:\fleet-integrator-installer-DHL2\work\matilda\14\done' -File |
sort CreationTime -Descending | select -First 1 |
Copy-Item \\Ict_nas\dhl\$dateCheck
B) Specify a full file path for copying
Get-ChildItem 'C:\fleet-integrator-installer-DHL2\work\matilda\14\done' -File |
sort CreationTime -Descending | select -First 1 | foreach {
Copy-Item $_.FullName "\\Ict_nas\dhl\$dateCheck\$($_.Name)"
}
Related
I am using powershell to copy files into a folder, but I want to update the modified time [LastWriteTime] with the current time. I would like some advice on how I can do that once I copy the file. Below is my current code
$Date = Get-Date -Format "dd-MM-yyyy-dddd HH-mm"
$FROM = Get-ChildItem "C:\Testing\DeviceLists\" -Recurse
$TO = Get-ChildItem "C:\Transfer"
$LOGS = "C:\Testing\logs\"
#$d = [datetime](Get-ItemProperty -Path C:\Transfer -Name LastWriteTime).lastwritetime
$d = Get-ChildItem C:\Transfer\ -File | Sort-Object -Property -CreationTime | Select-Object -Last 1
foreach($item in $from){
$fromdate = $item.LastWriteTime
$ToFileInfo = $TO | where Name -eq $item.Name
if((Get-date $fromdate) -ge (Get-Date $d.LastWriteTime))
{
#Move the files that are greater than destination date
copy-item $item.FullName -Destination "C:\Transfer" -Force
#change lastwritetime of copied file
$item.LastWriteTime = (Get-Date)
Add-Content "$Logs\Log - $Date.txt" -Value "$item has been copied"
}
else
{
#log that file is having an error or lesser time
}
};
Add-Content "$Logs\Log - $Date.txt" -Value "All files have been copied"
Use -PassThru to make Copy-Item return the copied file info, then set the timestamp on that:
$newItem = Copy-Item $item.FullName -Destination "C:\Transfer" -Force -PassThru
$newItem.LastWriteTime = Get-Date
I have this working partially, I can get powershell to attach the latest 3 files in this directory, but I cannot get it to only pick files based on file type or extension. My issue is that these files have no extension and are actually "files".
Can anyone help me get this script to only pick "files"
# Start-Process Outlook
$outlook = New-Object -comObject Outlook.Application
$message = $outlook.CreateItem(0)
$message.To = "test#test.com" # for multiple email use ';' as separator
#$message.CC = "" # for multiple email use ';' as separator
$message.Subject = "Files $((get-date).adddays(-1).toshortdatestring())"
$message.Body = "Attached."
$path = "C:\Downloads"
#$lastest = Get-ChildItem -Path $path -File | Sort-Object -Property LastAccessTime -Descending | Select-Object -First 3
Get-ChildItem -Path $path -File | Sort-Object -Property LastAccessTime -Descending | % { if ($_.Extension -eq ".file") {Send-Mail $_.FullName} }
foreach ($file in $lastest)
{
$message.Attachments.Add($file.FullName)
}
$message.Display()
Got this script running. Nearly completed my mission to print attachments from it that land in a specific subfolder of outlook
$OutputFolder = 'C:\tests';
$outlook = New-Object -ComObject Outlook.Application;
$olFolderInbox = 6;
$ns = $outlook.GetNameSpace("MAPI");
$inbox = $ns.GetDefaultFolder($olFolderInbox);
$inbox.Folders `
| ? Name -eq 'colour' `
| % Items `
| % Attachments `
| % {
$OutputFileName = Join-Path -Path $OutputFolder -ChildPath $_.FileName;
if (Test-Path $OutputFileName) {
$FileDirectoryName = [System.IO.Path]::GetDirectoryName($OutputFileName);
$FileNameWithoutExtension = [System.IO.Path]::GetFileNameWithoutExtension($OutputFileName);
$FileExtension = [System.IO.Path]::GetExtension($OutputFileName);
for ($i = 2; Test-Path $OutputFileName; $i++) {
$OutputFileName = "{0} ({1}){2}" -f (Join-Path -Path $FileDirectoryName -ChildPath $FileNameWithoutExtension), $i, $FileExtension;
}
}
Write-Host $OutputFileName;
$_.SaveAsFile($OutputFileName)
}
Remove-Item -Path C:\tests\*.jpg
Dir C:\tests\ | Out-Printer -name xerox-b8
Remove-Item -Path C:\tests\*.*
when i try to pipe the objects to print i am getting XML printing out, or just the directory contents
I have tried:
select-object (wrong)
get-childitem (wrong)
DIR C:\tests\*.* (only returns directory listing printout)
These either return a load of XML rubbish or just a directory listing,
How can i pipe the contents of a folder to a printer using powershell, surely this can be done
I searched, i googled.. about to smash my head on the table
how come this will not work?
move-Item $path$file $targetdir
it gives me an error
Move-Item : An object at the specified path C:\Repository\test.csv
does not exist.
now if i debug this and i output using
write-output move-Item $path$file $targetdir
and take that output and paste it (file name with path and destination) it works!
and trust me the file is there. =\
Code below
$path = 'C:\test\'
$TimeStamp = Get-Date -Format "MM-dd-yyyy_hh-mm-ss"
$LogFile = Get-Date -Format "MM_dd_yyyy"
$targetdir = "C:\test\Uploaded\"
#Get-ChildItem -path $path\* -Include *.csv | foreach-object {$_.Fullname} | Format-Table name -hidetableheaders | Out-File $path\list.txt
Get-ChildItem -path $path\* -Include *.csv | Format-Table name -hidetableheaders | Out-File $path\list2.txt
get-content C:\test\list2.txt | where {$_ -ne ""} | out-file C:\test\list.txt
Remove-Item C:\test\list2.txt
$list = get-content C:\test\list.txt
foreach ($file in $list)
{
$ftp = "ftp://REMOVED/$file"
"ftp url: $ftp"
$webclient = New-Object System.Net.WebClient
$uri = New-Object System.Uri($ftp)
"Uploading $file..."
$succeeded = $true;
& {
trap { $script:succeeded = $false; continue }
$webclient.UploadFile($uri, $path+$file)
}
if ($succeeded)
{
echo $file 'Was successfully uploaded!' $Timestamp >> logfile$LogFile.log
move-Item -path $path$file -destination $targetdir
#test-path $path$file
}
else
{
echo $file 'Was not successfully uploaded, will retry later' $Timestamp >> logfile$LogFile.log
}
}
exit
Basics are:
Test-Path before you move it (file and destination)
Move the file, ensure you have permission (force it to move)
so:
echo $targetdir
echo "$path$file"
if (!(Test-Path $targetdir)) {
New-Item -ItemType directory $targetdir
}
if(Test-Path "$path$file") {
Move-Item "$path$file" $targetdir -Force
} else {
echo "file does not exist"
}
If you loop over a collection you have to use the ".FullName" property of the object:
Get-ChildItem $path | ForEach-Object { Move-Item $_.FullName $targetdir -Force }
Does the target directory already exist? I believe Move-Item will fail if the target directory doesn't exist. If that's the case, you can simply test for existence of the directory beforehand and then create as necessary.
If (!(Test-Path -Path $targetdir)) {
New-Item -ItemType directory -Path $targetdir
}
This worked for me. Thank you #TheMadTechnician. Hopes this helps everyone
$TimeStamp = Get-Date -Format "MM-dd-yyyy_hh-mm-ss"
$LogFile = Get-Date -Format "MM_dd_yyyy"
$path='C:\test\'
$targetDir = 'C:\test\Uploaded\'
$fileList = Get-ChildItem $path*.csv
If(!(Test-Path $TargetDir)){New-Item -ItemType Directory -Path $TargetDir|Out-Null}
$fileList | Select -ExpandProperty Name | Out-File 'C:\test\list.txt'
$list = get-content C:\test\list.txt
foreach ($file in $list)
{
$ftp = "ftp://REMOVED/$file"
"ftp url: $ftp"
$webclient = New-Object System.Net.WebClient
$uri = New-Object System.Uri($ftp)
"Uploading $file..."
$succeeded = $true;
& {
trap { $script:succeeded = $false; continue }
$webclient.UploadFile($uri, $path+$file)
}
if ($succeeded)
{
echo $file 'Was successfully uploaded!' $Timestamp >> logfile$LogFile.log
move-Item -path $path$file -destination $targetdir$Timestamp"_"$file
#test-path $path$file
}
else
{
echo $file 'Was not successfully uploaded, will retry later' $Timestamp >> logfile$LogFile.log
}
}
exit
How about this then:
ForEach($File in $List){
Join-Path $path $file | Move-Item -Dest $Targetdir
}
Edit: Also... your creation of list.txt, it bothered me so I had to comment. Format-Table should be used for formatting text, not for selecting a value to output to a file. There's a better way to do that, consider this alternative:
Get-ChildItem "$path*.csv" | Select -ExpandProperty Name | Out-File $pathlist.txt
Since you say that $path = 'C:\test\' you are adding extra backslashes in there that may cause issues for some commands.
Edit2: Ok, if that doesn't work, why not work with the files themselves instead of outputting to a file, importing from that file, and then working with things.
$path='c:\test\'
$TargetDir = 'c:\test\NewDir'
$FileList = Get-ChildItem $path*.csv
If(!(Test-Path $TargetDir)){New-Item -ItemType Directory -Path $TargetDir|Out-Null}
$FileList | Move-Item -Destination $TargetDir
Then if you really want a list of those file names just pipe $FileList to Select and then to Out-File
$FileList | Select -ExpandProperty Name | Out-File 'C:\Test\list.txt'
Here, look through this and see if there's anything you like. I made a few changes, such as declaring paths at the beginning for everything, I moved the WebClient object creation outside of the loop, and changed how things are displayed on screen. Plus I skip the entire exporting to text file and re-importing it.
$path = 'C:\test'
$ftpaddr = 'ftp://ftp.example.com/uploads'
$TimeStamp = Get-Date -Format "MM/dd/yyyy hh:mm:ss tt"
$LogFile = Get-Date -Format "MM_dd_yyyy"
$LogDir = "C:\Test\Logs"
If(!(test-path $LogDir)){New-Item -ItemType Directory -Path $LogDir | Out-Null}
$targetdir = 'C:\test\Uploaded'
If(!(test-path $targetdir)){New-Item -ItemType Directory -Path $targetdir | Out-Null}
$list = Get-ChildItem -path $path\* -Include *.csv
$webclient = New-Object System.Net.WebClient
"ftp url: $ftpaddr"
foreach ($file in ($list|select -ExpandProperty Name))
{
$uri = New-Object System.Uri(("$ftpaddr/$file"))
Write-Host "Uploading $file... " -NoNewline -ForegroundColor White
$succeeded = $true
& {
trap { $script:succeeded = $false; continue }
$webclient.UploadFile($uri, "$Path\$file")
}
if ($succeeded)
{
Write-Host "Success!" -ForegroundColor Green
"$Timestamp`t$File was successfully uploaded!" | Out-File "$logdir\logfile$LogFile.log" -Append
move-Item -path "$path\$file" -destination $targetdir
}
else
{
Write-Host "Failed! Will retry later." -ForegroundColor Red
"$Timestamp`t$File was not successfully uploaded, will retry later" | Out-File "$logdir\logfile$LogFile.log" -Append
}
}
I am new to powershell and am running into a problem while trying to exclude certain directories during recursive copy. Any help is appreciated!
Thanks in advance.
$Date = Get-Date
$Date = $Date.adddays(-1)
$destPath = "\\destination\test"
$srcPath = "H:\program files\symphony\Save"
$srcPathRemits = “H:\program files\symphony\files"
$destDrive = "X:"
$User = "user"
$Password = "password"
$exclude = #('H:\program files\symphony\files\Temp\*','H:\program files\symphony\files\Other\*','H:\program files\symphony\files\etc\*','H:\program files\symphony\files\ParsedXML\*')
$net = new-object -ComObject WScript.Network
$net.MapNetworkDrive($destDrive, $destPath, $false, $User, $Password)
gci -recurse -path $srcPathRemits -Exclude $exclude | ? {!($_.psiscontainer) -AND $_.lastwritetime -gt $Date} | % { write-host $_.fullname; Copy-Item -path $_.fullname -destination $destDrive}
$net.RemoveNetworkDrive($destDrive,"true","true")
You didn't say what the problem was, but I'll assume that the directories ($exclude) were not properly excluded. Try this instead, for the gci line:
Get-Item -Path H:\program files\symphony\files\* -Exclude Temp, Other, etc, ParsedXML | Get-ChildItem -recurse | ? {!($_.psiscontainer) -AND $_.lastwritetime -gt $Date} | % { write-host $_.fullname; Copy-Item -path $_.fullname -destination $destDrive}