14
对于像-WhatIf这样的事物,我们通过[CmdletBinding]属性给我们$ PSCmdlet.ShouldProcess()。是否有其他用于实现常见命令行参数的工具或实践,如-Verbose,-Debug,-PassThru等?Powershell:如何实现标准交换机?
对于像-WhatIf这样的事物,我们通过[CmdletBinding]属性给我们$ PSCmdlet.ShouldProcess()。是否有其他用于实现常见命令行参数的工具或实践,如-Verbose,-Debug,-PassThru等?Powershell:如何实现标准交换机?
Write-Debug
和Write-Verbose
自动处理-Debug
和-Verbose
参数。
-PassThru
在技术上不是常见的参数,但你可以实现它想:
function PassTest {
param(
[switch] $PassThru
)
process {
if($PassThru) {$_}
}
}
1..10|PassTest -PassThru
这是使用某个cmdlet的函数的PASSThru价值的例子:
function Add-ScriptProperty {
param(
[string] $Name,
[ScriptBlock] $Value,
[switch] $PassThru
)
process{
# Use ":" to explicitly set the value on a switch parameter
$_| Add-Member -MemberType ScriptProperty -Name $Name -Value $Value `
-PassThru:$PassThru
}
}
$calc = Start-Process calc -PassThru|
Add-ScriptProperty -Name SecondsOld `
-Value {((Get-Date)-$this.StartTime).TotalSeconds} -PassThru
sleep 5
$calc.SecondsOld
有无看看Get-Help about_CommonParameters
了解更多信息。
我想你可能想要存储输入变量,做一些然后通过存储的变量在最后(如果$ passthru)。 – Matt
是的,'PassTest'不是一个有用的功能;只是一个简单的例子来说明如何实现'-PassThru'。另外,你也可能会对输入变量做些什么,但是可以通过原来的值不变(例如'$ _。Kill(); if($ PassThru){$ _}')。我添加了一个使用PassThru参数设置另一个命令的PassThru的非trival示例。 – Rynant