Powershell错误处理和记录 [英] Powershell Error-handling and logging

查看:82
本文介绍了Powershell错误处理和记录的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下Powershell脚本,可以循环浏览文件列表并重命名它们。我想介绍一些错误处理,但不确定从哪里开始。

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()


推荐答案

好吧,在这里您不给我们太多工作。您需要找出代码中可能出问题的地方,并使用ex处理那些错误。尝试/捕获块或陷阱。

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.

例如。如果您无权创建/覆盖目标文件,则 filestream 构造函数可能会引发异常。这是一个 UnauthorizedAccessException 异常,在 MSDN-FileStream类因此,您可以使用以下方法:

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

(new-object Exception) | gm 

(如果不是所有属性的90%都是从这个常规表达式继承而来的)

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

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

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

这篇关于Powershell错误处理和记录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆