Startsidan  ▸  Texter  ▸  Teknikblogg

Anders Hesselbom

Programmerare, skeptiker, sekulärhumanist, antirasist.
Författare till bok om C64 och senbliven lantis.
Röstar pirat.

Piping objects

2011-06-29

If you want to create and run a ps1 script, make sure to give yourself the permission to execute scripts. If you are running a newer operating system, you must start PowerShell as an administrator the time that you grant yourself the right to run scripts.

When you type DIR, a list of DirectoryInfo and/or FileInfo objects are created and sent to the script host. Each object, no matter type, are displayed as strings, meaning that the directory name or file name is displayed. How ever, you can use the pipeline to access actual objects. I have some directories and a few files in my C root, so if I pipe the output from the DIR command to an iteration that displays the object’s type name, like so:

DIR C:\ | ForEach-Object { Write-Host $_.GetType().Name }

From that I will get the word DirectoryInfo for each directory and the word FileInfo for each file in my C root. These are the .NET classes that represent directories and files. Since the PowerShell pipeline actually is handling objects, you can use these objects by accessing the properties or calling the functions of each object. A simple task such as displaying the number of files in each directory, is a walk in the park, when the actual object you need to do this, already is in the pipeline.

DIR C:\ | ForEach-Object {
If ($_.GetType().Name -like "DirectoryInfo")
   {
      Write-Host $_.Name "(" $_.GetDirectories().Length
         " dirs and " $_.GetFiles().Length " files.)"
   }
}

The output for this, is the name of the directory and the number of child directories and files that it holds. I can see that my Windows folder holds 66 directories and 45 files.

Categories: PowerShell

Leave a Reply

Your email address will not be published. Required fields are marked *



En kopp kaffe!

Bjud mig på en kopp kaffe (20:-) som tack för bra innehåll!

Bjud på en kopp kaffe!

Om...

Kontaktuppgifter, med mera, finns här.

Följ mig

Twitter Instagram
GitHub RSS

Public Service

Folkbildning om public service.

Hem   |   linktr.ee/hesselbom   |   winsoft.se   |   80tal.se   |   Filmtips