Change Credential Retrieval in SSRS with powershell - powershell

I want to change SSRS data source credential retrieval from using the following credentials to without any credentials with powershell and script fails.
I want to change value 'Store' to 'None' according to this article:
https://learn.microsoft.com/en-us/dotnet/api/reportservice2010.credentialretrievalenum?view=sqlserver-2016#ReportService2010_CredentialRetrievalEnum_None
This is my code:
$uri ='http://ServerName/ReportServer/ReportService2010.asmx?wsdl'
$reporting = New-WebServiceProxy -uri $uri -UseDefaultCredential -namespace "ReportingWebService"
$DataSources = $reporting.ListChildren('/', $true) | Where-Object {$_.Name -eq "DataSourceName"}
foreach($Object in $DataSources) {
$dataSource =$reporting.GetDataSourceContents($Object.path)
#$dataSource.CredentialRetrieval="None"
$dataSource.CredentialRetrieval=[ReportingWebService.CredentialRetrievalEnum]::None
$reporting.SetDataSourceContents($Object.path,$dataSource)
}
This is the error:
Exception calling "SetDataSourceContents" with "2" argument(s): "The combination of values for the fields UserName and CredentialRetrieval are not valid. --->
Microsoft.ReportingServices.Diagnostics.Utilities.InvalidElementCombinationException: The combination of values for the fields UserName and CredentialRetrieval are not valid."
At line:13 char:4
+ $reporting.SetDataSourceContents($Object.path,$dataSource)
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : SoapException

The issue was that i actually did not change existent credential retrieval settings 'Store' with required Username parameter.
To resolve it i should create new data source definition with new credential retrieval settings and apply it to my data source:
$uri ='http://servername/ReportServer/ReportService2010.asmx?wsdl'
$reporting = New-WebServiceProxy -uri $uri -UseDefaultCredential
$type=$reporting.GetType().Namespace
$DataSources = $reporting.ListChildren('/', $true) | Where-Object {$_.Name -eq "Data source name"}
foreach($Object in $DataSources) {
$dataSource =$reporting.GetDataSourceContents($Object.path)
$dataSourceDefinitionType = ($type + '.DataSourceDefinition');
$dataSourceDefinition = New-Object ($dataSourceDefinitionType);
$dataSourceDefinition.Extension = $dataSource.Extension; #get data from existent data source definition
$dataSourceDefinition.ConnectString = $dataSource.ConnectString #get data from existent data source definition
$credentialRetrievalDataType = ($type + '.CredentialRetrievalEnum');
$credentialRetrieval = new-object ($credentialRetrievalDataType);
$credentialRetrieval.value__ = 3;
$dataSourceDefinition.CredentialRetrieval = $credentialRetrieval;
$dataSourceDefinition.WindowsCredentials = $dataSource.WindowsCredentials; #get data from existent data source definition
$dataSourceDefinition.Enabled = $dataSource.Enabled; #get data from existent data source definition
$dataSourceDefinition.EnabledSpecified = $dataSource.EnabledSpecified; #get data from existent data source definition
$reporting.SetDataSourceContents($Object.path,$dataSourceDefinition)
}

Related

% : You cannot call a method on a null-valued expression

I think I've found unexplainable in PowerShell scripting. Let me describe the problem below:
I created a function that will query VSTS and will output back the amount of bugs that contain specific tags.
function GetBugsFromVSTS($applicationName, $first_url, $second_url, $query) {
#Building the body of the HTTP request to VSTS endpoint
$bodyOfRequest = $query | ConvertTo-Json
#Building headers of the HTTP request to VSTS endpoint
$headers = #{
'Content-Type'='application/json'
'Accept'='application/json'
'Authorization' = '' + $vsts_access_token + ''
}
$getBugs = Invoke-RestMethod -Uri $first_url `
-Method Post `
-Body $bodyOfRequest `
-Headers $headers | ConvertTo-Json -Depth 100
$json_decoded = $getBugs | ConvertFrom-Json
if ($json_decoded.workItems -eq $null) {
Write-Host "$applicationName Json decoded workitems are equal null" -ForegroundColor Red
} else {
Write-Host "$applicationName Json decoded workitems are not null" -ForegroundColor Green
$json_decoded.workItems | % {
$bug_id = $_.id
Write-Host $bug_id
}
}
$json_decoded.workItems | % {
$bug_id = $_.id
$url = ($second_url +$bug_id)
$getVstsBugState = Invoke-RestMethod -Uri $url -Method Get -Headers $headers
[PSCustomObject]#{
"Application Name" = $applicationName
"Id" = $bug_id;
"State" = $getVstsBugState.fields.'System.State';
"Reason" = $getVstsBugState.fields.'System.Reason';
"Severity" = $getVstsBugState.fields.'Microsoft.VSTS.Common.Severity'.Substring(4);
"AssignedTo" = $getVstsBugState.fields.'System.AssignedTo'.displayName
}
}
}
When I try to run it
$application = "MyBeautifulApp"
$application_first_url = "https://test.visualstudio.com/72L80E4b-1583-45c1-b669-d8de6133V895/_apis/wit/wiql?api-version=1.0"
$application_second_url = "https://test.visualstudio.com/72L80E4b-1583-45c1-b669-d8de6133V895/_apis/wit/workItems/"
$application_query = #{"query" = "SELECT [System.Id],[System.WorkItemType],[System.Title],[System.AssignedTo],[System.State] FROM WorkItems WHERE [System.TeamProject] = #project AND [System.WorkItemType] = 'Bug' AND [System.Title] CONTAINS 'Test' AND [System.TAGS] CONTAINS 'Test'"}
GetBugsFromVSTS $application $application_first_url $application_second_url $application_query
} catch {
Write-Warning "##vso[task.logissue type=warning;]Some problem occured querying MyBeautifulApp application. Please see below for error details"
$_
}
The most interesting part here is that I'm getting this really weird error message
WARNING: ##vso[task.logissue type=warning;]Some problem occured
querying MyBeautifulApp application. Please see below for error
details
% : You cannot call a method on a null-valued expression.
For the sake of test I added if..else clause to test that $json_decoded.workItems are not equal null, and that verification passes. If I run the code, full output will be
MyBeautifulApp Json decoded workitems are not null
9805
10330
10331
10371
10372
10373
10374
WARNING: ##vso[task.logissue type=warning;]Some problem occured querying MyBeautifulApp application. Please see below for error details
% : You cannot call a method on a null-valued expression. line 29
+ $json_decoded.workItems | % {
+ ~~~
+ CategoryInfo : InvalidOperation: (:) [ForEach-Object], RuntimeException
+ FullyQualifiedErrorId : InvokeMethodOnNull,Microsoft.PowerShell.Commands.ForEachObjectCommand
How is it possible that the first verification for $json_decoded.workItems (line 23) is not indicating that variable equals null, whereas the second statement (line 29) shows that it's null?
The problem isn't $json_decoded.workItems, the problem happens inside the script block passed to % / ForEach-Object:
Since you're using an enclosing try / catch handler, the offending individual statement inside the block is, unfortunately, not pinpointed in the error message.
However, given that there's only one method call in your block, the offending line can be inferred:
"Severity" = $getVstsBugState.fields.'Microsoft.VSTS.Common.Severity'.Substring(4);
In other words: $getVstsBugState.fields.'Microsoft.VSTS.Common.Severity' evaluates to $null, which is why the .Substring() method call fails.

Dynamics CRM Export Solution (not on-premises)

I want to export a Dynamics CRM 365 solution. Tools like the ALM Toolkit e.g. didn't worked.
My Questions:
1) Is it possible to export the entire CRM365 solution by powershell at all?
2) If it is not possible by powershell - is it possible by c#?
I can connect to the crm withouth problems by powershell. But If I try to call
When I call this:
$domain = "https://mypath.com"
$username = "user"
$password = "password"
$secPassword = New-Object -TypeName System.Security.SecureString
$password.ToCharArray() | ForEach-Object {$secPassword.AppendChar($_)}
$credentials = new-object -typename System.Management.Automation.PSCredential -argumentlist $username, $secPassword
$conn = Get-CrmConnection -Url "https://mypath.com" -Credential $credentials
$exportPath = "C:\Users\xy\Data"
Import-Module "C:\Users\xy\Scripts\Adxstudio.Xrm.PowerShell\Adxstudio.Xrm.PowerShell.dll"
Export-CrmContent -Connection $conn -OutputPath $exportPath -Uncompressed -Generalized
I get the following error:
Export-CrmContent : Metadata Contains A Reference That Cannot Be Resolved: "https://mypath/XRMServices/2011/Organization.svc?wsdl=wsdl0".
In C:\Users\my.ps1:14 Char:1
+ Export-CrmContent -Connection $conn -OutputPath $exportPath -Uncompre ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [Export-CrmContent], InvalidOperationException
+ FullyQualifiedErrorId : System.InvalidOperationException,Adxstudio.Xrm.PowerShell.Cmdlets.ExportCrmContent
But if I set up the $conn by using this:
$conn= Get-CrmConnection -OrganizationName MyOrg -DeploymentRegion MyRegion -OnLineType Office365 -Credential $credentials
I can get the organizations without problems. But when I try to call the export method with this connection I get:
The Parameter "$conn" cannot be bound. The value "Microsoft.Xrm.Tooling.Connector.CrmServiceClient" of the type "Microsoft.Xrm.Tooling.Connector.CrmServiceClient" can't be converted to "Adxstudio.Xrm.PowerShell.Cmdlets.PsCrmConnection".
Are there any ideas to solve one of the both problems to export the crm solution?
Not tried the Powershell approach, but I've achieved this using C# in the past.
static void ExportUnManagedSolutions(IOrganizationService service, String directory)
{
//Find all the solutions
QueryExpression query = new QueryExpression
{
EntityName = "solution",
ColumnSet = new ColumnSet("friendlyname", "uniquename", "version"),
Criteria = new FilterExpression()
{
Conditions =
{
//Unmanaged solutions only
new ConditionExpression("ismanaged", ConditionOperator.Equal, false),
//These are special CRM solutions, which are marked as unmanaged but cant actually be exported
new ConditionExpression("friendlyname", ConditionOperator.NotEqual, "Active Solution"),
new ConditionExpression("friendlyname", ConditionOperator.NotEqual, "Default Solution"),
new ConditionExpression("friendlyname", ConditionOperator.NotEqual, "Basic Solution"),
}
}
};
EntityCollection solutions = service.RetrieveMultiple(query);
//For each solution found
foreach (Entity s in solutions.Entities)
{
Console.WriteLine("Exporting " + s["friendlyname"]);
//Perform a solution export
ExportSolutionRequest request = new ExportSolutionRequest();
request.Managed = false;
request.SolutionName = (String)s["uniquename"];
ExportSolutionResponse response = (ExportSolutionResponse)service.Execute(request);
byte[] exportXml = response.ExportSolutionFile;
string filename = (String)s["uniquename"] + " " + (String)s["version"] + ".zip";
//This assumes the file directory already exists
File.WriteAllBytes(directory + filename, exportXml);
Console.WriteLine("Solution exported to {0}.", directory + filename);
}
}

Powershell script can't find URL

I have a powershell that kicks off a workflow in SharePoint but my system is not allowing me to run it. The error I'm getting is as follows:
Get-SPWeb: Cannot find an SPWeb object with id or URL: xxx.com and site Url xxx.com
At C:\cert.ps1:1 char:17
+ $web = Get-SPWeb <<<< -Identity "xxx.com"
+ CategoryInfo : InvalidData (Microsoft.Share....SPCmdletGetWeb:SPCmdletGetWeb) [Get-SPWeb], SPCmdletPipeBindException
+ FullyQualifiedErrorId : Microsoft.SharePoint.Powershell.SPCmdletGetWeb
I tried adding Add-PSSnapin Microsoft.Sharepoint.Powershell but I the get an error saying its already been added.
Here's the script:
$web = Get-SPWeb -Identity "xxx.com"
$manager = $web.Site.WorkFlowManager
$list = $web.Lists["Certificate Tracking"]
$assoc = $list.WorkflowAssociations.GetAssociationByName("Certificate Notification","en-US")
$view = $list.Views["All Items"] #All Items
$items = $list.GetItems($view)
$data = $assoc.AssociationData
foreach ($item in $items) {
$wf = $manager.StartWorkFlow($item,$assoc,$data)
}
$web.Dispose()
The -Identity parameter for Get-SPWeb can be either a full or relative path, or a path with a wildcard * character. Additionally:
The identity param expects a valid URL in the form http://server_name or a relative path in the form of /SubSites/MySubSite.
Try this instead using the -Site param, which I think might be what you're looking for:
Get-SPWeb -Site http://sitename/sites/site1

Create Multiple Document Sets from List

I need a document set create for every name in this SharePoint 2010 list. The Document set title is the first and last name of the person and the document set has committee name property that needs to be set as well. The committee name comes from the same SharePoint list.
I don't understand wrong with my code:
$ErrorActionPreference = "Stop"
$url = "http://SERVER/etest"
$listName = "Advisory Committee"
$doclib = "TACM Application Docments"
$web = Get-SPWeb $url;
$list = $web.Lists[$listName];
$item = $list.Items;
$item | ForEach-Object {
$fullName = $_['Last Name'] + ", " + $_['First Name']
$committeeName = $_['Committee Name']
$cType = $list.ContentTypes["Document Set"]
[Hashtable]$docsetProperties = #{"Committee Name"=$committeeName}
$newDocumentSet = [Microsoft.Office.DocumentManagement.DocumentSets.DocumentSet]::Create($doclib.RootFolder,
$fullName,$cType.Id, $docsetProperties)
}
$web.Dispose()
I get the following error:
ForEach-Object : Cannot find an overload for "Create" and the argument count: "4".
At C:\Users\ev\desktop\docset.ps1:10 char:23
+ $item | ForEach-Object <<<< {
+ CategoryInfo : NotSpecified: (:) [ForEach-Object], MethodException
+ FullyQualifiedErrorId : MethodCountCouldNotFindBest,Microsoft.PowerShell
.Commands.ForEachObjectCommand
DocumentSet.Create method expects the first parameter to be a folder (SPFolder type):
parentFolder
Type: Microsoft.SharePoint.SPFolder
The folder in which to create the new DocumentSet object.
In your case you are passing an invalid object $doclib.RootFolder since $doclib is a string variable, probably you want something like this:
$doclibName = "TACM Application Docments"
$doclib = $web.Lists[$doclibName];
$newDocumentSet = [Microsoft.Office.DocumentManagement.DocumentSets.DocumentSet]::Create($doclib.RootFolder,$fullName,$cType.Id, $docsetProperties)
Example
$url = "http://contoso.intranet.com"
$listTitle = "Documents"
$web = Get-SPWeb $url;
$list = $web.Lists[$listTitle]
$docSetContentType = $list.ContentTypes["Document Set"]
[Hashtable]$docSetProperties = #{}
$docSetName = "Archive"
$docSet = [Microsoft.Office.DocumentManagement.DocumentSets.DocumentSet]::Create($list.RootFolder,$docSetName,$docSetContentType.Id, $docSetProperties)
$web.Dispose()
How to add Document Set content type into library
Go to Library Settings, then click Advanced Settings
set Allow management of content types? to Yesand click Ok button
click Add from existing site content types link and select
Document Set content type, then click Ok button

PowerShell: Exception calling "GetListItems" with "7" argument(s)

Attempting to Get List Items from SharePoint using PowerShell.
I used the example from here Windows PowerShell Blog, modified it to use with my site. Now I get the following error:
Exception calling "GetListItems" with "7" argument(s): "Exception of type 'Microsoft.SharePoint.SoapServer.SoapServerException' was thrown."
At line:30 char:1
+ $list = $service.GetListItems($listName, "", $query, $viewFields, $rowLimit, $qu ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : SoapException
Script I am using:
# The uri refers to the path of the service description, e.g. the .asmx page
$uri = "http://SITE/sites/DefaultCollection/Engineering/Subsite%20(UK)/_vti_bin/lists.asmx"
# Create the service
$service = New-WebServiceProxy -Uri $uri -Namespace SpWs -UseDefaultCredential
# The name of the list
$listName = "Test1"
# Create xml query to retrieve list.
$xmlDoc = new-object System.Xml.XmlDocument
$query = $xmlDoc.CreateElement("Query")
$viewFields = $xmlDoc.CreateElement("ViewFields")
$queryOptions = $xmlDoc.CreateElement("QueryOptions")
$query.set_InnerXml("FieldRef Name='Text1'")
$rowLimit = "10"
$list = $null
$service = $null
try
{
$service = New-WebServiceProxy -Uri $uri -Namespace SpWs -UseDefaultCredential
}
catch
{
Write-Error $_ -ErrorAction:'SilentlyContinue'
}
$list = $service.GetListItems($listName, "", $query, $viewFields, $rowLimit, $queryOptions, "")
if($service -ne $null)
{
try
{
$list = $service.GetListItems($listName, "", $query, $viewFields, $rowLimit, $queryOptions, "")
}
catch
{
Write-Error $_ -ErrorAction:'SilentlyContinue'
}
}
Anyone tried this before? How can I resolve this issue?
Here's the solution worked for me..
Add "?WSDL" to the end of $uri string
$uri = "http://SITE/sites/DefaultCollection/Engineering/Subsite%20(UK)/_vti_bin/lists.asmx?WSDL"
According to this link:To return a service description of a Web service that was created by using ASP.NET, append "?WSDL" to the URL of the Web service (for example, http://www.ss64.com/MyWebService.asmx?WSDL)
The line it is throwing the error at is:
$list = $service.GetListItems($listName, "", $query, $viewFields, $rowLimit, $queryOptions, "")
That line is not caught, but here is a similar issue throwing the same error. If you want to try and get a better exception, wrap the line in another try catch:
try{
$list = $service.GetListItems($listName, "", $query, $viewFields, $rowLimit, $queryOptions, "")
}
catch{
[System.Exception]
write-host ($_.Exception).Message
}
Please make sure to add "?WSDL" to your URI which is why the code breaks. Pretends like it doesn't know the definition of the function (atleast I guess)...
Like the one below. I was surprised to see this made my code work. Weird..
$uri = "http://<>/sites/DefaultCollection/Engineering/Subsite%20(UK)/_vti_bin/lists.asmx?WSDL"