又到了 PowerShell 練習時間。今天的題目是 - 如何在 PowerShell 引用 C# DLL?

借用上一篇介紹的 DotNetZip 當例子,我打算用 PowerShell 動態建立加密 ZIP 檔。

準備 PowerShell 腳本 Test.ps1 如下,並將 DotNetZip.dll 複製到同一資料夾:

Add-Type -Path .\DotNetZip.dll
$zip = New-Object Ionic.Zip.ZipFile
$zip.Password = "12345678"
$zip.AddEntry("files\test.txt", "Hello World!") | Out-Null
$zip.Save("$(pwd)\test.zip")
$zip.Dispose()

原理是先使用 Add-Type -Path DLL完整路徑 載入第三方或自製 .NET 組件,New-Object Ionic.Zip.ZipFile 相當於 C# 的 new Ionic.Zip.ZipFile(),後面操作與 C# 寫法大同小異。但這裡有個小眉角,若寫成 $zip.Save(".\test.zip"),.\ 會指向 C:\Users\userName 資料夾(%UserProfile%) 而非當下路徑,故我改用 "$(pwd)\test.zip" 取代。

執行成功,加密 ZIP 檔 GET!

再來一個練習,這回我要用 .NET 內建程式庫連上 SQL 執行 SELECT GETDATE() 取得現在時間。

Add-Type -AssemblyName "System.Data"
$cn = New-Object System.Data.SqlClient.SqlConnection
$cn.ConnectionString = "Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=X:\Lab\TestEF\TestExecStoreQry\TestDB.mdf;Integrated Security=True;Connect Timeout=30"
try {
    $cn.Open()
    $cmd = $cn.CreateCommand()
	$cmd.CommandText = "SELECT GETDATE()"
    $dr = $cmd.ExecuteReader()
    $dr.Read()
    $dr[0].ToString("yyyy-MM-dd HH:mm:ss.fff")
}
finally {
    if ($null -ne $cn) {
        $cn.Dispose()
    }
}

跟先前做法差不多,但由於 System.Data.SqlClient 命名空間隸屬 System.Data.dll 位於 GAC,故寫成 Add-Type -AssemblyName "System.Data" 即可載入,另外我還加了 try ... finally 模擬 using。執行成功!

練習完畢。

Example of using PowerShell to call 3rd-party or custom .NET library.


Comments

Be the first to post a comment

Post a comment