Powershell Error-handling and logging

2019-09-21 04:08发布

问题:

I have the following powershell script that cycles through a list of files and renames them. I'd like to introduce some error handling, but not sure where to begin.

[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:

Well you don't give us much to work with here. You need to figure out what can go wrong in your code and handle those using ex. try/catch blocks or traps.

Ex. your filestream constructor may throw an exception if you don't have access to create/overwrite the destination-file. This is an UnauthorizedAccessException exception, as defined at MSDN - FileStream Class So to handle that, you can use this:

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'
}

To inspect the properties of an exception, use

(new-object UnauthorizedAccessException) | gm

or

(new-object Exception) | gm 

(90% if not all of the properties are inherited from a this general expcetion anyways)

Search here at SO or google to learn more about try/catch and traps.