Implementation code for filtering by file suffix in PowerShell _powershell

Source: Internet
Author: User

Small knitting in the use of PowerShell, often use Get-childitem (alias dir), to get some files or directories. The results are then filtered by file type, or file suffix. Many times such a work to do down, small make up feel vexed, there is no simple, once and for all method? We'll discuss it today.

No suspense, first give a filter code, we first look at:

Copy Code code as follows:

Filter where-extension
{
Param
(
[string[]]
$extension = ('. png ', '. jpg ', '. gif ')
)

$_ |
Where-object {
$extension-contains $_. Extension
}
}

What is filter, so to speak, is similar to the function, but is placed behind the pipe. So you'll see "$_ |" Inside the filter. Such a token. This filter requires passing in an array parameter, which is the suffix list. If you do not pass, then filter by default. png,.jpg and. gif.
Okay, let's see how it's used.

I want to filter all of the TXT or. log text files in the D-packing directory, PowerShell script writes:

Copy Code code as follows:

Dir d:\ | Where-extension. Txt,.log

You can make up with the small, put this filter into the profile inside, so that each call is no longer defined and directly used. Ah? You don't know what profile is? Then go and see this article.

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.