Windows PowerShell Cookbook 2013 by Unknown

Windows PowerShell Cookbook 2013 by Unknown

Author:Unknown
Language: eng
Format: epub


Discussion

You can access many simple Windows APIs using the script given in Recipe 17.5 . This approach is difficult for more complex APIs, however.

In PowerShell version one, it was possible to access these APIs in one of two ways: by generating a dynamic assembly on the fly (you wouldn’t really do this for one-off calls, but Recipe 17.5 uses this technique) or by looking up the P/Invoke definition for that API call and compiling the C# to access it.

These are both good approaches, but PowerShell version two introduces the Add-Type cmdlet to make this much easier.

Add-Type offers four basic modes of operation:

PS > Get-Command Add-Type | Select -Expand ParameterSets | Select Name

----

FromSource

FromMember

FromPath

FromAssemblyName

These modes of operation are:

FromSource

Compile some C# (or other language) code that completely defines a type. This is useful when you want to define an entire class, its methods, namespace, etc. You supply the actual code as the value to the -TypeDefinition parameter, usually through a variable. For more information about this technique, see Recipe 17.6 .

FromPath

Compile from a file on disk, or load the types from an assembly at that location. For more information about this technique, see Recipe 17.8 .

FromAssemblyName

Load an assembly from the .NET Global Assembly Cache (GAC) by its shorter name. This is not the same as the [Reflection.Assembly]::LoadWithPartialName method, since that method introduces your script to many subtle breaking changes. Instead, PowerShell maintains a large mapping table that converts the shorter name you type into a strongly named assembly reference. For more information about this technique, see Recipe 17.8 .

FromMember

Generates a type out of a member definition (or a set of them). For example, if you specify only a method definition, PowerShell automatically generates the wrapper class for you. This parameter set is explicitly designed to easily support P/Invoke calls.

Now, how do you use the FromMember parameter set to call a Windows API? The solution shows the end result of this process, but let’s take it step-by-step. First, imagine that you want to access sections of an INI file.

PowerShell doesn’t have a native way to manage INI files, and neither does the .NET Framework. However, the Windows API does, through a call to the function called GetPrivateProfileString . The .NET framework lets you access Windows functions through a technique called P/Invoke (Platform Invocation Services). Most calls boil down to a simple P/Invoke definition , which usually takes a lot of trial and error. How-ever, a great community has grown around these definitions, resulting in an enormous resource called P/Invoke .NET ( http://www.pinvoke.net/ ). The .NET Framework team also supports a tool called the P/Invoke Interop Assistant that generates these defini-tions as well, but we won’t consider that for now.

First, we’ll create a script called Get-PrivateProfileString.ps1 . It’s a template for now: ## Get-PrivateProfileString.ps1

param(

$Path,

$Category,

$Key)

$null

To start fleshing this out, we visit P/Invoke .NET and search for GetPrivateProfile String , as shown in Figure 17-1 .



Download



Copyright Disclaimer:
This site does not store any files on its server. We only index and link to content provided by other sites. Please contact the content providers to delete copyright contents if any and email us, we'll remove relevant links or contents immediately.
Popular ebooks
Eco-friendly approach of bio-indigo synthesis and developing purification methods towards isolation of indigo from indirubin and bacterial fragments by Ramalingam Manivannan & Kaliyan Prabakaran & Young-A Son(210886)
Personalized inhaled bacteriophage therapy for treatment of multidrug-resistant Pseudomonas aeruginosa in cystic fibrosis by unknow(179251)
CONSORT 2025 statement: updated guideline for reporting randomized trials by unknow(87772)
Critical evaluation of the ProfiLER-02 study design and outcomes by Vivek Subbiah & Razelle Kurzrock(87363)
Cardiac gene therapy makes a comeback by Oliver J. Müller & Susanne Hille & Anca Kliesow Remes(87142)
Whisky: Malt Whiskies of Scotland (Collins Little Books) by dominic roskrow(74447)
Unveiling the design rules for tunable emission in graphene quantum dots: A high-throughput TDDFT and machine learning perspective by Şener Özönder & Mustafa Coşkun Özdemir & Caner Ünlü(50898)
A yeast-based oral therapeutic delivers immune checkpoint inhibitors to reduce intestinal tumor burden by unknow(40267)
Covalent hitchhikers guide proteins to the nucleus by Alexander F. Russell & Madeline F. Currie & Champak Chatterjee(40218)
Meet the Authors: Christopher R. Mansfield and Emily R. Derbyshire by Christopher R. Mansfield & Emily R. Derbyshire(40100)
Alkaline-earth metals promote propane dehydrogenation with carbon dioxide through geometric effects: Altering the reaction pathway by unknow(32736)
Induced iron vacancies boosting FeOOH loaded on sustainable Fenton-like collagen fiber membrane for efficient removal of emerging contaminants by unknow(32514)
Efficient electric-field-assisted photochemical conversion of methane to n-propanol exclusively over penetrated TiO2Ti hollow fibers by Guanghui Feng(32458)
Bi2SiO5 nanosheets as piezo-photocatalyst for efficient degradation of 2,4-Dichlorophenol by Hangyu Shi & Yifu Li & Lishan Zhang & Guoguan Liu & Qian Zhang & Xuan Ru & Shan Zhong(32394)
A novel NDIPTA organic heterojunction photocatalyst with built-in electric field for efficient hydrogen production by Jiahui Yang & Baojun Ma & Yongfa Zhu(32368)
Enhanced conversion of methane to liquid-phase oxygenates via hollow ferrite nanotube@horseradish peroxidase based photoenzymatic catalysis by Jun Duan & Shiying Fan & Xinyong Li & Shaomin Liu(32334)
Ordered macroporous superstructure of defective carbon adorned with tiny cobalt sulfide for selective electrocatalytic hydrogenation of cinnamaldehyde by Xiao-Shi Yuan & Sheng-Hua Zhou & San-Mei Wang & Wenbo Wei & Xiaofang Li & Xin-Tao Wu & Qi-Long Zhu(32261)
What's Done in Darkness by Kayla Perrin(27154)
Topological analysis of non-conjugated ethylene oxide cored dendrimers decorated with tetraphenylethylene: Insights from degree-based descriptors using the polynomial approach by A Theertha Nair & D Antony Xavier & Annmaria Baby & S Akhila(26535)
Investigation of mechanical and self-healing properties of hydroxyl-terminated polybutadiene functionalized with 2-ureido-4-pyrimidinone by Mohsen Kazazi & Mehran Hayaty & Ali Mousaviazar(26461)