![](/img/trans.png)
[英]How to create PowerShell datastructure that works well with format-table
[英]How do I create an alias to Format-Table in Powershell?
假设我有一个Powershell Format-Table
字符串,例如:
ls | Format-Table Name, @{expression={$_.Length / 1024}; label='KB'}
我对从中获得的输出感到满意,但是我不想每次使用它时都键入它。 我希望能够通过一个简单的单字命令调用它,例如:
ls | Format-KiloBytes
我想我应该为此定义一个函数,因为别名不能指定参数。 但是,如果我定义如下内容:
function kilobytes {format-table Name, @{expression={$_.Length / 1024}; label='KB'}}
则没有任何效果:
PS> ls | format-table Name, @{expression={$_.Length / 1024}; label='KB'}
... Produces the formatted output
PS> ls | kilobytes
... Produces output with unchanged formatting, the same as 'ls'
编辑:看来我很困惑。 在进行实验时,我已经创建了一个别名kilobytes
,该别名被别名为Format-Table
。 我忘记了这一点,但这意味着创建函数kilobytes
成功而没有任何警告,但是随后调用kilobytes
不是调用新创建的函数而是现有的别名。
首先,您可以尝试:
function kilobytes {$input | format-table Name, @{expression={$_.Length / 1024}; label='KB'}}
您可以在about_Functions中找到$input
的说明。 在管道中使用函数时,通过管道传递给该函数的对象将分配给$ input自动变量。
这是有效的过滤器版本:
filter kilobytes {$_ | select Name,@{expression={$_.Length / 1024}; label='KB'}}
要么:
filter kilobytes {[PSCustomObject]@{Name=$_.name;KB=$_.length/1024}}
代理功能提供了一种绑定一个或多个参数的好方法,同时仍然以自然的方式支持原始命令。 在Bing上搜索“ powershell代理功能”将提供许多详细信息。
以下是完全满足您需要的代理功能。 您可以看到仍然具有Format-Table参数,如-AutoSize,但没有-Property参数,因为该参数已经过硬编码。
此代理的更智能版本实际上可能支持向硬编码的属性添加其他属性。
function Format-Kilobytes
{
[CmdletBinding(HelpUri='http://go.microsoft.com/fwlink/?LinkID=113303')]
param(
[switch]${AutoSize},
[switch]${HideTableHeaders},
[switch]${Wrap},
[System.Object]${GroupBy},
[string]${View},
[switch]${ShowError},
[switch]${DisplayError},
[switch]${Force},
[ValidateSet('CoreOnly','EnumOnly','Both')]
[string]${Expand},
[Parameter(ValueFromPipeline=$true)]
[psobject]${InputObject})
begin
{
try {
$wrappedCmd = $ExecutionContext.InvokeCommand.GetCommand('Format-Table',
[System.Management.Automation.CommandTypes]::Cmdlet)
$properties = "Name",@{expression={$_.Length / 1024}; label='KB'}
$scriptCmd = {& $wrappedCmd @PSBoundParameters -Property $properties }
$steppablePipeline = $scriptCmd.GetSteppablePipeline($myInvocation.CommandOrigin)
$steppablePipeline.Begin($PSCmdlet)
} catch {
throw
}
}
process { try { $steppablePipeline.Process($_) } catch { throw } }
end { try { $steppablePipeline.End() } catch { throw } }
<#
.ForwardHelpTargetName Format-Table
.ForwardHelpCategory Cmdlet
#>
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.