Set the Defaultvalue for a site column in SharePoint using Powershell - powershell

I am trying to set the default value for a site column.
I found following code to set the default value of a column in library, but I could not find a way to set the site column using MetadataDefaults
add-pssnapin microsoft.sharepoint.powershell -ea silentlycontinue
[Reflection.Assembly]::LoadwithPartialName("Microsoft.Office.DocumentManagement")
$web = get-spweb http://mysitecoll/sites/Nate
$lib = $web.Lists["Shared Documents"]
$metadataDefaults = New-Object -TypeName Microsoft.Office.DocumentManagement.MetadataDefaults -ArgumentList $web
foreach ($oneFolder in $lib.Folders) {
Write-Host ("Folder: {0}" -f $oneFolder.Url)
$folderObject = $web.GetFolder($oneFolder.Url)
$folderDefaultValue = $metadataDefaults.GetFieldDefault($folderObject, "ColumnName")
Write-Host (" Default Value: {0}" -f $folderDefaultValue)
}
$web.dispose()
Help reference for Metadata Default members
https://msdn.microsoft.com/EN-US/library/office/microsoft.office.documentmanagement.metadatadefaults_members.aspx
above code taken from http://blogs.technet.com/b/okoestner/archive/2011/12/01/fetch-default-values-of-folders-with-powershell.aspx

$web = $Global:site.RootWeb
$field = $web.Fields["FieldName"]
$field.DefaultValue = GUID for the value
$field.Update($true)
The above code worked for updating the Site columns default value

Related

Basic question about using PowerShell to modify user assignments in SSRS

I have somple experience in PowerShell but I don't have experience in using it to automate SQL Server Reporting Service. Basically I want to assign a user a role to a particular report object in SSRS. I have found the following codes in
SSRS: How to assign multiple users a role to a report quickly?
It seems a good start for creating my script.
function Add-SSRSUserRole
(
[string]$reportServerUrl,[string]$userGroup,[string]$requiredRole,[string]$folder,[bool]$inheritFromParent
)
{
#Ensure we stop on errors
$ErrorActionPreference = "Stop";
#Connect to the SSRS webservice
$ssrs = New-WebServiceProxy -Uri "$reportServerUrl" -UseDefaultCredential;
$namespace = $ssrs.GetType().Namespace;
$changesMade = $false;
#Look for a matching policy
$policies = $ssrs.GetPolicies($folder, [ref]$inheritFromParent);
if ($policies.GroupUserName -contains $userGroup)
{
Write-Host "User/Group already exists. Using existing policy.";
$policy = $policies | where {$_.GroupUserName -eq $userGroup} | Select -First 1 ;
}
else
{
#A policy for the User/Group needs to be created
Write-Host "User/Group was not found. Creating new policy.";
$policy = New-Object -TypeName ($namespace + '.Policy');
$policy.GroupUserName = $userGroup;
$policy.Roles = #();
$policies += $policy;
$changesMade = $true;
}
#Now we have the policy, look for a matching role
$roles = $policy.Roles;
if (($roles.Name -contains $requiredRole) -eq $false)
{
#A role for the policy needs to added
Write-Host "Policy doesn't contain specified role. Adding.";
$role = New-Object -TypeName ($namespace + '.Role');
$role.Name = $requiredRole;
$policy.Roles += $role;
$changesMade = $true;
}
else
{
Write-Host "Policy already contains specified role. No changes required.";
}
#If changes were made...
if ($changesMade)
{
#...save them to SSRS
Write-Host "Saving changes to SSRS.";
$ssrs.SetPolicies($folder, $policies);
}
Write-Host "Complete.";
}
[string]$url = "http://localhost/ReportServer/ReportService2006.asmx?wsdl";
Add-SSRSUserRole $url "Everyone" "Browser" "/MyReportFolder" $true;
Add-SSRSUserRole $url "Domain\User" "Browser" "/MyReportFolder" $true;
Now I have two elementary questions:
Do I need any SSRS modules to be installed in my PowerShell in order to run the above script?
The sample code above assign a permission to a folder. What changes are required if I want to assign permissions to a report object directly instead?
Thanks for your response in advance,

SharePoint Online Powershell Folder creation

I need to be able to script folder creation from a csv into a SharePoint Online document library with each folder with permission inheritance disabled and for different user to each folder to be added.
The following code can create the folders and disable the inheritance but it seems to try add a group but not a user. How to make it add a user instead?
Thanks.
### Get the user credentials
$credential = Get-Credential
$username = $credential.UserName
$password = $credential.GetNetworkCredential().Password
$securePassword = ConvertTo-SecureString $password -AsPlainText -Force
### Input Parameters
$url = 'URL HERE'
$csvfilepath='C:\Scripts\data.csv'
$libname ='BUS61'
### References
# Specified the paths where the dll's are located.
Add-Type -Path 'C:\Scripts\SPOCmdlets\Microsoft.SharePoint.Client.dll'
Add-Type -Path 'C:\Scripts\SPOCmdlets\Microsoft.SharePoint.Client.Runtime.dll'
### CreateFolder with Permissions Function
function CreateFolderWithPermissions()
{
# Connect to SharePoint Online and get ClientContext object.
$clientContext = New-Object Microsoft.SharePoint.Client.ClientContext($url)
$credentials = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($username, $securePassword)
$clientContext.Credentials = $credentials
Function GetRole
{
[CmdletBinding()]
param
(
[Parameter(Mandatory = $true, Position = 1)]
[Microsoft.SharePoint.Client.RoleType]$rType
)
$web = $clientContext.Web
if ($web -ne $null)
{
$roleDefs = $web.RoleDefinitions
$clientContext.Load($roleDefs)
$clientContext.ExecuteQuery()
$roleDef = $roleDefs | Where-Object { $_.RoleTypeKind -eq $rType }
return $roleDef
}
return $null
}
# Get the SharePoint web
$web = $clientContext.Web;
$clientContext.Load($web)
#Get the groups
$groups = $web.SiteGroups
$clientContext.Load($groups)
$clientContext.ExecuteQuery()
#Read CSV File and iterate
$csv = Import-CSV $csvfilepath
foreach ($row in $csv)
{
#Create Folder
$folder = $web.Folders.Add($libname + "/" + $row.Folder)
$clientContext.Load($folder)
$clientContext.ExecuteQuery()
#Assign Role
$group = $groups.GetByName($row.Group)
$clientContext.Load($group)
$clientContext.ExecuteQuery()
$roleType= $row.Role
$roleTypeObject = [Microsoft.SharePoint.Client.RoleType]$roleType
$roleObj = GetRole $roleTypeObject
$usrRDBC = $null
$usrRDBC = New-Object Microsoft.SharePoint.Client.RoleDefinitionBindingCollection($clientContext)
$usrRDBC.Add($roleObj)
# Remove inherited permissions
$folder.ListItemAllFields.BreakRoleInheritance($false, $true)
$clientContext.Load($folder.ListItemAllFields.RoleAssignments.Add($group, $usrRDBC))
$folder.Update()
$clientContext.ExecuteQuery()
# Display the folder name and permission
Write-Host -ForegroundColor Blue 'Folder Name: ' $folder.Name ' Group: '$row.Group ' Role: ' $roleType;
}
}
#Execute the function
CreateFolderWithPermissions
Let's assume that you will define user login in your CSv file. Than you have to change the line:
$group = $groups.GetByName($row.Group)
to
$user = $web.EnsureUser($row.User)
and replace all references to $group variable with $user
More generic approach for searching for a user (with for example display name) would be using Utility.ResolvePrincipal method:
[Microsoft.SharePoint.Client.Utilities.Utility]::ResolvePrincipal($clientContext, $web, "DisplayName", ([Microsoft.SharePoint.Client.Utilities.PrincipalType]::User), ([Microsoft.SharePoint.Client.Utilities.PrincipalSource]::All), $null, $false)

SSRS and powershell: Parameter not accepted

I use Powershell to run several reports on Microsoft SQL Report Services and to save the results to a Word doc. I have a script with functions that handle communications with the Report Server:
## File "qrap-functions.ps1"
function GetRSConnection($server, $instance)
{
$User = "xxxx"
$PWord = ConvertTo-SecureString -String "yyyy" -AsPlainText -Force
$c = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $User, $PWord
$reportServerURI = "http://" + $server + "/" + $instance + "/ReportExecution2005.asmx?WSDL"
$RS = New-WebServiceProxy -Class 'RS' -NameSpace 'RS' -Uri $reportServerURI -Credential $c
$RS.Url = $reportServerURI
return $RS
}
function GetReport($RS, $reportPath)
{
$reportPath = "/" + $reportPath
#$reportPath
$Report = $RS.GetType().GetMethod("LoadReport").Invoke($RS, #($reportPath, $null))
$parameters = #()
$RS.SetExecutionParameters($parameters, "nl-nl") > $null
return $report
}
function AddParameter($params, $name, $val)
{
$par = New-Object RS.ParameterValue
$par.Name = $name
$par.Value = $val
$params += $par
return ,$params
}
function GetReportInFormat($RS, $report, $params, $format, $saveas)
{
$deviceInfo = "<DeviceInfo><NoHeader>True</NoHeader></DeviceInfo>"
$extension = ""
$mimeType = ""
$encoding = ""
$warnings = $null
$streamIDs = $null
$RS.SetExecutionParameters($params, "nl-nl") > $null
$RenderOutput = $RS.Render($format,
$deviceInfo,
[ref] $extension,
[ref] $mimeType,
[ref] $encoding,
[ref] $warnings,
[ref] $streamIDs
)
$Stream = New-Object System.IO.FileStream($saveas), Create, Write
$Stream.Write($RenderOutput, 0, $RenderOutput.Length)
$Stream.Close()
}
Then, I have a script that executes a report containing the financial quarterly data. This script runs fine:
## File "qrap-financieel.ps1"
. "./qrap-functions.ps1"
$saveas = "e:\test\financieel.doc"
$RS = GetRSConnection -server "MSZRDWH" -instance "reportserver_acc"
$report = GetReport -RS $RS -reportPath "kwartaalrapportage/kwartaalrapportage financieel"
$params = #()
$kwartaal = "[Periode Maand].[Jaar Kwartaal].&[2015-2]"
$kptc = "[Kostenplaats].[Team code].&[2003]"
$params = AddParameter -params $params -name "PeriodeMaandJaarKwartaal" -val $kwartaal
$params = AddParameter -params $params -name "KostenplaatsTeamcode" -val $kptc
GetReportInformat -RS $RS -report $report -params $params -format "WORD" -saveas $saveas
The values for $kwartaal and $kptc are hard-coded here, but are parameters in the actual version of this script. Besides the financial quarterly, we have three other quarterly reports that need to be output by this script.
Two of these run fine, in the fourth I can't seem to get one of the parameters right. The script for that one is:
## File "qrap-zorglog.ps1"
. "./qrap-functions.ps1"
$RS = GetRSConnection -server "MSZRDWH" -instance "reportserver_acc"
$report = GetReport -RS $RS -reportPath "kwartaalrapportage/kwartaalrapportage zorglogistiek"
$s = "Urologie"
$saveas = "e:\test\ZL Urologie.doc"
$params = #()
$kwartaal = "[Periode Maand].[Jaar Kwartaal].&[2015-2]"
$params = AddParameter -params $params -name "HoofdspecialismeSpecialismeOms" -val "[Hoofdspecialisme].[Specialisme Oms].&[$s]"
$params = AddParameter -params $params -name "PeriodeMaandJaarKwartaal" -val $kwartaal
$params = AddParameter -params $params -name "WachttijdenSpecialismeSpecialisme" -val "[Wachttijden Specialisme].[Specialisme].&[$s]"
$params = AddParameter -params $params -name "SpecialisatieGroeperingSpecialisatieGroeperingOms" -val "[Specialistie Groepering].[Specialistie Groepering Oms].&[$s]"
$params = AddParameter -params $params -name "AanvragendSpecialismeSpecialismeOms" -val "[AanvragendSpecialisme].[Specialisme Oms].&[$s]"
GetReportInformat -RS $RS -report $report -params $params -format "WORD" -saveas $saveas
When I execute this script, I get this error:
Exception calling "Render" with "7" argument(s): "System.Web.Services.Protocols.SoapException: This report requires a
default or user-defined value for the report parameter 'HoofdspecialismeSpecialismeOms'. To run or subscribe to this
report, you must provide a parameter value. ---> Microsoft.ReportingServices.Diagnostics.Utilities.ReportParameterValueNot
SetException: This report requires a default or user-defined value for the report parameter
'HoofdspecialismeSpecialismeOms'. To run or subscribe to this report, you must provide a parameter value.
I clearly DO supply a value for 'HoofdspecialismeSpecialismeOms'; I've previously noticed that this error also is thrown when the parameter is not in the expected format. This format, since the
report filter is based on a hierarchy in an SSAS cube, looks like this: [hierarchy].[sub-level].&[member]. I've ensured that [Hoofdspecialisme].[Specialisme Oms].&[$s] is the correct format by
looking it up in the query that populates the prompt in SSRS. The report does display data when run through SSRS - and taking a parameter from the prompt.
I did notice that this parameter allows multiple selection. However, I don't believe this leads to the error because that is also true for AanvragendSpecialismeSpecialismeOms.
Any idea why this one parameter fails to be fed into the report when calling GetReportInformat?
Have you tried
function AddParameter($params, $name, $val)
{
$par = New-Object RS.ParameterValue
$par.Name = $name
$par.Value = $val
$params += $par
return ,$params
# ^Removing this comma?
}
As well as declaring the data types explicitly for your parameters?
function AddParameter([Array]$params, [String]$name, [String]$val)
{
$par = New-Object RS.ParameterValue
$par.Name = $name
$par.Value = $val
$params += $par
return ,$params
}
Also, with so many user-defined helper functions calling imported types that call methods and set properties to a report we can't see, it can get a little difficult to help troubleshoot in-depth for this specific report you're getting an error on. It looks like you've tried moving the line around in the order which sounds to me like you might have an issue with how that specific report parses the values you input through RS.ParameterValue so maybe take a look at if it accepts the string you set in -val for your AddParameter user defined function.
Edit:
From https://social.msdn.microsoft.com/Forums/sqlserver/en-US/e38b4a34-c780-43bb-8321-15f96d0938a9/exception-calling-render-systemwebservicesprotocolssoapexception-one-or-more-data-source?forum=sqlreportingservices
This error is generated when you are attempting to run a report in which one or more of the data sources are set to "prompt" credentials. This means we do not use your Windows credentials automatically, but rather you need to supply a different set of credentials which are used only for the data source.
Sounds like you might need to put aside the script and check if the report is different.
I've finally figured it out: The failing prompt had a multi-select enabled. And when filling in a multi-select, SSRS expects a list of values. When only given one string, the string is ignored and the parameter is assumed blank.
To feed it a list, we must do:
$multival = New-Object System.Collections.Specialized.StringCollection
$multival.Add("[Hoofdspecialisme].[Specialisme Oms].&[$s]")
[snip]
$params = AddParameter -params $params -name "HoofdspecialismeSpecialismeOms" -val $multival
Found the answer thanks to this question:
How to pass multiple value parameter to reporting services report via powershell

Nesting dynamic parameters in PowerShell

I am working on a function that will insert a row into a SQL database. It is basically a simple change log to help me track what is changed on my various SQL instances. As part of this, I want to have the following parameters:
Timestamp
Server
Instance
Change
I've got the Timestamp, Change, and Server all figured out, but the Instance is giving me some trouble. The Server parameter is dynamic, as it pulls a list of SQL servers from my inventory. I then want the value of that parameter to be used in another dynamic parameter, which pulls a list of the instances that are on that server (also from my inventory). Here is what I have for the dynamic portion:
DynamicParam {
if (!(Get-Module sqlps)){ Pop-Location; Import-Module sqlps -DisableNameChecking; Push-Location }
$inventoryinstance = 'ServerName'
$newparams = New-Object System.Management.Automation.RuntimeDefinedParameterDictionary
$server_query = 'SELECT [Name] FROM [ServerInventory].[dbo].[Servers] WHERE [TypeID] = 1 ORDER BY [Name]'
$servers = Invoke-Sqlcmd -serverinstance $inventoryinstance -query $server_query -connectiontimeout 5
# Populate array
$serverlist = #()
foreach ($servername in $servers.Name) {
$serverlist += $servername
}
$attributes = New-Object System.Management.Automation.ParameterAttribute
$attributes.ParameterSetName = "__AllParameterSets"
$attributes.Position = 1
$attributes.Mandatory = $true
$attributes.HelpMessage = "The server the change was made on"
# Server list parameter setup
if ($serverlist){ $servervalidationset = New-Object System.Management.Automation.ValidateSetAttribute -ArgumentList $serverlist }
$serverattributes = New-Object -Type System.Collections.ObjectModel.Collection[System.Attribute]
$serverattributes.Add($attributes)
if ($serverlist){ $serverattributes.Add($servervalidationset) }
$serverob = New-Object -Type System.Management.Automation.RuntimeDefinedParameter("Server", [String], $serverattributes)
$newparams.Add("Server", $serverob)
$instance_query = "SELECT [Name] FROM [ServerInventory].[dbo].[SQLInstances] WHERE [ServerID] = (SELECT [ServerID] FROM [ServerInventory].[dbo].[Servers] WHERE [Name] = '$($PSBoundParameters.Server)')"
$instances = Invoke-Sqlcmd -serverinstance $inventoryinstance -query $instance_query -connectiontimeout 5
# Populate array
$instancelist = #()
foreach ($instancename in $instances.Name) {
$instancelist += $instancename
}
$attributes = New-Object System.Management.Automation.ParameterAttribute
$attributes.ParameterSetName = "__AllParameterSets"
$attributes.Position = 2
$attributes.Mandatory = $false
$attributes.HelpMessage = "The instance the change was made on, do not specify for server-level changes"
# Server list parameter setup
if ($instancelist){ $instancevalidationset = New-Object System.Management.Automation.ValidateSetAttribute -ArgumentList $instancelist }
$instanceattributes = New-Object -Type System.Collections.ObjectModel.Collection[System.Attribute]
$instanceattributes.Add($attributes)
if ($instancelist){ $instanceattributes.Add($instancevalidationset) }
$instanceob = New-Object -Type System.Management.Automation.RuntimeDefinedParameter("Instance", [String], $instanceattributes)
$newparams.Add("Instance", $instanceob)
return $newparams
}
Everything seems to be working, except the value for the instance variable doesn't autocomplete. Is it possible to use the value of one dynamic parameter to generate another?

Changing User Profile Property for all the users in sharepoint 2010 using powershell

I want to change the edit setting and Display setting value of a user profile property called Department for all users. Can someone please tell me how to do it.
I can get to the department property with this powershell. Right now this Property Edit Setting is DO not Allow Users to edit this property and I want to make it Editable for every user.
Add-PSSnapin "Microsoft.SharePoint.PowerShell" -ErrorAction SilentlyContinue
$mySiteUrl = "http://www.test.com/mysite"
$site = Get-SPSite $mySiteUrl
$context = Get-SPServiceContext $site
$profileManager = New-Object Microsoft.Office.Server.UserProfiles.UserProfileManager($context)
$userProfile = $profileManager.GetUserProfile("Test\822");
$userProfile.Properties | sort DisplayName | FT DisplayName,Name,#{Label="Type";Expression={$_.CoreProperty.Type}}
$userProfile["Department"].Value
$site.Dispose()
Thanks
I guess you mean this property, right?
The following script demonstrates how to set IsUserEditable sub property of Departments user profile property:
if ((Get-PSSnapin -Name Microsoft.SharePoint.PowerShell -ErrorAction SilentlyContinue) -eq $null)
{
Add-PsSnapin Microsoft.SharePoint.PowerShell
}
$siteUrl = "http://contoso.intranet.com/"
$site = Get-SPSite $siteUrl
$context = Get-SPServiceContext($site)
$profileConfigMgr = New-Object Microsoft.Office.Server.UserProfiles.UserProfileConfigManager($context)
$profilePropMgr = $profileConfigMgr.ProfilePropertyManager
$subtypePropMgr = $profilePropMgr.GetProfileSubtypeProperties("UserProfile")
$subtypeProp = $subtypePropMgr.GetPropertyByName("Department")
$subtypeProp.IsUserEditable = $true
$subtypeProp.Commit()
References
How to: Work with user profiles and organization profiles by using the server object model in SharePoint 2013