Powershell Scripting Game-march 2016

Source: Internet
Author: User
Tags mailmessage

Again to the PowerShell script contest once a month. This time the topic is very interesting, tested several knowledge points, the beans took the half-day effort to realize completely.

http://powershell.org/wp/2016/03/05/2016-march-scripting-games-puzzle/

The topics are as follows:

A European file server with a large number of filenames are named after the Latin alphabet, they are all found out.

The following points are required for specific requirements:

    1. All of these Latin letters (French, German, and so on) belong to the Latin-1 alphabet category, only the documents containing the letters are found, and the other Latin symbols are not to be considered.

    2. Write a function to get the name, location, size of these files, size needs good readability, such as how many k the small file shows, how many m or how many grams the large file displays

    3. If the corresponding file information is found, yyyymmdd_filenameswithdiacritics.csv is saved as a CSV file in the following format. YYYYMMDD represents the year, month, and date.

    4. Write a scheduled task every 2 Saturday night 11 o'clock execute the above function

    5. e-Mail The attachments generated above to the administrator

    6. Http://powershell.org/wp/wp-content/uploads/2016/03/FileShare.zip This is a file for testing.


Here are the steps the beans complete:

1. The first problem to be solved is how to find the Latin alphabet? As prompted, I found that the Unicode code for Latin-1 is shown below. If you just display the letters and not the other symbols, then his code range is 00c0 to 00FF.

650) this.width=650; "src=" Http://s1.51cto.com/wyfs02/M00/7D/1F/wKioL1bgpe-gmvgyAACTVqjAcz4601.png "title=" 1.PNG " alt= "Wkiol1bgpe-gmvgyaactvqjacz4601.png"/>

That way I can use regular expressions to determine if the filenames include these symbols. Like what

Get-childitem-recurse C:\Test | where-object {$_.name-match "[\u00c0-\u00ff]"}


2. The output file size must also be well readable. His default output is in bytes, I need to redefine it based on size, and if the precision is too long it's hard to see, I need to keep one after the decimal point.

I can judge in the custom field, if less than 1000 bytes in byte display, less than 1M in KB display, greater than 1G in MB display.


For example

  Get-ChildItem -Recurse -Path  $path |          Where-Object {$_.name -match  "[\u00c0-\u00ff]"} |          select Name, directory, creationtime, lastwritetime,         @{        n= "Size";         e={        if ($_.length -lt  1000) {"{0:n1}"  -f $_.length.tostring () + " byte"}         elseif ($_.length -lt 1000000) {("{0:n1}"  -f  ($_.LENGTH/1KB)). ToString () + " kb"  }        else{("{0:n1}"  -f  ($_. LENGTH/1MB)). ToString ()  +  " MB"}         }         } | tee -variable file 



3. Save in time format, you can use Get-date-format YYYY. M.D to achieve. Notice when I export-csv. Specifies that the encoding format is Unicode, or the default asii format displays only question marks.


if ($file-eq $null) {write-warning "No file name dectected with Latin Character"} else{$name = (get-date-form at YYYY. M.D) + "Filenameswithdiacritics.csv" $file | Export-csv c:\temp\ $name-encoding Unicode}


4. Schedule tasks. There should be a bug here. I'm using WINDOWS10 and PowerShell 5, but when I create a trigger, I get an error that I can't find the corresponding command. After research, it is necessary to manually register the contents of the corresponding MOF files inside the WMI library.

Mofcomp that command is a manual registration command.

Mofcomp C:\Windows\System32\wbem\SchedProv.mof$action = New-scheduledtaskaction-execute ' Powershell.exe '-argument ' Get-diacritic.ps1 ' $trigger = new-scheduledtasktrigger-weekly-weeksinterval 2-daysofweek saturday-at 3amregister-scheduledtask-action $action-trigger $trigger-taskname "Latinname"-description "Weekly FileName scanning "


5. Send the file to the administrator


Note that I used the Office365 test, so the port is 587. I for the sake of convenience, the password is clear, better practice should be encrypted after the fingerprint (a bunch of garbled), copied into the script to use.

$from = "[email protected]" $to = "[email protected]" $SMTP = "smtp.office365.com" $sub = "file list" $body = "attached is The file list "$attach =" C:\scripts\file.csv "$secpasswd = convertto-securestring" Password "-asplaintext-force $mycreds = New-object System.Management.Automation.PSCredential ($from, $secpasswd) send-mailmessage-to $to-from $from-subject $sub-body $body-credential $mycreds-smtpserver $smtp-deliverynotificationoption never-bodyashtml-usessl-port 587-a Ttachments $attach


Finally, give a full version.


Get-diacritic.ps1

Function get-diacritic{    [cmdletbinding ()]         Param     (        # Param1  Help description        [parameter (                     Valuefrompipelinebypropertyname= $true,                    position=0)]         $Path = ". \ "    )     begin    {    }     Process    {             Get-ChildItem -Recurse -Path  $path |          where-object {$_.name -match  "[\u00c0-\u00ff]"} |         select name,  directory, creationtime, lastwritetime,        @{         n= "Size";         e={         if ($_.length -lt 1000) {"{0:n1}"  -f $_. Length.tostring () + " byte"}        elseif ($_.length -lt  1000000) {("{0:n1}"  -f  ($_.LENGTH/1KB)). ToString () + " kb"  }        else{("{0:n1}"  -f  ($_. LENGTH/1MB)). ToString ()  +  " MB"}         }         } | tee -Variable file          if ($file  -eq  $null) {write-warning  "No file name dectected with latin character "}         else{         $name = (get-date -format yyyy. M.D) + "Filenameswithdiacritics.csv"                   $file  | export-csv c:\temp\ $name  -Encoding Unicode}          $from  =  "[email protected]"           $to  =  "[email protected]"            $smtp  =  "smtp.office365.com"           $sub  =  "File list"                    $Body  =  $file  | ConvertTo-Html -Head  "scanning  Result " -as table | out-string         $attach = "C:\temp\" + $name           $secpasswd  = ConvertTo-SecureString  "Password"  -AsPlainText -Force           $mycreds  = New-Object  system.management.automation.pscredential  ($from,  $secpasswd)          Send-MailMessage -To  $to  -From  $from  -Subject  $sub  -body $ body -credential  $mycreds  -SmtpServer  $smtp  -deliverynotificationoption never  -BodyAsHtml -UseSsl -port 587 -Attachments  $attach     }     end    {    }}get-diacritic c:\users\yli\ Downloads


Scheduled Task scripts

Mofcomp C:\Windows\System32\wbem\SchedProv.mof$action = New-scheduledtaskaction-execute ' Powershell.exe '-argument ' Get-diacritic-path C:\users\yli\Downloads ' $trigger = New-scheduledtasktrigger-weekly-weeksinterval 2-daysofweek Saturday-at 3amregister-scheduledtask-action $action-trigger $trigger-taskname "Latinname"-description "Weekly FileN AME Scanning "


Run results

The following values are saved as CSV files

650) this.width=650; "src=" Http://s1.51cto.com/wyfs02/M01/7D/1F/wKioL1bgrASz2xnCAABWEX1eEGM083.png "style=" float: none; "title=" 2.PNG "alt=" Wkiol1bgrasz2xncaabwex1eegm083.png "/>


The saved file name

650) this.width=650; "src=" Http://s4.51cto.com/wyfs02/M02/7D/1F/wKioL1bgrTCCtVkfAAAaN8zpR-c913.png "title=" 5.PNG " alt= "Wkiol1bgrtcctvkfaaaan8zpr-c913.png"/>


Create a scheduled task


650) this.width=650; "src=" Http://s2.51cto.com/wyfs02/M02/7D/20/wKiom1bgrFzzJuP7AAAdqD8ZKuo939.png "title=" 4.PNG " alt= "Wkiom1bgrfzzjup7aaadqd8zkuo939.png"/>


Perform a scheduled task

Start-scheduledtask-taskname "Latinname"


Messages Received

650) this.width=650; "src=" Http://s3.51cto.com/wyfs02/M00/7D/20/wKiom1bgs93zp7EEAADAew_N-NM740.png "title=" 3.PNG " alt= "Wkiom1bgs93zp7eeaadaew_n-nm740.png"/>


This article is from the "Mapo Tofu" blog, please be sure to keep this source http://beanxyz.blog.51cto.com/5570417/1749412

Powershell Scripting Game-march 2016

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.