如何使用#Requires
关键字检查特定的dll?这是我的代码,它要求文件Microsoft.Search.Interop.dll
与脚本位于同一文件夹中。
# Load DLL containing classes & interfaces
Add-Type -path "Microsoft.Search.Interop.dll"
# Provides methods for controlling the Search service. This
# interface manages settings and objects that affect the search engine
# across catalogs.
#
# https://msdn.microsoft.com/en-us/library/bb231485(v=vs.85).aspx
$sm = New-Object Microsoft.Search.Interop.CSearchManagerClass
# Retrieves a catalog by name and creates a new ISearchCatalogManager
# object for that catalog.
$catalog = $sm.GetCatalog("SystemIndex")
# Resets the underlying catalog by rebuilding the databases
# and performing a full indexing.
#
# https://msdn.microsoft.com/en-us/library/bb266414(v=vs.85).aspx
$catalog.Reset()
答案 0 :(得分:1)
如果您只想检查文件系统(即与脚本位于同一文件夹中)或GAC中是否存在特定程序集,那么测试程序集是否存在的简单函数就足够了。
该函数将接受带或不带路径的程序集名称。它测试脚本文件夹中的程序集(如果没有路径元素)。然后,如果指定了searchGAC
param,则在GAC中测试是否存在。如果它在任何地方找到程序集,它将加载它,否则,将抛出异常。
# requires function
function Get-Assembly ([string]$dllName, [switch]$searchGAC) {
if ($dllName.Split('\\').Count -eq 1) {
$dllName = Join-Path $PSScriptRoot $dllName
}
if (Test-Path $dllName -PathType Leaf) {
Add-Type -path $dllName
} else {
$found = $false
}
if (!$found -and $searchGAC) {
$dllName = ($dllName -split '\\')[-1]
$assembly = [appdomain]::CurrentDomain.GetAssemblies() | Select -ExpandProperty Modules | where {$_.Name -match $dllName}
if ($assembly) {
[void][System.Reflection.Assembly]::Load($assembly.Assembly.FullName)
$found = $true
}
}
if (!$found) {
throw [System.IO.FileNotFoundException] "$dllName not found."
}
}
Set-Alias -Name Requires -Value Get-Assembly -Force
# your code from here, with the requires added in
# Load DLL containing classes & interfaces
Requires -dllName 'Microsoft.Search.Interop.dll' -searchGAC
# Provides methods for controlling the Search service. This
# interface manages settings and objects that affect the search engine
# across catalogs.
#
# https://msdn.microsoft.com/en-us/library/bb231485(v=vs.85).aspx
$sm = New-Object Microsoft.Search.Interop.CSearchManagerClass
# Retrieves a catalog by name and creates a new ISearchCatalogManager
# object for that catalog.
$catalog = $sm.GetCatalog("SystemIndex")
# Resets the underlying catalog by rebuilding the databases
# and performing a full indexing.
#
# https://msdn.microsoft.com/en-us/library/bb266414(v=vs.85).aspx
$catalog.Reset()