【问题标题】:Powershell Error-handling and loggingPowershell 错误处理和日志记录
【发布时间】:2013-02-13 13:55:39
【问题描述】:

我有以下 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()

【问题讨论】:

    标签: powershell error-handling


    【解决方案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 
    

    (无论如何,如果不是所有的属性都继承自这个一般的 expcetion,则 90%)

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

    【讨论】:

    • 感谢您的快速反馈。就您而言,此脚本将循环遍历大约 20,000 个文件。所以我想知道它是否在给定文件上停止。
    • 由于缺乏共享点经验,我无法为您提供帮助。尝试使用谷歌,或等待其他人的帮助。使用此信息更新您的问题,以便人们知道您需要检查什么。请尝试自己修复它(使用 google、SO 等学习)并在遇到问题时提供带有错误的示例。 MSDN 也是一个很好的资源,例如。 msdn.microsoft.com/en-us/library/…
    猜你喜欢
    • 2015-03-03
    • 2011-03-05
    • 2011-06-03
    • 2014-03-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-01-08
    相关资源
    最近更新 更多