我有一个Powershell脚本,该脚本读取文件和文件夹信息并将数据添加到数组。
如果存在断点,脚本可以正常运行。断点可以在脚本中的任何位置,一旦到达断点,我就继续执行代码,而不会出现错误。
即使我使用断点之前的行Disabled
将断点设置为Get-PSBreakpoint | Disable-PSBreakpoint
,代码也可以正确执行。
删除断点后,代码错误“方法调用失败,因为添加到数组时[System.ManagementAutomation.PSObject]
不包含名为op_Addition
的方法。
这里发生错误
$report += New-Object -TypeName PSObject -Property $props
在这里
$filerec += New-Object -TypeName PSObject -Property $propsfile
这是发生错误的功能
function ScanDrive([string]$scanpath)
{
#Scan the drive
$files = Get-ChildItem -Path $scanpath -Force -Recurse
$filecount = $files.Count
$Counter = 0
#Set up the result array
$folderRes = @()
$filesRes = @()
ForEach ($file in $files)
{
$lblInfo.Text = $file.FullName
$Form.Refresh()
$Counter++
[Int]$Percentage = ($Counter/$filecount)*100
$pbScan.Value = $Percentage
Write-Debug "Help"
if ($file.Attributes -eq 'Directory')
{
write-host 'This is a folder' + $file.FullName -ForegroundColor DarkGreen
try
{
$acl = Get-Acl -path $file.PSPath
Write-Host 'ACL' + $acl.Group.ToString()
$access = $acl.access
foreach($ar in $access)
{
$props = [ordered]@{
'ID' = ''
'FolderName' = $file.Name;
'ADGroupUser' = $ar.IdentityReference;
'Permissions' = $ar.FileSystemRights.ToString();
'ControlType' = $ar.AccessControlType;
'IsInherited' = $ar.IsInherited
}
$report += New-Object -TypeName PSObject -Property $props
$folderRes += $report
}
Write-Host "Folder record count : " + $folderRes.Count.ToString()
}
catch
{
Write-Host '******************************' -ForegroundColor Yellow
Write-Host 'Error ' + $_.Exception.Message -ForegroundColor Red
Write-Host '******************************' -ForegroundColor Yellow
}
}
else
{
write-host 'This is a file' + write-host $file.FullName -ForegroundColor DarkGreen
$iname = $file.Name
$iparent = $file.PSParentPath
$isize = $file.Length
$itype = $file.Extension
$iowner = get-acl $file.FullName
$owner = $iowner.Owner
$icreated = $file.CreationTime
$ilasmod = $file.LastWriteTime
$idirectory = $file.Directory
$ireadonly = $file.IsReadOnly
$ilastacc = $file.LastAccessTime
$ifilename = $file.FullName
$usergroup = $iowner.Group
$iatts = $file.Attributes
$propsfile = [ordered]@{
'ID' = ''
'Name' = $iname;
'Parent' = $iparent;
'Size' = $isize;
'Type' = $itype;
'Owner' = $owner;
'CreatedDate' = $icreated;
'LastModDate' = $ilasmod;
'Directory' = $idirectory;
'IsReadOnly' = $ireadonly;
'LastAccessedDate' = $ilastacc;
'FileName' = $ifilename;
'UserGroup' = $usergroup;
'Attributes' = $iatts;
'LoggedDate' = Get-Date
}
$filerec += New-Object -TypeName PSObject -Property $propsfile
$filesRes += $filerec
}
}
Write-Host "File record count : " + $filesRes.Count.ToString()
Return $filesRes,$folderRes
}
答案 0 :(得分:1)
您无需添加到$filerec
和$report
,只需覆盖它们即可(将+=
更改为=
):
$filerec = New-Object -TypeName PSObject -Property $propsfile
$report = New-Object -TypeName PSObject -Property $props
当前代码尝试创建一个对象数组,然后将其添加到另一个数组中,这将在$folderRes
和$filesRes
中创建重复项。