मैं किसी भी सवाल का जवाब मैं खोजने गया था से संतुष्ट नहीं था, इसलिए मैं कुछ मिलाया गया और ऊपर (में PowerShell 3.0+) इस के साथ आया था:
$output = try{your_command *>&1}catch{$_}
इस के साथ आप सभी त्रुटियों पर कब्जा कर सकते हैं और आउटपुट जो your_command
का उपयोग करने की कोशिश कर उत्पन्न होते हैं।
यह अपवाद पकड़ता है जब आप एक गैर-मौजूद आदेश का उपयोग करें:
PS C:\Users\jdgregson> $output = try{your_command *>&1}catch{$_}
PS C:\Users\jdgregson> echo $output
your_command : The term 'your_command' 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:1 char:15
+ $output = try{your_command 2>&1}catch{$_}
+ ~~~~~~~~~~~~
+ CategoryInfo : ObjectNotFound: (your_command:String) [], Comman
dNotFoundException
+ FullyQualifiedErrorId : CommandNotFoundException
PS C:\Users\jdgregson>
यह अपवाद पकड़ता है जब आप एक मौजूदा आदेश को अमान्य तर्क पारित:
PS C:\Users\jdgregson> $output = try{cat C:\invalid-path.txt *>&1}catch{$_}
PS C:\Users\jdgregson> echo $output
cat : Cannot find path 'C:\invalid-path.txt' because it does not exist.
At line:1 char:15
+ $output = try{cat C:\invalid-path.txt 2>&1}catch{$_}
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : ObjectNotFound: (C:\invalid-path.txt:String) [Ge
t-Content], ItemNotFoundException
+ FullyQualifiedErrorId : PathNotFound,Microsoft.PowerShell.Commands.GetCo
ntentCommand
और यह उत्पादन करता है, तो फैल जाती है वहाँ आपके आदेश के साथ कोई समस्या नहीं थी:
PS C:\Users\jdgregson> $output = try{cat C:\valid-path.txt *>&1}catch{$_}
PS C:\Users\jdgregson> echo $output
this file is really here
यह आपके लिए काम करता है उदाहरण भी:
PS C:\Users\jdgregson> $output = try{Test-Error *>&1}catch{$_}
PS C:\Users\jdgregson> echo $output
echo
WARNING: warning
Test-Error : error
At line:1 char:15
+ $output = try{Test-Error *>&1}catch{$_}
+ ~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [Write-Error], WriteErrorExcep
tion
+ FullyQualifiedErrorId : Microsoft.PowerShell.Commands.WriteErrorExceptio
n,Test-Error
@JasonMArcher इस प्रश्न पर टैग अपडेट करने के लिए धन्यवाद! क्या वीजा 3 में तय होने के बाद हमें कुछ भी अतिरिक्त करना चाहिए और मैं मूल रूप से वी 2 का उपयोग कर रहा था? धन्यवाद। – smaclell
यह निर्भर करता है, क्या आप केवल वी 2 के उत्तर चाहते हैं? यह कोई समस्या नहीं है जो V2 के लिए विशिष्ट है। इस प्रकार सबसे अच्छा विचार PowerShell के संस्करण के साथ वास्तविक उत्तरों को प्राथमिकता देना है जिसका उद्देश्य उनके लिए है। :) – JasonMArcher
मैंने पीएस संस्करण संगतता के बारे में मौजूदा उत्तरों में कुछ नोट्स जोड़े। – JasonMArcher