Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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:22713"
$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()
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
248 views
Welcome To Ask or Share your Answers For Others

1 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...