2016-10-26 54 views
1

如果尝试在ineracvie powershell中做些事情,是否有可能捕获一个错误? 我的意思是:在交互PowerShell中捕获错误

powershell.exe 
PS C:>_ 
PS C:>fuu 
fuu: this is not a cmdlet .... BLA BLA BLA 
+ ~~~ 
    + CategoryInfo   : ObjectNotFound: (fuu:String) [], CommandNotFoundException 
    + FullyQualifiedErrorId : CommandNotFoundException 

这是ineractive PowerShell中的正常行为。 我可以把我的Profile.ps1中的东西或所以一切都保持这样,但对于一个特定的错误,例如这些CommandNotFoundException,只有在这些错误我改变PowerShell的行为?也许是一个新的主持人或其他东西。

powershell.exe 
PS C:>_ 
PS C:>fuu 
fuu: this is not a cmdlet so CommandNotFoundException and now i behave diffrent my lord 
PS C:>_ 

所以是的,我知道尝试捕捉等 - >在脚本中,但我的意思是interactivly作为默认的行为!

感谢

[更新]

要明确的事情了。真正的案例是编码。 ExecutionPolicy是AllSignt,如果我忘了签testcode ofcourse你得到了错误:

+ ~~~~~~~~~~~~~~ 
    + CategoryInfo   : Sicherheitsfehler: (:) [], PSSecurityException 
    + FullyQualifiedErrorId : UnauthorizedAccess 

但确切的这种情况下,我不想这个错误,我想这个问题,你要签名吗? Y/N

....比做那个。

回答

0

使用此结构:

$Error.Clear() 

fooo 

$Errormessage = $Error | Out-String 
$Errormessage 

您将获得:

fooo : The term 'fooo' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the 
path is correct and try again. 
At line:5 char:1 
+ fooo 
+ ~~~~ 
    + CategoryInfo   : ObjectNotFound: (fooo:String) [], CommandNotFoundException 
    + FullyQualifiedErrorId : CommandNotFoundException 

,当你有字符串就可以使解析器,让您的自定义错误处理程序一样

$customerror = $Errormessage.reaplace("fooo : The term 'fooo' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the 
path is correct and try again.","Foo is not functin") 

write-output $customerror 
+0

但如何我将这些添加到正常的PS行为?我不想在我的“fuu”调用中添加代码行。我想操纵错误处理的ineracive外壳 –

+0

@AnUser你的意思编辑powershell错误通过defult? 。我不知道这是可能的。对不起,朋友 。我只是把你的问题投给顶级的问题。如果你想我可以删除我的答案。 – saftargholi

+0

谢谢你,不要删除它,也许它会清理一些东西。 –