You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何让返回PSCustomObject的PowerShell函数支持属性自动补全?

实现PowerShell函数返回对象的属性自动补全

我编写了名为Get-FilePathComponents的PowerShell函数,用于拆分文件路径组件,返回带有指定命名属性的PSCustomObject。为实现该返回对象属性的自动补全功能,我曾尝试通过自定义types.ps1xml文件并为函数添加[OutputType('VSYSFileOps.Object.FilePathComponents')]的方式,但该方法不符合ps1xml的设计用途。最终通过定义C#类并在函数中添加[OutputType("FilePathComponents")]的方案,成功在VSCode中实现了IntelliSense和TAB补全。

原函数代码

function Get-FilePathComponents {

    [CmdletBinding()]
    param (
        [Parameter(Mandatory,Position=0,ValueFromPipeline)]
        [String[]]
        $Path
    )

    begin {}

    process {

        foreach ($P in $Path) {
            [PSCustomObject]@{
                ContainingFolder     = Split-Path $P -Parent
                FileBaseName         = Split-Path $P -LeafBase
                FileFullName         = Split-Path $P -Leaf
                FileExtension        = Split-Path $P -Extension
                FullPathNoExtension  = [IO.Path]::Combine((Split-Path $P -Parent),(Split-Path $P -LeafBase))
                CompletePath         = $P
                ParentFolder         = Split-Path (Split-Path $P -Parent) -Parent
            }
        }
    }
}

尝试的types.ps1xml代码片段

<Types>
<Type>
<Name>VSYSFileOps.Object.FilePathComponents</Name>

<ScriptProperty>
   <Name>ContainingFolder</Name>
   <GetScriptBlock>
      $this.ContainingFolder
   </GetScriptBlock>
</ScriptProperty>
... Etc...

最终解决方案代码

$FilePathComponents = @'
public class FilePathComponents
{
    public string ContainingFolder { get;set; }
    public string FileBaseName { get;set; }
    public string FileFullName { get;set; }
    public string FileExtension { get;set; }
    public string FullPathNoExtension { get;set; }
    public string CompletePath { get;set; }
    public string ParentFolder { get;set; }
}
'@

Add-Type -TypeDefinition $FilePathComponents -Language CSharp

function Get-FilePathComponents {

    [OutputType("FilePathComponents")]

    [CmdletBinding()]
    param (
        [Parameter(Mandatory,Position=0,ValueFromPipeline)]
        [String[]]
        $Path
    )

    begin {}

    process {
        foreach ($P in $Path) {
            $obj = [FilePathComponents]::new()
            $obj.ContainingFolder     = Split-Path $P -Parent
            $obj.FileBaseName         = Split-Path $P -LeafBase
            $obj.FileFullName         = Split-Path $P -Leaf
            $obj.FileExtension        = Split-Path $P -Extension
            $obj.FullPathNoExtension  = [IO.Path]::Combine((Split-Path $P -Parent),(Split-Path $P -LeafBase))
            $obj.CompletePath         = $P
            $obj.ParentFolder         = Split-Path (Split-Path $P -Parent) -Parent
            $obj
        }
    }
}

内容的提问来源于stack exchange,提问作者fmotion1

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.23 04:36:17