2016-06-08 38 views
0

我有一个脚本,在启动时测试几件事情,例如,如果某些网络驱动器仍然需要映射。它会根据需要映射它。

有时会出现这样的错误。

In \\server\powershell$\Powershell-Scripts\_DVLP\LogonScript.ps1:57 
Zeichen:9 
+   $Map.MapNetworkDrive($_.letter,$_.path,$false) 
+   ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 
    + CategoryInfo   : NotSpecified: (:) [], MethodInvocationException 
    + FullyQualifiedErrorId : ComMethodTargetInvocation 

我得到这个错误作为一个文件,它是由单纯出口的$error变量文件

$error |out-file C:\myfile.txt -force 

,你可以看到生成的电子邮件附件,错误不是很有用的,因为我没有看到那里的驱动器号。所以我想把我的.mapnetworkdrive包装成一个Try/Catch Block。

Try {...} 
Catch { 
    $failedletter= $_.letter 
    $failedpath = $_.path 
    $export = $failedletter + $failedpath + $_.exception.message #send this to $error variable 
} 

我现在的问题是,如果我可以给整个catch块(或部分)的$error变量,所以我没有让我的日志更加复杂。有什么办法将事情发送到错误变量?

我可以简单地做$error += $export?那么它在$ error变量中是两次?只应在有一次

+0

我会用'$ error | fl * -Force'并将结果传递给你的'out-file' –

+0

@jisaak问题更像,我怎样才能得到更多的东西(见$ failedletter和$ failedpath)到错误变量,因为这个变量的行为是用错误信息填充本身。我不知道如何做到这一点,而不会破坏任何东西或获得两次关于1错误的错误信息。 – SimonS

回答

0

如果你调用一个ErrorRecordGet-Member cmdlet的,你会看到,你只能够设置ErrorDetails

Name     MemberType  Definition                                    
----     ----------  ----------                                    
Equals    Method   bool Equals(System.Object obj)                               
GetHashCode   Method   int GetHashCode()                                  
GetObjectData   Method   void GetObjectData(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context), void ISerializable.... 
GetType    Method   type GetType()                                   
ToString    Method   string ToString()                                  
CategoryInfo   Property  System.Management.Automation.ErrorCategoryInfo CategoryInfo {get;}                      
ErrorDetails   Property  System.Management.Automation.ErrorDetails ErrorDetails {get;set;}                      
Exception    Property  System.Exception Exception {get;}                              
FullyQualifiedErrorId Property  string FullyQualifiedErrorId {get;}                             
InvocationInfo  Property  System.Management.Automation.InvocationInfo InvocationInfo {get;}                      
PipelineIterationInfo Property  System.Collections.ObjectModel.ReadOnlyCollection[int] PipelineIterationInfo {get;}                 
ScriptStackTrace  Property  string ScriptStackTrace {get;}                               
TargetObject   Property  System.Object TargetObject {get;}                              
PSMessageDetails  ScriptProperty System.Object PSMessageDetails {get=& { Set-StrictMode -Version 1; $this.Exception.InnerException.PSMessageDetails };}  

所以,你可以这样做:

Try {...} 
catch { 
    $_.ErrorDetails += ('Letter: {0} Path: {1}' -f $_.letter, $_.path) 
    throw $_ 
}