首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Powershell -在函数中执行命令之前进行确认

Powershell -在函数中执行命令之前进行确认
EN

Stack Overflow用户
提问于 2022-07-16 11:54:49
回答 2查看 151关注 0票数 3

我在我的powershell配置文件中添加了以下函数(来自echo $profile的路径,我的类似于D:\C_Drive\Hardlink\Documents\WindowsPowerShell\Microsoft.PowerShell_profile.ps1)

代码语言:javascript
复制
function test {
    [cmdletbinding(SupportsShouldProcess)]
    ls
}
Set-Alias ggg test

使用[cmdletbinding(SupportsShouldProcess)]提示确认,但在运行ggg时会出现以下错误

代码语言:javascript
复制
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

在函数中执行命令之前,正确的确认方法是什么?

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2022-07-16 12:27:22

试试这个:

代码语言:javascript
复制
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/

票数 2
EN

Stack Overflow用户

发布于 2022-07-16 14:27:29

使用SupportsShouldProcess是正确的,但是它缺少了ConfirmImpact。通过这种方式,您可以定义您的函数是高风险函数,和PowerShell总是要求确认。这也是由您的偏好变量决定的,默认情况下,它被设置为High

高:在运行高风险的cmdlet或函数之前,PowerShell提示进行确认。

例如,如果首选项变量设置为None,PowerShell将不再要求您确认操作。

代码语言:javascript
复制
function test {
    [cmdletbinding(SupportsShouldProcess, ConfirmImpact = 'High')]
    param([string] $myParam)

    if($PSCmdlet.ShouldProcess([string] $myParam)) {
        Get-ChildItem $myParam
    }
}

那么,如果我们试图调用该函数:

代码语言:javascript
复制
PS /> test C:\

将出现以下确认提示:

代码语言:javascript
复制
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 必须调用来提示确认。

代码语言:javascript
复制
function test {
    [cmdletbinding()]
    param()

}
票数 6
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/73003971

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档