I have a question, last saturday when I was migrate DC from Windows 2003 to 2012R2, everything was migrate ok, but I can't run a ps script on Windows 2012R2. I change some parameter, mail adress etc.
param([String]$EmailTo = "user#domain.com")
psql.exe -h 10.1.1.20 -p 5432 -w -H -f C:\Scripts\errors_o_htm_V3.sql' -o 'C:\Scripts\errors.html -U script database
$file = "C:\Scripts\errors.html"
$old = Get-Content $file
Add-Content -Path $file -Value $old
$EmailFrom = "sender#domain.com"
$Subject = "Reports"
$SMTPServer = "smtp.serwer.com"
$SMTPClient = New-Object Net.Mail.SmtpClient($SmtpServer, 587)
$SMTPClient.EnableSsl = $false
$SMTPClient.Credentials = New-Object System.Net.NetworkCredential("user","password");
$msg = new-object Net.Mail.MailMessage
$msg.From = $EmailFrom
$msg.To.Add($EmailTo)
$msg.To.Add("user#domain.com")
$msg.Subject = $Subject
$msg.IsBodyHTML = $True
$msg.Body = $old
$msg.BodyEncoding = [System.Text.Encoding]::GetEncoding("UTF-8")
$SMTPClient.Send($msg)
When I run script manualy, he generate error file and send it, but when I want to set it in scheduler - he send an empty mail, something wrong with psql.exe -h ......
I add psql path to Environment Variables.
In scheduler i set:
Program/Script powershell.exe or full path
Add arguments C:\Scripts\script.ps1, and also I add -f before path.
But when I run this script he don't generate the error file with data.
I thing something is wrong with shedule parameters.
Related
A task job is running by task scheduler every 30 mins everyday.
I just want one more task to monitor whether the task is completed or not.
Would you please give me the powershell script as necessary below.
Sorted by Event id : 101 and 102, specified task job name, action time, the job result in the last 24 hours,
I want to have log txt file into C drive. I guess it should be used "Get-WinEvent"...
Otherwise if you know it's simple way to export the result log automatically(Task completed or not)
on daily base, please let me know.
Thank you
See these examples to inspire you to what you are after. Once you've tried some things, well, you know.
Powershell Script to Monitor Scheduled Tasks
https://social.technet.microsoft.com/Forums/windows/en-US/dc607f76-02c1-489f-b519-340b0faf8fcd/powershell-script-to-monitor-scheduled-tasks
$servername = "tome-mac"
$schedule = new-object -com("Schedule.Service")
$schedule.connect($servername)
$tasks = $schedule.getfolder("\").gettasks(0)
$tasks |select name, lasttaskresult, lastruntime
Make Windows Task Scheduler alert me on fail
https://superuser.com/questions/249103/make-windows-task-scheduler-alert-me-on-fail
$ScheduledTaskName = "Hans\Backup"
$Result = (schtasks /query /FO LIST /V /TN $ScheduledTaskName | findstr "Result")
$Result = $Result.substring(12)
$Code = $Result.trim()
If ($Code -gt 0) {
$User = "mymail#gmail.com"
$Pass = ConvertTo-SecureString -String "myPassword" -AsPlainText -Force
$Cred = New-Object System.Management.Automation.PSCredential $User, $Pass
################################################################################
$From = "Alert Scheduled Task <mymail#gmail.com>"
$To = "Me Gmail <mymail#gmail.com>"
$Subject = "Scheduled task 'Backup' failed"
$Body = "Error code: $Code"
$SMTPServer = "smtp.gmail.com"
$SMTPPort = "587"
Send-MailMessage -From $From -to $To -Subject $Subject `
-Body $Body -SmtpServer $SMTPServer -port $SMTPPort -UseSsl `
-Credential $Cred
}
Or just use these module(s) to determine if they can assist you in your use case.
https://www.powershellgallery.com/packages/TaskScheduler/1.0
https://gallery.technet.microsoft.com/scriptcenter/Schedule-Task-Monitor-a7c74403
I have been struggling to get a script to work that can FTP a file to a remote windows server and wanted to see if I could get some help. I searched through multpile pages on StackOverflow and Google and have been unsuccessful so far.Below is the code I have
Logic is as follows:
Pick up the oldest file with a pattern within a folder
Connect to FTP server
Copy the file to the remote server
Move the file from the in folder to an archive folder
Code seems to be failing where I try to FTP the file to the server - $webclient.UploadFile($uri,$latestfile)
Getting this exception:
Exception calling "UploadFile" with "2" argument(s): "An exception occurred during a WebClient request."
At C:\Downloads\powershell\testmove3.ps1:22 char:26
+ $webclient.UploadFile <<<< ($uri,$latestfile)
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : DotNetMethodException
$source = "C:\downloads\"
$destination = "C:\dest\"
Get-ChildItem -Path C:\downloads | Where-Object { $_.name -like "TEST.CSV-PlainText*.txt" }
$latestfile=gci -path $source | Where-Object { $_.name -like "TEST.CSV-PlainText*.txt"} | sort FirstWriteTime | select -last 1
"Oldest File $latestfile"
## Get ftp object
$ftp_client = New-Object System.Net.WebClient
$user="someuser"
$pass="somepass"
$ftp_address = "ftp://ftp.testserver.com"
## Make uploads
$uri = New-Object System.Uri($ftp+$item.Name)
"Item is $latestfile"
$webclient.UploadFile($uri,$latestfile)
"File uploaded to remote servr"
Move-Item $latestfile.FullName $destination
"File $latestfile moved"
Ok, was on it overnight and happy to report that I got a solution - yeeehaw !!
I have even added a logic to trap an exception and send out an email notification. Hope this helps anyone with their FTP issues using Powershell. At the end, it returns a success or failure code to the calling program.
#PowerShell.exe -File "C:\temp\FTP.ps1"
trap [Exception] {
$recipient = "recipient#yahoo.com"
$sender = "sender#yahoo.com"
$server = "test.mailserver.com"
$subject = "FTP Test"
$body = "Exception Title: " + $_.Exception.GetType().FullName + "`r`n`r`n" + "Exception Details: " + $_.Exception.Message
$msg = new-object System.Net.Mail.MailMessage $sender, $recipient, $subject, $body
$client = new-object System.Net.Mail.SmtpClient $server
$client.Credentials = [System.Net.CredentialCache]::DefaultNetworkCredentials
$client.Send($msg)
exit 1
}
$ftpuser = "testuser"
$ftppass = "testpass"
$ftpserver = "ftp://ftp.testserver.com/"
$file = "C:\temp\one.txt"
$filenewname = "one.txt"
$webclient = New-Object System.Net.WebClient
$ftp = $ftpserver+$filenewname
$uri = New-Object System.Uri($ftp)
#Error was happening because the method call was attempting to use the HttpProxy on the Server machine.
#If the proxy is not set to null explicitly in your code, then you will get error - "An exception occurred during a webclient request"
$webclient.Proxy = $NULL
$webclient.Credentials = New-Object System.Net.NetworkCredential($ftpuser,$ftppass)
"Uploading $filenewname in $ftpserver"
$webclient.UploadFile($uri,$file)
"Uploaded $filenewname in $ftpserver"
return 0
If this is going to be used in any live support environment, I like to suggest using a prompt for password:
$ftppass = Read-Host "Enter password" -AsSecureString
Hoping someone can guide me / help me.
The issue, I have 2 servers one running a Ubuntu which has a website for clients to login and download / view reports. The other is a windows server 2012 R2 which creates / stores the reports. I need to move the files from the windows to the Ubuntu server so clients can view. The data is large currently 7gb and growing at 3 gb a year.
I need a batch file to connect using ftp and then copy the folder to a local folder. However it only needs to copy those files which have modified.
I have only ever written one batch file and I cant seem to find any ftp batch scripts which only copies modifed files.
Your my last resort as I cant seem to find a coder who knows batch script (its a dieing art). I have never used powershell so would not know where to start here.
Any help or advice please let me know.
Thanks
John
You can do it with PowerShell with winscp. Exemple :
try
{
# Load WinSCP .NET assembly
Add-Type -Path "WinSCPnet.dll"
# Setup session options
$sessionOptions = New-Object WinSCP.SessionOptions -Property #{
Protocol = [WinSCP.Protocol]::Sftp
HostName = "example.com"
UserName = "user"
Password = "mypassword"
SshHostKeyFingerprint = "ssh-rsa 2048 xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx"
}
$session = New-Object WinSCP.Session
try
{
# Connect
$session.Open($sessionOptions)
# Upload files
$transferOptions = New-Object WinSCP.TransferOptions
$transferOptions.TransferMode = [WinSCP.TransferMode]::Binary
$transferResult = $session.PutFiles("d:\toupload\*", "/home/user/", $False, $transferOptions)
# Throw on any error
$transferResult.Check()
# Print results
foreach ($transfer in $transferResult.Transfers)
{
Write-Host ("Upload of {0} succeeded" -f $transfer.FileName)
}
}
finally
{
# Disconnect, clean up
$session.Dispose()
}
exit 0
}
catch [Exception]
{
Write-Host ("Error: {0}" -f $_.Exception.Message)
exit 1
}
This would be a way to do it in PowerShell. It would take files that are older then 31 days and upload them.
function FTP-Upload {
[CmdletBinding()]
param(
[Parameter(Mandatory=$true)]
[string]$Source_File,
[Parameter(Mandatory=$true)]
[string]$Target_File,
[Parameter(Mandatory=$true)]
[string]$Target_Server,
[Parameter(Mandatory=$true)]
[string]$Target_Username,
[Parameter(Mandatory=$true)]
[string]$Target_Password
)
$FTP = [System.Net.FTPWebRequest]::Create("ftp://$Target_Server/$Target_File")
$FTP = [System.Net.FTPWebRequest]$FTP
$FTP.Method = [System.Net.WebRequestMethods+Ftp]::UploadFile
$FTP.Credentials = New-Object System.Net.NetworkCredential($Target_Username,$Target_Password)
$FTP.UseBinary = $true
$FTP.UsePassive = $true
# read in the file to upload as a byte array
$content = [System.IO.File]::ReadAllBytes($Source_File)
$FTP.ContentLength = $content.Length
# get the request stream, and write the bytes into it
$rs = $FTP.GetRequestStream()
$rs.Write($content, 0, $content.Length)
# be sure to clean up after ourselves
$rs.Close()
$rs.Dispose()
}
$Upload_Server = "server.network.tld"
$Upload_Location = "/data/"
$Upload_Username = "ftpuser"
$Upload_Password = "ftppassword"
$Files_To_Upload = Get-ChildItem E:\Path\To\Files -Recurse | Where-Object {($_.CreationTime -le (Get-Date).AddDays(-31)) -and (!$_.PSIsContainer)}
Foreach ($File in $Files_To_Upload) {
FTP-Upload -Source_File $File.FullName -Target_File ($Upload_Location + $File.Name) -Target_Server $Upload_Server -Target_Username $Upload_Username -Target_Password $Upload_Password
}
I am working on a PowerShell script that is run from another application that is called after a success event and executes a series of commands:
First it zips a designated file (ExampleFile)
Then deleted the original
Uploads the zipped file to a server through FTP
My problem starts during the FTP process: as it exists below - the ZIP file is created correctly in the local system, and a ZIP file is created on the FTP server but it's stuck with a filesize of 0 bytes.
From the server, it looks like the upload hangs?
So: Lines 1-3 all work fine and the local zipped file has a non-zero size.
Add-Type -A 'System.IO.Compression.FileSystem';
[IO.Compression.ZipFile]::CreateFromDirectory("ExampleFolder\ExampleFile", "ExampleFolder\ExampleFile_Datestamp.zip");
Remove-Item -Recurse -Force "ExampleFolder\ExampleFile";
$Username = "exampleusername";
$Password = "examplepassword";
$LocalFile = "C:\Users\example_path\ExampleFolder\ExampleFile.zip";
$RemoteFile = "ftp://exampleserver/examplepath2/ExampleFile_Datestamp.zip";
$FTPRequest = [System.Net.FtpWebRequest]::Create("$RemoteFile");
$FTPRequest = [System.Net.FtpWebRequest]$FTPRequest;
$FTPRequest.Method = [System.Net.WebRequestMethods+Ftp]::UploadFile;
$FTPRequest.Credentials = new-object System.Net.NetworkCredential($Username, $Password);
$FTPRequest.UseBinary = $true;
$FTPRequest.UsePassive = $true;
$FileContent = gc -en byte $LocalFile;
$FTPRequest.ContentLength = $FileContent.Length;
$Run = $FTPRequest.GetRequestStream();
$Run.Write($FileContent, 0, $FileContent.Length);
$Run.Close();
$Run.Dispose();
This has me pretty well stumped, so any ideas or thoughts appreciated.
powershell.exe -nologo -noprofile -command "Add-Type -A 'System.IO.Compression.FileSystem'; [IO.Compression.ZipFile]::CreateFromDirectory(\"ExampleFolder\ExampleFile\", \"ExampleFolder\ExampleFile_Datestamp.zip\"); Remove-Item -Recurse -Force \"ExampleFolder\ExampleFile\"; $Username = \"exampleusername\"; $Password = \"examplepassword\"; $LocalFile = \"C:\Users\example_path\ExampleFolder\ExampleFile.zip\"; $RemoteFile = \"ftp://exampleserver/examplepath2/ExampleFile_Datestamp.zip\"; $FTPRequest = [System.Net.FtpWebRequest]::Create(\"$RemoteFile\"); $FTPRequest = [System.Net.FtpWebRequest]$FTPRequest; $FTPRequest.Method = [System.Net.WebRequestMethods+Ftp]::UploadFile; $FTPRequest.Credentials = new-object System.Net.NetworkCredential($Username, $Password); $FTPRequest.UseBinary = $true; $FTPRequest.UsePassive = $true; $FileContent = gc -en byte $LocalFile; $FTPRequest.ContentLength = $FileContent.Length; $Run = $FTPRequest.GetRequestStream(); $Run.Write($FileContent, 0, $FileContent.Length); $Run.Close(); $Run.Dispose();
You are missing a call to FtpWebRequest.GetResponse:
...
$Run = $FTPRequest.GetRequestStream();
$Run.Write($FileContent, 0, $FileContent.Length);
$Run.Close();
$FTPResponse = $FTPRequest.GetResponse()
Write-Out $FTPResponse.StatusCode
Write-Out $FTPResponse.StatusDescription
See How to: Upload Files with FTP.
I need to find the most recent file in a folder/dir and send that file as an attachment in a email, so far i have this code that find the most recent file in my windows SO, but i need to specify a route a find the most recent file there and then send that file in a email so far i have this:
EDIT 1:
So far i have this:
This part gives me the last file created in a dir/folder:
$dir = "D:\Users\myUser\Desktop\dirTest"
$latest = Get-ChildItem -Path $dir | Sort-Object LastAccessTime -Descending | Select-Object -First 1
$latest.Fullname
$attachment = $latest.Fullname
And this send the email (i'm using yahoo accounts):
$emailSmtpServer = "smtp.mail.yahoo.com"
$emailSmtpServerPort = "587"
$emailSmtpUser = "yahooAccountThatSendsTheEmail#yahoo.com"
$emailSmtpPass = "passForThisquestion"
$emailMessage = New-Object System.Net.Mail.MailMessage
$emailMessage.From = "yahooAccountThatSendsTheEmail#yahoo.com"
$emailMessage.To.Add( "yahooAccountThatRECIEVESTheEmail#yahoo.com" )
$emailMessage.Subject = "Testing e-mail"
$emailMessage.Body = "email from power shell"
$emailMessage.Attachments.Add( $attachment ) <---- this part gives me problems
$SMTPClient = New-Object Net.Mail.SmtpClient($emailSmtpServer, $emailSmtpServerPort)
$SMTPClient.EnableSsl = $true
$SMTPClient.Credentials = New-Object System.Net.NetworkCredential($emailSmtpUser, $emailSmtpPass);
$SMTPClient.Send($emailMessage)
It works now, this is my final script.
This script search the most recent file created in a Dir and it sends that file created to a email account.
Here is my script it works for me but it takes a few minutes to send the email, thanks for the help
This script do what i wanted, it find the most recent file and send tha file in a email.
$dir = "d:\Users\myUser\Desktop\testDir"
$latest = Get-ChildItem -Path $dir | Sort-Object LastAccessTime -Descending | Select-Object -First 1
$latest.Fullname
$attachment = $latest.Fullname
$emailSmtpServer = "smtp.mail.yahoo.com"
$emailSmtpServerPort = "587"
$emailSmtpUser = "test_sender_mail_account#yahoo.com"
$emailSmtpPass = "MyPassword"
$emailMessage = New-Object System.Net.Mail.MailMessage
$emailMessage.From = "test_sender_mail_account#yahoo.com"
$emailMessage.To.Add( "test_receiver_mail_account#gmail.com" )
$emailMessage.Subject = "My Subject"
$emailMessage.Body = "My body message"
$emailMessage.Attachments.Add($attachment)
$SMTPClient = New-Object Net.Mail.SmtpClient($emailSmtpServer, $emailSmtpServerPort)
$SMTPClient.EnableSsl = $true
$SMTPClient.Credentials = New-Object System.Net.NetworkCredential($emailSmtpUser, $emailSmtpPass);
$SMTPClient.Send($emailMessage)
With PowerShell, something like this should do alright:
function Send-RecentFile {
param(
[ValidateScript({Test-Path $_ })]
[String] $Path
)
$file = Get-ChildItem -Path $Path -File | Sort CreationTime | Select -Last 1
Write-Output "The most recently created file is $($file.Name)"
$messageParameters = #{
From = "myaccount#mydomain.com"
To = "destinationAccount#theirdomain.com"
Subject = "title"
Body = "message body"
SMTPServer = "mail.mydomain.com"
Attachments = $file.FullName
}
Send-MailMessage #messageParameters -Credential (Get-Credential "peopleo#anotherDomain.com")
}
If you do want to store the credentials in the file, you might have to do something slightly different with it.
Please check this powershell command.
$Body = “get the information here to show the data with attachement”
$dir = "Path\of\the\folder(C:\..\..)"
$latest = Get-ChildItem -Path $dir | Sort-Object LastAccessTime -Descending | Select-Object -First 1
$latest.Fullname
$file = $latest.Fullname
$EmailFrom = “sender#gmail.com”
$EmailTo = “receiver#gmail.com”
$SMTPServer = “smtp.gmail.com”
$EmailSubject = “Enter Your Subject”
$att = new-object Net.Mail.Attachment($file)
$mailmessage = New-Object system.net.mail.mailmessage
$mailmessage.from = ($EmailFrom)
$mailmessage.To.add($EmailTo)
$mailmessage.Subject = $EmailSubject
$mailmessage.Body = $Body
$mailmessage.IsBodyHTML = $true
$mailmessage.Attachments.Add($att)
$SMTPClient = New-Object Net.Mail.SmtpClient($SmtpServer, 587)
$SMTPClient.EnableSsl = $true
$SMTPClient.Credentials = New-Object System.Net.NetworkCredential(“sender_username”, “sender_password”);
$SMTPClient.Send($mailmessage)
$att.Dispose()