我正在寻找在PowerShell 中实现 PowerShell 提供程序。
我一直在想,如果我只是定义类型,然后将它们导入我的会话(导入模块),我应该能够让它们可用。
例如,这不起作用,但它沿着我想要实现的路径。
我显然错过了很多......有人知道这是否可能吗?
# EnvironmentProvider.ps1
$reference_assemblies = (
"System.Management.Automation, Version=1.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
# "System.Configuration.Install, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"
)
$source = @"
namespace Providers
{
using System.Management.Automation;
using System.Management.Automation.Provider;
[CmdletProvider("Environments", ProviderCapabilities.None)]
public class EnvironmentProvider : DriveCmdletProvider
{
protected override PSDriveInfo NewDrive(PSDriveInfo drive)
{
return new EnvironmentDriveInfo(drive);
}
protected override object NewDriveDynamicParameters()
{
return base.NewDriveDynamicParameters();
}
}
public class EnvironmentDriveInfo : PSDriveInfo
{
public EnvironmentDriveInfo(PSDriveInfo driveInfo) : base(driveInfo)
{
}
}
}
"@
# -ea silentlycontinue in case its already loaded
#
add-type -referencedassemblies $referenced_assemblies -typedefinition $source -language CSharp -erroraction silentlycontinue
导入模块后,我尝试创建驱动器“环境”:
new-psdrive -psprovider Environments -name "Environments" -root ""
错误:
New-PSDrive : Cannot find a provider with the name 'Environments'.
假设提供者实际工作,也许让它返回一个环境列表:dev、qa、staging、production。
然后我希望能够通过以下方式重新使用它:
c:\adminlib>import-module .\EnvironmentProvider.ps1
c:\adminlib>environments:
environments:>ls
dev
qa
staging
production
environments:> cd production
environments\production> [execute actions against production]
environments\production:> cd dev
environments\dev:> [execute actions against dev, etc]