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