gpt4 book ai didi

powershell - 在 Powershell 中实现装饰器模式

转载 作者:行者123 更新时间:2023-12-01 10:20:50 25 4
gpt4 key购买 nike

我有我的自定义函数 f,它运行一些东西然后调用预定义函数 Invoke-WebRequest

我想让 f 接受 Invoke-WebRequest 所做的所有参数,然后将这些参数传递给 Invoke-WebRequest

 f --UseBasicParsing -Uri https://google.com -UseBasicParsing  -Body @{'name'='user'} -ErrorOnAction Stop
# Some processing is made
# then, the following is executed
Invoke-WebRequest -Uri https://google.com -UseBasicParsing -Body @{'name'='user'} -ErrorOnAction Stop

有没有快速的方法来实现这个? (而不是在 f 中声明所有可能的参数)

最佳答案

虽然和不声明参数不一样,但是你可以通过生成代理命令来生成声明:

[System.Management.Automation.ProxyCommand]::Create((Get-Command Invoke-WebRequest))

结果看起来像这样:

[CmdletBinding(HelpUri='https://go.microsoft.com/fwlink/?LinkID=217035')]
param(
[switch]
${UseBasicParsing},

[Parameter(Mandatory=$true, Position=0)]
[ValidateNotNullOrEmpty()]
[uri]
${Uri},

[Microsoft.PowerShell.Commands.WebRequestSession]
${WebSession},

[Alias('SV')]
[string]
${SessionVariable},

[pscredential]
[System.Management.Automation.CredentialAttribute()]
${Credential},

[switch]
${UseDefaultCredentials},

[ValidateNotNullOrEmpty()]
[string]
${CertificateThumbprint},

[ValidateNotNull()]
[X509Certificate]
${Certificate},

[string]
${UserAgent},

[switch]
${DisableKeepAlive},

[ValidateRange(0, 2147483647)]
[int]
${TimeoutSec},

[System.Collections.IDictionary]
${Headers},

[ValidateRange(0, 2147483647)]
[int]
${MaximumRedirection},

[Microsoft.PowerShell.Commands.WebRequestMethod]
${Method},

[uri]
${Proxy},

[pscredential]
[System.Management.Automation.CredentialAttribute()]
${ProxyCredential},

[switch]
${ProxyUseDefaultCredentials},

[Parameter(ValueFromPipeline=$true)]
[System.Object]
${Body},

[string]
${ContentType},

[ValidateSet('chunked','compress','deflate','gzip','identity')]
[string]
${TransferEncoding},

[string]
${InFile},

[string]
${OutFile},

[switch]
${PassThru})

begin
{
try {
$outBuffer = $null
if ($PSBoundParameters.TryGetValue('OutBuffer', [ref]$outBuffer))
{
$PSBoundParameters['OutBuffer'] = 1
}
$wrappedCmd = $ExecutionContext.InvokeCommand.GetCommand('Microsoft.PowerShell.Utility\Invoke-WebRequest', [System.Management.Automation.CommandTypes]::Cmdlet)
$scriptCmd = {& $wrappedCmd @PSBoundParameters }
$steppablePipeline = $scriptCmd.GetSteppablePipeline($myInvocation.CommandOrigin)
$steppablePipeline.Begin($PSCmdlet)
} catch {
throw
}
}

process
{
try {
$steppablePipeline.Process($_)
} catch {
throw
}
}

end
{
try {
$steppablePipeline.End()
} catch {
throw
}
}
<#

.ForwardHelpTargetName Microsoft.PowerShell.Utility\Invoke-WebRequest
.ForwardHelpCategory Cmdlet

#>

关于powershell - 在 Powershell 中实现装饰器模式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52906216/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com