LoginSignup
9
7

More than 5 years have passed since last update.

powershellのusing(import,include) 名前空間省略方法のメモ

Last updated at Posted at 2014-11-26

PowershellにC#で言うところのusing(javaのimport,cのinclude)がない、と思っているのではないかというコードが多いのでメモ

まず、New-Objectにtypeオブジェクトだけでなく、文字列が指定できるので、名前空間文字列を先頭行で宣言して、newするときに使う方法

PS C:\Temp> $List="System.Collections.Generic.List"
PS C:\Temp> $a=New-Object "$List[Int]"
PS C:\Temp> $a.GetType()

IsPublic IsSerial Name                                     BaseType
-------- -------- ----                                     --------
True     True     List`1                                   System.Object

staticメソッド・プロパティを使う場合はtype型にキャストした変数をポインタにできるみたいなんですけど、
名前空間は文字列型にして、個別のクラスはtypeにキャストするのが使い勝手がいいのかな、と思いました。

PS C:\temp> $excel="Microsoft.Office.Interop.Excel"
PS C:\temp> [Reflection.Assembly]::LoadWithPartialName($excel)

GAC    Version        Location
---    -------        --------
True   v2.0.50727     C:\Windows\assembly\GAC_MSIL\Microsoft.Office.Interop.Excel\15.0.0.0__71e9bce111e9429c\Microso...


PS C:\temp> $xlFixedFormatType="$excel.XlFixedFormatType" -as [type]
PS C:\temp> $xlFixedFormatType::xlTypePDF
xlTypePDF
PS C:\temp> $xlFixedFormatType::xlTypePDF.GetType()

IsPublic IsSerial Name                                     BaseType
-------- -------- ----                                     --------
True     True     XlFixedFormatType                        System.Enum

参考
ExcelファイルからPDFファイルやXPSファイルを作成する
http://blog.powershell-from.jp/?p=965

2016/4/5
Powershell5.0で正式な名前空間省略の文法ができたみたいです

PowerShell 5.0 で搭載された using namespace シンタックスの概要
http://tech.guitarrapc.com/entry/2015/08/30/082605

9
7
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
9
7