Showing posts with label powershell. Show all posts
Showing posts with label powershell. Show all posts

11 December 2012

How to loop through files in a folder by windows powershell


Step 1:
Create a powershell file named as loopfiles.ps1 (you can simply create a new text file and rename it as loopfiles.ps1).

Step 2:
Open the loopfiles.ps1 file and paste the following and save it:

############################


$fso = new-object -com scripting.filesystemobject
$folder = $fso.getfolder("C:\temp")

foreach ($f in $folder.files) {
    $f.path >> filesvisited.txt
$c = Get-Content $f.path
}
############################



Step 3:
Right click on the loopfiles.ps1 and select Run with Powershell.

At the end, one should have an output file (filesvisited.txt) with the names of the files in the current folder.

How to send email by windows powershell

The example below is built to run on gmail accounts.

Step 1:
Create a powershell file named as send_email.ps1 (you can simply create a new text file and rename it as send_email.ps1).

Step 2:
Open the send_email.ps1 file and paste the following and save it:


function fnSendEmail($Too,$Filee)
{
$smtpServer = "smtp.gmail.com"
$att = new-object Net.Mail.Attachment($Filee)
$msg = new-object Net.Mail.MailMessage
$smtp = new-object Net.Mail.SmtpClient($smtpServer, 587)
$smtp.EnableSsl = $true
$smtp.Credentials = New-Object System.Net.NetworkCredential("your-email@gmail.com", "your-password");
$msg.From = "your-email@gmail.com"
$msg.To.Add($Too)
$msg.Subject = "powershell test"
$msg.Body = "This is a test email with an attachment"
$msg.Attachments.Add($att)
$smtp.Send($msg)
$att.Dispose()
}

Step 3:

  • Start windows powershell 
  • change the directory to where the send_email.ps1 file is located (pls see the line 1 in the screenshot below)
  • call send_email.ps1 file (pls see the line 2 in the screenshot below), like that, one can use the fnSendEmail function in it
  • call fnSendEmail function by passing to parameters (recepient's email address and the full path of the file to be attached) (pls see the line 3 in the screenshot below)