我需要支持多个数据库实例,因此我创建了一个“工厂”函数来将别名(Invoke-DbCmd
)分配给所需的函数/ cmdlet:
MySql(虚拟):
function Invoke-MySqlCmd {
param(
[string]$Query
)
write-debug "Invoke-MySqlCmd"
# add implementation
}
Oracle(虚拟):
function Invoke-OracleCmd {
param(
[string]$Query
)
write-host "Invoke-OracleCmd"
# add implementation
}
'工厂'功能:
function Register-DbCommand {
param(
[ValidateSet('com.oracle','com.microsoft','org.mysql')]
[string]$Namespace
)
# remove existing assignment
Remove-Item alias:\Invoke-DbCmd -ErrorAction SilentlyContinue
$cmd = $null
switch ($Namespace) {
com.microsoft {
write-debug "Invoke-SqlCmd"
$cmd = Get-Command Invoke-SqlCmd
}
com.oracle {
write-debug "Invoke-OracleCmd"
$cmd = Get-Item Function:Invoke-OracleCmd
}
org.mysql {
write-debug "Invoke-MySqlCmd"
$cmd = Get-Item Function:Invoke-MySqlCmd
}
}
# return reference to new alias
Set-Alias -Name Invoke-DbCmd -Value $cmd -PassThru
}
虽然看起来创建了别名:
PS> register-dbcommand -Namespace 'com.oracle'
CommandType Name Version Source
----------- ---- ------- ------
Alias Invoke-DbCmd
别名未列出:
PS> get-alias | ? {$_.Definition -like 'Invoke*'} | select displayname
DisplayName
-----------
?? -> Invoke-NullCoalescing
curl -> Invoke-WebRequest
icm -> Invoke-Command
iex -> Invoke-Expression
ihy -> Invoke-History
ii -> Invoke-Item
irm -> Invoke-RestMethod
iwmi -> Invoke-WmiMethod
iwr -> Invoke-WebRequest
pester -> Invoke-Pester
psake -> Invoke-psake
r -> Invoke-History
wget -> Invoke-WebRequest
尝试使用别名会产生异常:
PS> invoke-dbcmd
invoke-dbcmd : The term 'invoke-dbcmd' is not recognized as the name of a cmdlet, function, script file, or operable program. Check
the spelling of the name, or if a path was included, verify that the path is correct and try again.
At line:1 char:1
+ invoke-dbcmd
+ ~~~~~~~~~~~~
+ CategoryInfo : ObjectNotFound: (invoke-dbcmd:String) [], CommandNotFoundException
+ FullyQualifiedErrorId : CommandNotFoundException
我错过了什么?
答案 0 :(得分:1)
它很有意思似乎有用,但您可能应该使用-Force
,因为您先将其删除。您可以添加New-Alias -Scope Global
,然后也不会删除现有的。
根据您的评论,上述内容似乎无关,请尝试使用{{1}}在全局范围内进行设置。