I have this script running in VSCode but different $SiteURL. I open this script again in ISE and change the $SiteUR $searchfor and $folderpath. The issue I have is everytime I run in ISE and when it's doing Get-PnPListItem, it's getting an items from the path that I provided in the VSCode. Not sure what is going on so I would be really appreciated if I can get any help or suggestion.
$SiteURL = "https://companyName-my.sharepoint.com/personal/user_id"
$searchfor = "/personal/user_id/Documents/Pkmon"
$folderpath = "Documents/Pkmon"
$CSVFile = "C:\Users\user\Desktop\Resource\FolderStats.csv"
#Connect to SharePoint Online
Connect-PnPOnline $SiteURL -useWebLogin
$FolderItems = Get-PnpListItem -List $folderpath -PageSize 2000 -Fields ID, FileDirRef, FileRef -ScriptBlock `
{ Param($items) $global:counter += $items.Count; Write-Progress -PercentComplete ($global:Counter / ($List.ItemCount) * 100) -Activity `
"Getting Items from Folder '$FolderServerRelativeURL'" -Status "Getting Items $global:Counter of $($List.ItemCount)"; }
$fieldvalues = $FolderItems.Fieldvalues
$result = #()
foreach ($field in $fieldvalues) {
$obj = New-object psobject -property $field
$result += $obj.fileref
}
$final = $result | where-object {$_ -match $searchfor}
$item = New-Object psobject -Property #{
FolderName = Split-Path -Path $searchfor -Leaf
URL = $searchfor
filesfoldercount = $final.count
}
$item
$item | Export-Csv -Path $CSVFile -NoTypeInformation
You can capture the connection object in a variable like
$thisConnection = Connect-PnPOnline $SiteURL -useWebLogin -ReturnConnection
-ReturnConnection acts as what is normally called -PassThru. It makes the cmdlet return the connection object for use with the -Connection parameter on other cmdlets.
Then use that in parameter -Connection of the Get-PnpListItem cmdlet:
$FolderItems = Get-PnpListItem -List $folderpath -Connection $thisConnection ...
You may also need to specify the connection in the VSCode instance.
When done, disconnect using Disconnect-PnPOnline -Connection $thisConnection
Related
I've this PowerShell Script that get the folder name, Folder path and last modified from either SharePoint Online or OneDrive account but I'm just wondering how can I also get the the file name inside each folder, their path and latest modified date in the same report file.
I've stuck with this so any help or suggestion would be really appreciated.
Connect-PnPOnline $SiteURL -Credentials $credential
#Get the list
$List = Get-PnPList -Identity $ListName
#Get Folders from the Library - with progress bar
$global:counter = 0
$FolderItems = Get-PnPListItem -List $ListName -PageSize 500 -Fields FileLeafRef -ScriptBlock { Param($items) $global:counter += $items.Count; Write-Progress -PercentComplete `
($global:Counter / ($List.ItemCount) * 100) -Activity "Getting Items from List:" -Status "Processing Items $global:Counter to $($List.ItemCount)"; } | Where { $_.FileSystemObjectType -eq "Folder" }
Write-Progress -Activity "Completed Retrieving Folders from List $ListName" -Completed
$FolderStats = #()
ForEach ($FolderItem in $FolderItems) {
#Get Files and Folders of the Folder
Get-PnPProperty -ClientObject $FolderItem.Folder -Property Files, Folders | Out-Null
#Collect data
$Data = [PSCustomObject][ordered]#{
FolderName = $FolderItem.FieldValues.FileLeafRef
Path = $FolderItem.FieldValues.FileRef
ModifiedDate = $FolderItem.FieldValues.Modified
}
$Data
$FolderStats += $Data
}
$FolderStats | Export-Csv -Path $CSVFile -NoTypeInformation
I have a very large SharePoint folder with many nested subfolder and I'm trying to count how many items are in there before we migrate that folder to different location.
I've this simple script but I'm always getting this error when every I tried to count a folder that really large so just wondering how can I increase the threshold or fix this issue.
$SiteURL = "https://company-my.sharepoint.com/personal/hello_nam_corp_com"
$searchfor = "/Documents/Archive"
$folderpath = "Documents/Archive"
$CSVFile = "C:\Users\Desktop\Resource\FolderStats.csv"
#Connect to SharePoint Online
Connect-PnPOnline $SiteURL -useWebLogin
#Get the list
#$documents = Get-PnPList -Identity $ListName | Where-Object {$_.Title -eq 'Documents'}
$FolderItems = Get-PnpListItem -List $folderpath
$fieldvalues = $FolderItems.Fieldvalues
$result = #()
foreach ($field in $fieldvalues) {
$obj = New-object psobject -property $field
$result += $obj.fileref
}
$final = $result | where-object {$_ -match $searchfor}
$item = New-Object psobject -Property #{
FolderName = Split-Path -Path $searchfor -Leaf
URL = $searchfor
filesfoldercount = $final.count
}
$item
$item | Export-Csv -Path $CSVFile -NoTypeInformation
Get-PnpListItem : The attempted operation is prohibited because it exceeds the list view threshold.
At line:13 char:16
+ $FolderItems = Get-PnpListItem -List $folderpath
Try below PowerShell.
#Parameters
$SiteURL = "https://crescent.sharepoint.com/sites/marketing"
$ListName = "Branding"
$CSVFile = "C:\Temp\FolderStats.csv"
#Connect to SharePoint Online
Connect-PnPOnline $SiteURL -Interactive
#Get the list
$List = Get-PnPList -Identity $ListName
#Get Folders from the Library - with progress bar
$global:counter = 0
$FolderItems = Get-PnPListItem -List $ListName -PageSize 500 -Fields FileLeafRef -ScriptBlock { Param($items) $global:counter += $items.Count; Write-Progress -PercentComplete `
($global:Counter / ($List.ItemCount) * 100) -Activity "Getting Items from List:" -Status "Processing Items $global:Counter to $($List.ItemCount)";} | Where {$_.FileSystemObjectType -eq "Folder"}
Write-Progress -Activity "Completed Retrieving Folders from List $ListName" -Completed
$FolderStats = #()
#Get Files and Subfolders count on each folder in the library
ForEach($FolderItem in $FolderItems)
{
#Get Files and Folders of the Folder
Get-PnPProperty -ClientObject $FolderItem.Folder -Property Files, Folders | Out-Null
#Collect data
$Data = [PSCustomObject][ordered]#{
FolderName = $FolderItem.FieldValues.FileLeafRef
URL = $FolderItem.FieldValues.FileRef
FilesCount = $FolderItem.Folder.Files.Count
SubFolderCount = $FolderItem.Folder.Folders.Count
}
$Data
$FolderStats+= $Data
}
#Export the data to CSV
$FolderStats | Export-Csv -Path $CSVFile -NoTypeInformation
Script Link: https://www.sharepointdiary.com/2019/05/sharepoint-online-get-files-sub-folders-count-in-document-library-using-powershell.html
In my SharePoint site, I have two folders called "General" and "Testing2" under Document. I'm trying to get the count only for "General" but not sure why it's still also counting for Testing2 folder so I would be really appreciate if I can get any help or suggestion.
I tried like this, $ListName = "/Shared Documents/General" but still not working
#Parameters
$SiteURL = "https://comapny.sharepoint.com/sites/msteams_####/"
//I tried like this but still not working
$ListName = "/Shared Documents/General"
$CSVFile = "C:\Users\kek\Desktop\Resource\LitHold\FolderStats.csv"
#Connect to SharePoint Online
Connect-PnPOnline $SiteURL -useWebLogin
#Get the list
$List = Get-PnPList -Identity $ListName
#Get Folders from the Library - with progress bar
$global:counter = 0
$FolderItems = Get-PnPListItem -List $ListName -PageSize 500 -Fields FileLeafRef -ScriptBlock { Param($items) $global:counter += $items.Count; Write-Progress -PercentComplete `
($global:Counter / ($List.ItemCount) * 100) -Activity "Getting Items from List:" -Status "Processing Items $global:Counter to $($List.ItemCount)";} | Where {$_.FileSystemObjectType -eq "Folder"}
Write-Progress -Activity "Completed Retrieving Folders from List $ListName" -Completed
$FolderStats = #()
#Get Files and Subfolders count on each folder in the library
ForEach($FolderItem in $FolderItems)
{
#Get Files and Folders of the Folder
Get-PnPProperty -ClientObject $FolderItem.Folder -Property Files, Folders | Out-Null
#Collect data
$Data = [PSCustomObject][ordered]#{
FolderName = $FolderItem.FieldValues.FileLeafRef
URL = $FolderItem.FieldValues.FileRef
FilesCount = $FolderItem.Folder.Files.Count
SubFolderCount = $FolderItem.Folder.Folders.Count
}
$Data
$FolderStats+= $Data
}
#Export the data to CSV
$FolderStats | Export-Csv -Path $CSVFile -NoTypeInformation
I don't want to to print Testing 2
I am trying to generate a script that automatically uploads a Power BI report to a list of workspaces, but since I'm not that experienced with PowerShell I feel a bit out of my depth.
Based on this post
https://dev.to/merill/powershell-script-to-generate-a-report-on-all-power-bi-workspaces-and-groups-in-your-microsoft-365-tenant-44pc
I have written a script that generates an array of workspaces:
Connect-PowerBIServiceAccount
$workspaces = Get-PowerBIWorkspace -Scope Organization -Include All
$wslist = #()
foreach ($ws in $workspaces) {
$item = [ordered] #{
Id = $ws.ID
Name = $ws.Name
}
$u = new-object PSObject -Property $item
$wslist += $u
}
Similarly, I have written a script that generates an array of report ID's uploaded to a given Workspace:
Connect-PowerBIServiceAccount
$workspaceid = "enter-id-here"
$reports = Get-PowerBIReport -WorkspaceId $workspaceid
$rlist = #()
foreach ($r in $reports) {
$r
$item = [ordered] #{
Id = $r.ID
Name = $r.Name
}
$u = new-object PSObject -Property $item
$rlist += $u
}
What I want to do is merge these arrays into one that only includes the rows where the report name is equal to some predefined name stored in a string var.
Finally, I want to iterate through the array, and for each row delete the old report and then upload a new version.
If I got your point correctly, you need something like this:
Import-Module MicrosoftPowerBIMgmt
$oldReportName = "Fancy Report"
$pbixFilePath = "C:\Power BI\Fancy Report.pbix"
$username = "user#example.com"
$password = "P#ssw0rd" | ConvertTo-SecureString -asPlainText -Force
$credential = New-Object System.Management.Automation.PSCredential($username, $password)
Connect-PowerBIServiceAccount -Credential $credential | Out-Null
# -All - Returns all results, not only top 100
$workspaces = Get-PowerBIWorkspace -All -Scope Organization -Include All
foreach($workspace in $workspaces) {
$report = Get-PowerBIReport -WorkspaceId $workspace.Id -Scope Organization -Name $oldReportName
if ($report) {
Write-Host "Report $oldReportName found in workspace $($workspace.Name)..."
New-PowerBIReport -Path $pbixFilePath -Workspace $workspace -ConflictAction CreateOrOverwrite
}
}
Disconnect-PowerBIServiceAccount
$oldReportName is the name of the report, that you are looking for. $pbixFilePath is where the new version that should be uploaded is. I've added -All, because otherwise Get-PowerBIWorkspace will return only the first 100 workspaces in the tenant. And because this is tenant-wise operation, $username and $password should be admin credentials (as of October 2020 service principal cannot be used for admin operations).
There is no need to construct an array. Just iterate through the workspaces and check is there a report with this name published there ($report = Get-PowerBIReport -WorkspaceId $workspace.Id -Scope Organization -Name $oldReportName). If such one exists, upload the new one there and replace it (New-PowerBIReport -Path $pbixFilePath -Workspace $workspace -ConflictAction CreateOrOverwrite).
The final, fully working PS script (with dummy names and paths) looks like this:
Connect-PowerBIServiceAccount
Import-Module MicrosoftPowerBIMgmt
# Report name here:
$ReportName = "AwesomeReport"
$FolderPath = "C:\Users\AwesomeUser\AwesomeReports"
$workspaces = Get-PowerBIWorkspace -All -Scope Organization -Include All
foreach($workspace in $workspaces) {
$report = Get-PowerBIReport -WorkspaceId $workspace.Id -Scope Organization -Name $ReportName
if ($report) {
Write-Host "Report $ReportName found in workspace $($workspace.Name)..."
$filePath = "$FolderPath\$($workspace.Name)\$ReportName.pbix"
New-PowerBIReport -Path $filePath -WorkspaceId $workspace.Id -Name $ReportName -ConflictAction CreateOrOverwrite
}
}
Disconnect-PowerBIServiceAccount
I'm trying to upload a fileshare from my local machine to SharePoint using Add-PnPFile, i also have csv that has all the properties("Modified By", "Created By") for each file.
I have written this code below to grab the all the properties of the files from a csv document and tested to see if the user existed in the tenant before the using the Add-PnPFile command to upload the file.
Function Upload-Nom{
Param (
[parameter(Position=0,ValueFromPipeline=$True,ValueFromPipelineByPropertyName=$True)]
[Alias('FullName')]
[string[]]$Path = $PWD
)
Begin {}
Process {
ForEach ($item in $Path) {
#iterate all the file urls in the csv
Import-Csv $item | ForEach-Object {
#capture all the properties you need to update the file properties on sharepoint
$name = $_.Name
$fullName = $_.FullName
$itemtype = $_.'Item Type'
$relativepath = $_.Path -replace '(sites\/honours\/)'
$modifiedbyuser = $_.'Modified By'
$createdbyuser = $_.'Created By'
$modified = $_.Modified
$path = $_.Path -replace '\/','\'
$path = $path -replace '(sites\\honours\\)'
$fullurl ="C:\Users\modonny\Downloads\" +$path+"\"+ $name
#convert dates to SP format
[DateTime]$dateformats = New-Object System.DateTime;
if([DateTime]::TryParse($_.Modified, [ref]$dateformats)){
$cdob = $dateformats;
}
$modifieduser = Get-PnPUser | ? Title -eq $modifiedbyuser
$createduser = Get-PnPUser | ? Title -eq $createdbyuser
#check if user exists in tenancy
if($modifieduser){
$muserid = $modifiedbyuser.Email
}else{
$muserid = "john.doe#test.gov.uk"
}
if($createduser){
$cuserid = $createduser.Email
}else{
$createduser = Get-PnPUser | ? Email -EQ "john.doe#test.gov.uk"
$cuserid = "john.doe#test.gov.uk"
}
$object = #{}
$object.Add("Modified",$cdob)
$object.Add("Editor" ,$muserid)
$object.Add("Author" ,$cuserid)
if($fullurl | Test-Path){
if($itemtype -eq 'Folder'){
write-host "this item is a folder"
}else{
#upload files to sharepoint with the data in the $object variable
Add-PnPFile -Path $fullurl -Folder $relativepath -Values $object
}
}
}
}
}
Upload-Nom -Path "C:\Users\modonny\Documents\testing.csv"
When the code completes running all files are uploaded but the Modified By/Created By property isn't.
Sample script for your reference.
#region Variables
$Username = "user#tenant.onmicrosoft.com"
$Password = "password"
$siteURL = "https://tenant.sharepoint.com/sites/Community"
#endregion Variables
#region Credentials
[SecureString]$SecurePass = ConvertTo-SecureString $Password -AsPlainText -Force
[System.Management.Automation.PSCredential]$PSCredentials = New-Object System.Management.Automation.PSCredential($Username, $SecurePass)
#endregion Credentials
Connect-PnPOnline -Url $siteURL -Credentials $PSCredentials
$user=Get-PnPUser | ? Email -eq "user1#tenant.onmicrosoft.com"
Add-PnPFile -Path "C:\Lee\test.docx" -Folder "MyDoc" -Values #{Editor=""+$user.Id+"";Modified="7/24/2019"}