powershell - Powershell错误处理和记录

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

最佳答案

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

例如如果您无权创建/覆盖目标文件,则filestream构造函数可能会引发异常。这是MSDN - FileStream Class定义的UnauthorizedAccessException异常。要处理此异常,可以使用以下代码:

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和trap的更多信息。

关于powershell - Powershell错误处理和记录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15143905/

相关文章:

powershell - SaltStack : run powershell script in a state

powershell - Get-ChildItem和Copy-Item说明

PowerShell 管道或输入参数

c# - 等效于 Powershell [ValidateSet]

c - 哪些事件会导致 ferror 返回非零值?

windows - 为什么这个try/catch block 神奇地吞噬了异常?

javascript - 如何测试 Jest 没有抛出异常?

Powershell v2::加载 COM 互操作 DLL

json - JSONEncoder.encode 在 Swift 中抛出什么异常?

php - 有没有一种干净的方法将 undefined variable 用作PHP中的可选参数?