2014-09-02 118 views
4

我想創建一個PowerShell提供程序,它將像目錄結構一樣工作。 根是一個返回文本文件的網址。這個文件有一個項目列表。當這些項目中的每一個都附加到原始Web地址的末尾時,我會得到另一個包含另一個項目列表的文件。這將遞歸直到文件不返回任何項目。所以結構是這樣的:自定義PowerShell提供程序實現

root: 1.2.3.4/test/  -> returns file0 
file0: item1, item2, item3 

1.2.3.4/test/item1  -> returns file1 
1.2.3.4/test/item2  -> returns file2 
1.2.3.4/test/item3  -> returns file3 

file1: item4, item5 
file2: item6 
file3: <empty> 

因爲我想創建一個類似結構的導航,我延長了NavigationCmdletProvider

public class TESTProvider : NavigationCmdletProvider 

我能夠創建新PSDrive來如下:

PS c:\> New-PSDrive -Name dr1 -PSProvider TestProvider -Root http://1.2.3.4/v1 

Name   Used (GB)  Free (GB) Provider  Root           CurrentLocation 
----   ---------  --------- --------  ------------------- 
dr1         TestProvider http://1.2.3.4/v1 

但是,當我'cd'到該驅動器時,出現錯誤:

PS c:\> cd dr1: 

cd : Cannot find path 'dr1:\' because it does not exist. 
At line:1 char:1 
+ cd dr1: 
+ ~~~~~~~~ 
    + CategoryInfo   : ObjectNotFound: (dr1:\:String) [Set-Location], ItemNotFoundException 
    + FullyQualifiedErrorId : PathNotFound,Microsoft.PowerShell.Commands.SetLocationCommand 

我需要使用什麼方法來實現/覆蓋以顯示提示信息:PS dr1:>當我執行cd dr1時:? (在此之後我明白,我將不得不重寫GetChildItems(string path, bool recurse)得到項目1,項目2,項目3列出)。

+1

這不完全是您的問題的答案,但您應該查看https://github.com/beefarino/p2f/或https://github.com/beefarino/simplex - 他們都使構建提供者變得更簡單。 – 2014-09-02 22:04:19

回答

3

我發現,實施IsValidPathItemExistsIsItemContainerGetChildren讓你到工作狀態。這是我通常從我實施導航提供商時開始的:

[CmdletProvider("MyPowerShellProvider", ProviderCapabilities.None)] 
public class MyPowerShellProvider : NavigationCmdletProvider 
{ 

    protected override bool IsValidPath(string path) 
    { 
     return true; 
    } 

    protected override Collection<PSDriveInfo> InitializeDefaultDrives() 
    { 
     PSDriveInfo drive = new PSDriveInfo("MyDrive", this.ProviderInfo, "", "", null); 
     Collection<PSDriveInfo> drives = new Collection<PSDriveInfo>() {drive}; 
     return drives; 
    } 

    protected override bool ItemExists(string path) 
    { 
     return true; 
    } 

    protected override bool IsItemContainer(string path) 
    { 
     return true; 
    } 

    protected override void GetChildItems(string path, bool recurse) 
    { 
     WriteItemObject("Hello", "Hello", true); 
    } 
} 
相關問題