Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/powershell/13.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Powershell错误处理和日志记录_Powershell_Error Handling - Fatal编程技术网

Powershell错误处理和日志记录

Powershell错误处理和日志记录,powershell,error-handling,Powershell,Error Handling,我有下面的powershell脚本,它循环浏览文件列表并重命名它们。我想介绍一些错误处理,但不确定从哪里开始 [System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SharePoint") $Url = "https://....." $UrlSub = "docs" $FullPath = $Url + $UrlSub $destinationFolder = "c:\022713\" $sourceCsv = "c:\fi

我有下面的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.try/catch块或陷阱处理这些错误

例如,
filestream
构造函数可能会在您无权创建/覆盖目标文件时引发异常。这是一个
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

(如果不是所有属性都继承自此常规表达式,则为90%)


在SO或google上搜索,了解更多关于尝试/捕获和陷阱的信息。

感谢您的快速反馈。在您看来,这个脚本将在大约20000个文件中循环。因此,我想知道它是否在给定的文件上停止。由于缺乏sharepoint经验,我无法帮助您。尝试使用谷歌,或者等待其他人的帮助。用这些信息更新了你的问题,让人们知道你需要检查什么。一定要尝试自己修复(使用谷歌等来学习),并在遇到问题时提供错误示例。MSDN也是一个很好的资源,例如。
(new-object Exception) | gm