Powershell错误处理和日志记录

时间:2013-02-27 16:43:35

标签: powershell error-handling

我有以下powershell脚本,它循环遍历文件列表并重命名它们。我想介绍一些错误处理,但不知道从哪里开始。

[System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SharePoint")

$Url = "https://....."
$UrlSub = "docs"
$FullPath = $Url + $UrlSub
$destinationFolder = "c:\022713\"
$sourceCsv = "c:\filename.CSV"

$Site = New-Object -TypeName Microsoft.SharePoint.SPSite $Url 
$web =  $Site.OpenWeb($UrlSub)
$fileObjects = Import-CSV $sourceCsv 

ForEach ($fileObject in $fileObjects) 
{
    $fileUrl = $fileObject.DOC_FILENAME.replace($Url,"")
    $file = $web.GetFile($FullPath)
        $binary = $file.OpenBinary()

    $dateTimeStamp = Get-Date -format s
    $newFileName = $fileObject.DocumentType + "_" + $fileObject.SAPObjectNumber + "_" + $dateTimeStamp.replace(":","").replace("-","")
    $extension = [System.IO.Path]::GetExtension($file.Name)

    $stream = New-Object System.IO.FileStream(($destinationfolder + $newFileName + $extension), [System.IO.FileMode]::Create)
    $writer = New-Object System.IO.BinaryWriter($stream)
    $writer.write($binary)
    $writer.Close()
}
$web.Dispose()

1 个答案:

答案 0 :(得分:1)

嗯,你这里没有给我们太多帮助。您需要弄清楚代码中可能出现的问题并使用ex来处理这些问题。尝试/捕获块或陷阱。

实施例。如果您无权创建/覆盖目标文件,则filestream构造函数可能会抛出异常。这是一个UnauthorizedAccessException例外,正如MSDN - FileStream Class所定义的那样。为了解决这个问题,你可以使用它:

try {
    $stream = New-Object System.IO.FileStream($destinationfolder + $newFileName + $extension), Create
    $writer = New-Object System.IO.BinaryWriter($stream)
    $writer.write($binary)
    $writer.Close()
} catch [UnauthorizedAccessException] {
    #Handle your exception, ex. log it. Exception is stored in variable $_  and includes properties like $_.message
} catch {
    #Catch every possible terminating exception except 'UnauthorizedAccessException'
}

要检查异常的属性,请使用

(new-object UnauthorizedAccessException) | gm

(new-object Exception) | gm 

(如果并非所有属性都是90%,那么无论如何都是从这种普遍的过程中继承的)

在此搜索SO或Google以了解有关try / catch和陷阱的更多信息。