How I can show and add items to Sharepoint List via Powershell? - list

hi I want to show and add items in Sharepoint via Powershell (I use for testing a list and a libary)
The name is Powershell-Test
the Url is
http//intranet/departments/it/abt/Lists/Powershell-Test/AllItems.aspx
I enable remote on the Sharepoint Server and make a remote connection to this from my localhost.
Enter-PSSession -ComputerName [sharepoint server] -Authentication Negotiate -Credential [Domain\name]
if((Get-PSSnapin -Name Microsoft.Sharepoint.Powershell -ErrorAction SilentlyContinue) -eq $null)
{
Add-PSSnapin Microsoft.Sharepoint.Powershell
}
$webURL = "http//intranet/departments/it/abt/Lists/"
$listname = "Powershell-Test"
$web = Get-SPWeb $webURL
$web.lists | format-table title
$list = $web.LIsts[$listName]
$list.items | foreach { $_[„Title“] + „`n“ + $_[„Body“] }
The Problem is that I don#t get the connection to the list :(
How I can to this?

I presume you have permission to access the site.
I also presume you don't have a site or subsite with the name "Lists".
I don't think you can use Get-SPWeb with the path "/Lists/" within it (unless the site was named "lists").
Could you try:
if ((Get-PSSnapin -Name Microsoft.SharePoint.Powershell -ErrorAction SilentlyContinue) -eq $null) {
Add-PSSnapin Microsoft.SharePoint.Powershell
}
$siteURL = "http//intranet/departments/it/abt/"
$web = Get-SPWeb $siteURL
$list = $web.Lists["Powershell-Test"]
$list.Items | foreach { $_["Title"] + "`n" + $_["Body"] }

Related

Gateway Binding using the API

I get an Error 400 (Bad Request) using the code below. I have looked at it for hours. Does anyone see anything wrong? Any suggestions? I've tried the suggestions in this link, but no luck: https://community.powerbi.com/t5/Developer/BindToGateway-Powershell-REST-API-POST-failing-Need-Help/m-p/852851
#Login to Power BI using PowerBIPS App registration.
Write-Host "Start Login"
$ApplicationId = "abc123"
$SecurePassword = "password" | ConvertTo-SecureString -AsPlainText -force
$credential = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList
$ApplicationId, $SecurePassword
Connect-PowerBIServiceAccount -ServicePrincipal -Credential $credential -TenantId "ten123"
Write-Host "Login Success"
Write-Host "Get Workspace info for workspace: AC Common_TST"
$workspaceName = "AC Common_TST"
$datasetName = "DateDim"
$workspace = Get-PowerBIWorkspace -Name $workspaceName
$workspaceObject = ( Get-PowerBIWorkspace -Name "AC Common_TST" )
$groupid=$workspaceObject.id
$newGatewayId = "gatewayid" # the ID of PRDGateway1
$dataset = Get-PowerBIDataset -WorkspaceId $workspace.Id | Where-Object Name -eq $datasetName
$datasetid = $dataset.id
$workspaceId = $workspace.Id
Write-Host "GroupID is "$workspace.id
Write-Host "Dataset ID is "$dataset.id
# POST body
$postParams = #'
{
"gatewayObjectId": "gatewayid",
"datasourceObjectIds": [
"dsid"
]
}
'#
$jsonPostBody = $postParams | ConvertTo-JSON
$uri = "https://api.powerbi.com/v1.0/myorg/groups/$workspaceid/datasets/$datasetId/Default.BindToGateway"
Invoke-PowerBIRestMethod -URL $uri -Method POST -Body $jsonPostBody
Resolve-PowerBIError -Last

Powershell Script to get all columns and type in a SPList

I want to retrieve all columns, and their type in a SharePoint list.
I have tried several scripts but the results are not what I am looking for.
Below are the scripts I have tried:
Add-PSSnapin Microsoft.SharePoint.PowerShell -ErrorAction SilentlyContinue
#Configuration Parameters
$SiteURL="http://url.com/"
$ListName= "theList"
$CSVPath="C:\Temp\list.csv"
#Get the Web and List
$Web = Get-SPWeb $SiteURL
$List = $Web.Lists.TryGetList($ListName)
#Export List Fields to CSV file
$List.Fields | select Title, InternalName | Export-Csv -path $CSVPath -NoTypeInformation
Add-PSSnapin Microsoft.SharePoint.PowerShell -ErrorAction SilentlyContinue
$url = "http://url.com/"
$listName = "theList"
$path ="C:\Temp\list.csv"
$web = Get-SPWeb $url
$list = $web.Lists.TryGetList($listName)
$fields = $list.ContentTypes | %{ $_.FieldLinks }
$items = #() #array to store objects representing list items
$list.items | %{
$item = $_;
$hash = #{}; #hash table to store field name-value pairs
$fields | %{ $hash[$_.DisplayName] = $item[$_.Name] };
$items += new-object psobject -Property $hash }
$items | Export-Csv -Path $path
Just adding the Type property.
Add-PSSnapin Microsoft.SharePoint.PowerShell -ErrorAction SilentlyContinue
#Configuration Parameters
$SiteURL="http://sp:12001"
$ListName= "Customers"
$CSVPath="C:\Lee\script\list.csv"
#Get the Web and List
$Web = Get-SPWeb $SiteURL
$List = $Web.Lists.TryGetList($ListName)
#Export List Fields to CSV file
$List.Fields | select Title, InternalName,Type | Export-Csv -path $CSVPath -NoTypeInformation

Get sharepoint lists with more than 5000 items Sharepoint Online Powershell

Can you please help me with a powershell script in sharepoint online that will get all the list with more than 5000 items ? TYIA!
The following PowerShell script for your reference:
Add-Type -Path "C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\16\ISAPI\Microsoft.SharePoint.Client.dll"
Add-Type -Path "C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\16\ISAPI\Microsoft.SharePoint.Client.Runtime.dll"
$SiteURL="https://xx.sharepoint.com/sites/lz"
$UserName="lz#xx.onmicrosoft.com"
$Password = "xx"
$listName ="customlist"
$rowLimit=100
$SecurePassword = $Password | ConvertTo-SecureString -AsPlainText -Force
$Creds = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($UserName,$SecurePassword)
#Bind to Site Collection
$ctx = New-Object Microsoft.SharePoint.Client.ClientContext($SiteURL)
$ctx.Credentials = $Creds
$list = $ctx.Web.Lists.GetByTitle($listName)
$ctx.Load($list)
# Prepare the query
$query = New-Object Microsoft.SharePoint.Client.CamlQuery
$query.ViewXml = "<View>
<RowLimit>$rowLimit</RowLimit>
</View>"
# An array to hold all of the ListItems
$items = #()
# Get Items from the List until we reach the end
do
{
$listItems = $list.getItems($query)
$ctx.Load($listItems)
$ctx.ExecuteQuery()
$query.ListItemCollectionPosition = $listItems.ListItemCollectionPosition
foreach($item in $listItems)
{
Try
{
# Add each item
$items += $item
}
Catch [System.Exception]
{
# This shouldn't happen, but just in case
Write-Host $_.Exception.Message
}
}
}While($query.ListItemCollectionPosition -ne $null)

Why Am I Seeing These Errors in My SSRS Powershell Script in One Environment but Not Another?

I have a Powershell Script I'm working on for post-migration SSRS report administration tasks.
In this particular scenario we have a DEV environment (where I've been primarily testing) which hosts a single instance of SSRS, and a Prod environment which is a scaled out deployment across 4 nodes.
I'm new to Powershell (just discovered it 2 days ago...) and the script I have is pretty simple:
Clear-Host 
$Username = "domain\myUsername"
$Password = "myPassword"
$Cred = New-Object System.Management.Automation.PSCredential -ArgumentList #($Username,(ConvertTo-SecureString -String $Password -AsPlainText -Force))
# Dev Connection String
$webServiceUrl = 'http://DEVwebServer.domain.com/reportserver/reportservice2010.asmx?WSDL'
# Prod Connection String
# $webServiceUrl = 'http://PRODwebServerNode1.domain.com/reportserver/reportservice2010.asmx?WSDL'
$rs = New-WebServiceProxy -Uri $webServiceUrl -Credential $Cred
 
$reports = $rs.ListChildren("/Some Folder Under Root", $true) | Where-Object { $_.TypeName -eq "Report" }
$type = $ssrsProxy.GetType().Namespace;
$schedDefType = "{0}.ScheduleDefinition" -f $type;
$schedDef = New-Object ($schedDefType)
$warning = #();
foreach ($report in $reports) {
$sched = $rs.GetExecutionOptions($report.Path, [ref]$schedDef);
$snapShotExists = $rs.ListItemHistory($report.Path);
if($sched -eq "Snapshot") {
Write-Host "Following report is configured to run from Snapshot:" -ForegroundColor Yellow
Write-Host ("Report Name: {0}`nReport Path: {1}`nExecution Type: {2}`n" -f $report.Name, $report.Path, $sched)
if ($snapShotExists) {
Write-Host "Does Snapshot Exist..?`n" -ForegroundColor Yellow
Write-Host "Yes!`tNumber of Snapshots: " $snapShotExists.Count -ForegroundColor Green
$snapShotExists.CreationDate
Write-Host "`n------------------------------------------------------------"
}
elseif (!$snapShotExists) {
Write-Host "Does Snapshot Exist..?`n" -ForegroundColor Yellow
Write-Host ("No!`n") -ForegroundColor Red
Write-Host "Creating Snapshot.......`n" -ForegroundColor Yellow
$rs.CreateItemHistorySnapshot($report.Path, [ref]$warning);
Write-Host "Snapshot Created!`n" -ForegroundColor Green
$snapShotExists.CreationDate
Write-Host "`n------------------------------------------------------------"
}
}
}
The purpose of the script is simply to recursively iterate over all of the reports for the given folder in the $reports variable, check to see if the execution type is set to "Snapshot", if it is check to see if a "History Snapshot" exists, and if one does not exist, create one.
When I run this in Dev it works just fine, but when I run in PROD I get the following error repeated for each $report in my foreach loop:
Any ideas on why this would work in one and not the other and how to overcome this error?
I was able to get this working on the Prod instance by making some adjustments using this answer as a guide:
By updating my call to New-WebServiceProxy to add a Class and Namespace flag, I was able to update the script in the following ways:
...
# Add Class and Namespace flags to New-WebServiceProxy call
$rs = New-WebServiceProxy -Class 'RS' -Namespace 'RS' -Uri $webServiceUrl -Credential $Cred
 
$reports = $rs.ListChildren("/Business and Technology Solutions", $true) | Where-Object { $_.TypeName -eq "Report" }
# Declare new "ScheduleDefintion object using the Class declared in the New-WebServiceProxy call
$schedDef = New-Object RS.ScheduleDefinition
$warning = #();
foreach ($report in $reports) {
# Referencing the "Item" property from the ScheduleDefinition
$execType = $rs.GetExecutionOptions($report.Path, [ref]$schedDef.Item)
...
I don't think the adding of the Class and Namespace flags on the New-WebServiceProxy call was exactly what did it, as I think it's just a cleaner way to ensure you're getting the proper Namespace from the WebService. Maybe just a little sugar.
I think the key change was making sure to the "Item" property from the schedule definition object, although I'm not sure why it was working in Dev without doing so...

Access next webpage after clicking

Requirement : After clicking on webpage named in $ie.Navigate below. I Need to access HTML / OuterHTML source of Web-page which opens next.
Ex: When I open https://www.healthkartplus.com/search/all?name=Sporanox (by setting $control = Sporanox), below code simply clicks on first matching link. After link is clicked, I need to access HTML of resulting page.
Update : referred another SO question and learned that we can search appropriate window. Code seems to be working for some scenarios but not for all. For $ie2 I get problem accessing Document property.
function getStringMatch
{
# Loop through all 2 digit combinations in the $path directory
foreach ($control In $controls)
{
$ie = New-Object -COMObject InternetExplorer.Application
$ie.visible = $true
$site = $ie.Navigate("https://www.healthkartplus.com/search/all?name=$control")
$ie.ReadyState
while ($ie.Busy -and $ie.ReadyState -ne 4){ sleep -Milliseconds 100 }
$link = $null
$link = $ie.Document.get_links() | where-object {$_.innerText -eq "$control"}
$link.click()
while ($ie.Busy -and $ie.ReadyState -ne 4){ sleep -Milliseconds 100 }
$ie2 = (New-Object -COM 'Shell.Application').Windows() | ? {
$_.Name -eq 'Windows Internet Explorer' -and $_.LocationName -match "^$control"
}
# NEED outerHTML of new page. CURRENTLY it is working for some.
$ie.Document.body.outerHTML > d:\med$control.txt
}
}
$controls = "Sporanox"
getStringMatch
I think the issue is when you look for the links in the first page.
The link innerText is not equal to $control, it contains $control i.e. innerText is "Sporanox (100mg)".
The following might help:
$link = $ie.Document.get_links() | where-object {if ($_.innerText){$_.innerText.contains($control)}}
EDIT
Here is the complete code I'm using:
function getStringMatch
{
# Loop through all 2 digit combinations in the $path directory
foreach ($control In $controls)
{
$ie = New-Object -COMObject InternetExplorer.Application
$ie.visible = $true
$site = $ie.Navigate("https://www.healthkartplus.com/search/all?name=$control")
$ie.ReadyState
while ($ie.Busy -and $ie.ReadyState -ne 4){ sleep -Milliseconds 100 }
$link = $null
$link = $ie.Document.get_links() | where-object {if ($_.innerText){$_.innerText.contains($control)}}
$link.click()
while ($ie.Busy)
{
sleep -Milliseconds 100
}
# NEED outerHTML of new page. CURRENTLY it is working for some.
$ie.Document.body.outerHTML > d:\med$control.txt
}
}
$controls = "Sporanox"
getStringMatch