powershell函数 - cmdlet没有什么支持?
对于下面的这些cmdlet,我尝试使用 [cmdletbinding(supportsshouldprocess)]
line创建该函数,但不确定它是否有效。
如何修改脚本以支持 whatf
参数?
function Remove-License {
[CmdletBinding(SupportsShouldProcess)]
param ([String] $UserPrincipalName )
$AssignedLicense = (Get-MsolUser -UserPrincipalName $UserPrincipalName).licenses.AccountSkuId
$AssignedLicense |
ForEach-Object {
Write-Host "Removing $($UserPrincipalName) License $($AssignedLicense)..." -ForegroundColor Red
Set-MsolUserLicense -UserPrincipalName $upn -RemoveLicenses $_ -Verbose
}
}
Remove-License -UserPrincipalName '[email protected]' -WhatIf
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
补充 guiwhatsthat有用的答案,如果您想要您的功能支持以及
-confirm
,$ pscmdlet.shouldprocess
是您的工作方式。相反,如果您想要 SET-MSOLUSERLICENSE 要支持它,您需要创建一个 proxy命令 /proxy profxy /proxy profxy a围绕此cmdlet扩展其功能。
这些博客演示了如何做到:
解决某些问题以解决某些问题在您的代码上,您应该注意,
-removelicenses
将String []
作为输入,这意味着您可以将整个许可证的整个数组传递到删除作为参数。您可以使用 write-verbose 而不是
write-host
显示有关该功能正在执行的信息的信息(因为您的功能已经支持verbose
,这是合乎逻辑的)。另外,- Verbose
始终在set-msoluserlicense
上激活,如果使用您的函数的其他人不想看到冗长的消息,可能会感到困惑下面的示例)。您还可以使用
confirstImpact
设置为 high ,这样,该函数将始终要求在处理任何许可证删除的任何许可证-whatif 没有被使用。
-confirm:$ false
成为避免此类确认消息的替代方案。现在该函数支持将其输送到其他cmdlet,即:
To complement guiwhatsthat helpful answer, if you want your function to support Common Parameter including
-WhatIf
as well as-Confirm
,$PSCmdlet.ShouldProcess
is how you do it.If instead you want
Set-MsolUserLicense
to support it, you would need to create a proxy command / proxy function around this cmdlet to extend it's functionality.These blogs demonstrate how to do it:
To address some issues on your code, you should note that
-RemoveLicenses
takesstring[]
as input, this means you can pass the whole array of licenses to remove as argument.You could use
Write-Verbose
instead ofWrite-Host
to display information about what the function is doing (since your function already supports-Verbose
, this would be logical). Also,-Verbose
is being used always activated onSet-MsolUserLicense
which can be confusing if someone else using your function does not want to see verbose messages (this is addressed on the example below).You can also use
ConfirmImpact
set to High, this way the function will always ask for confirmation before processing any license removal assuming-WhatIf
was not being used.-Confirm:$false
becomes the alternative to avoid such confirmation messages.Now the function supports pipeline processing, you can process multiple users by piping it into other cmdlets, i.e.:
您可以使用$ pscmdlet.shouldprocess
ms文档:
You can use $PSCmdlet.ShouldProcess
MS Docs:
https://learn.microsoft.com/en-us/powershell/scripting/learn/deep-dives/everything-about-shouldprocess?view=powershell-7.2