简体   繁体   English

从 C# PowerShell cmdlet 返回退出代码

[英]Returning an exit code from C# PowerShell cmdlet

I am writing a PowerShell cmdlet in C# and this cmdlet is called by a parent process that I have no control over.我正在用 C# 编写一个 PowerShell cmdlet,这个 cmdlet 由我无法控制的父进程调用。 The parent process has mechanisms in place to handle persistent reboots from the cmdlet if the exit code of the process is 3010. The problem here is that I cannot figure out how to provide a value for the exit code given that the entry point into the cmdlet is:如果进程的退出代码是 3010,则父进程具有处理从 cmdlet 持续重启的机制。这里的问题是,鉴于进入 cmdlet 的入口点,我无法弄清楚如何为退出代码提供值是:

protected override void ProcessRecord() { ... }

I have read that cmdlets do not generate an exit code when researching the $LASTEXITCODE PS variable.我读到 cmdlet 在研究$LASTEXITCODE PS 变量时不会生成退出代码。 I'm fairly new to PowerShell in general so I am not sure if I am going about this the right way.总的来说,我对 PowerShell 还是很陌生,所以我不确定我是否以正确的方式来解决这个问题。 Does anyone have a way that I can accomplish what I have described?有没有人有办法完成我所描述的事情?

The cmdlet gets loaded and called by a PS script something like cmdlet 被 PS 脚本加载并调用,例如

Import-Module "C:\testing\test.dll"
Run-MyCmdlet

Are looking for a way to determine if the module loaded or for your cmdlet to indicate it failed?是否正在寻找一种方法来确定模块是否已加载或让您的 cmdlet 指示它失败?

To determine if the module loaded or failed look at the $ErrorActionPreference variable.要确定模块是否加载或失败,请查看$ErrorActionPreference变量。 ( https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_preference_variables?view=powershell-7.2#erroractionpreference ) https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_preference_variables?view=powershell-7.2#erroractionpreference

If you want your cmdlet to report a terminating error look at Cmdlet.ThrowTerminatingError(ErrorRecord) method.如果您希望 cmdlet 报告终止错误,请查看Cmdlet.ThrowTerminatingError(ErrorRecord)方法。 ( https://docs.microsoft.com/en-us/dotnet/api/system.management.automation.cmdlet.throwterminatingerror?view=powershellsdk-7.0.0 ) https://docs.microsoft.com/en-us/dotnet/api/system.management.automation.cmdlet.throwterminationerror?view=powershellsdk-7.0.0

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM