我在我的powershell配置文件中添加了以下函数(来自echo $profile的路径,我的类似于D:\C_Drive\Hardlink\Documents\WindowsPowerShell\Microsoft.PowerShell_profile.ps1)
function test {
[cmdletbinding(SupportsShouldProcess)]
ls
}
Set-Alias ggg test使用[cmdletbinding(SupportsShouldProcess)]提示确认,但在运行ggg时会出现以下错误
At D:\C_Drive\Hardlink\Documents\WindowsPowerShell\Microsoft.PowerShell_profile.ps1:2 char:5
+ [cmdletbinding(SupportsShouldProcess)]
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Unexpected attribute 'cmdletbinding'.
At D:\C_Drive\Hardlink\Documents\WindowsPowerShell\Microsoft.PowerShell_profile.ps1:3 char:5
+ ls
+ ~~
Unexpected token 'ls' in expression or statement.
+ CategoryInfo : ParserError: (:) [], ParseException
+ FullyQualifiedErrorId : UnexpectedAttribute在函数中执行命令之前,正确的确认方法是什么?
发布于 2022-07-16 12:27:22
试试这个:
function test {
$confirmation = Read-Host "Do you want to continue? [y to continue] "
if ($confirmation -eq 'y') {
ls
}
}
Set-Alias ggg test更多信息见此处:https://www.delftstack.com/howto/powershell/powershell-yes-no-prompt/
发布于 2022-07-16 14:27:29
使用SupportsShouldProcess是正确的,但是它缺少了ConfirmImpact和高。通过这种方式,您可以定义您的函数是高风险函数,和PowerShell总是要求确认。这也是由您的偏好变量决定的,默认情况下,它被设置为High
高:在运行高风险的cmdlet或函数之前,PowerShell提示进行确认。
例如,如果首选项变量设置为None,PowerShell将不再要求您确认操作。
function test {
[cmdletbinding(SupportsShouldProcess, ConfirmImpact = 'High')]
param([string] $myParam)
if($PSCmdlet.ShouldProcess([string] $myParam)) {
Get-ChildItem $myParam
}
}那么,如果我们试图调用该函数:
PS /> test C:\将出现以下确认提示:
Are you sure you want to perform this action?
Performing the operation "test" on target "C:\".
[Y] Yes [A] Yes to All [N] No [L] No to All [S] Suspend [?] Help (default is "Y"):最后,Cmdlet.ShouldProcess有许多过载,它们提供了一种更详细的请求确认的方式。目前在test函数上使用的方法是最简单的。
至于您在尝试运行函数时所看到的错误,这是因为该函数有一个属性声明来表示您的函数和高级功能,但是它缺少一个区块,即使该函数没有任何应该存在的参数。此外,SupportsShouldProcess 必须调用来提示确认。
function test {
[cmdletbinding()]
param()
}https://stackoverflow.com/questions/73003971
复制相似问题