I want to export the Web part XML based on GUID to the local. I am trying to export from SharePoint 2013 using CSOM PowerShell. Anyone suggest on this?
function EnsureDirectory($exportFolderPath)
{
if ( -not (Test-Path $exportFolderPath) ) {New-Item $exportFolderPath -Type Directory | Out-Null}
}
function ExportAllWebParts()
{
$WebURL= ""
$ctx = New-Object Microsoft.SharePoint.Client.ClientContext($WebURL)
$Page = $ctx.web.GetFileByServerRelativeUrl("")
$ctx.Load($Page)
$ctx.ExecuteQuery()
$wpManager = $Page.GetLimitedWebPartManager([Microsoft.SharePoint.Client.WebParts.PersonalizationScope]::Shared)
$webparts = $wpManager.Webparts
$ctx.Load($webparts)
$ctx.ExecuteQuery()
if($webparts.Count -gt 0){
Write-Host "Looping through all webparts"
foreach($webpart in $webparts){
$exportPath = "" + "\" + $webpart.Title + ".xml"
$xwTmp = new-object System.Xml.XmlTextWriter($exportPath,$null);
$xwTmp.Formatting = 1;#Indent
$wpManager.ExportWebPart($webpart, $xwTmp);
$xwTmp.Flush();
$xwTmp.Close();
#$webpartXmlWriter = New-Object System.Xml.XmlTextWriter($fileName,$null)
#$webpartXmlWriter.Formatting = [System.Xml.Formatting]::Indented
#$wpManager.ExportWebPart($webpart,$webpartXmlWriter)
}
}
}
ExportAllWebParts
Related
I want to create a file and write content to the file.
The new file will create based on the total SWPO file exist. I tried this scirpt, I can create new file. But when I put only 1 $PO_Path file, it will create 2 new file. Actually those 2 file are the same but one of the file without $c. Like this
ID_ABC18XXR3CT123_.job
ID_ABC18XXR3CT123_AE.job
BUt if I put $PO_Path file more than 1, it works well.
Anyone can help me please. Thanks.
Function Create_OriJob
{
$BID = "18XXR3CT123"
$Job_Path = $Config_File.Automation_Config.Path.OriJob
$PO_Path = $Config_File.Automation_Config.Path.POfiles
if(Test-Path -Path "$PO_Path\*$BID*")
{
Write-Output "SWPO File Found"
# Start-Sleep -s 3
$PO_Content = Get-Content -path "$PO_Path\*$BID*"
$POfile = Get-ChildItem -Name "$PO_Path\*$BID*"
$Get_CRM = $PO_Content | Where-Object {$_ -like "*;CRM*"}
$CRM = $Get_CRM.Substring(5,2)
$CRM = $CRM.split()
$POCountry = Get-ChildItem -Name "$PO_Path"
$GetCountry = $POCountry.Substring(15,3)
$GetCountry = $GetCountry.split()
For($i = 0; $i -lt $POfile.Length; $i++){
try{
$po = $POfile[$i]
$c = $CRM[$i]
$cc = $GetCountry[$i]
New-Item -ItemType File -Path "$Job_Path\$JobType`_$Prefix$BID`_$c.job" -Force
$Title = $Config_File.Automation_Config.Out_Job.Title
$Auto = $Config_File.Automation_Config.Out_Job.Auto
$Proc = $Config_File.Automation_Config.Out_Job.Process
$Auto = $Config_File.Automation_Config.Out_Job.Auto
$PO_Conf = $Config_File.Automation_Config.Out_Job.PO
$BIDINFO = $Config_File.Automation_Config.Out_Job.BIDINFO
$BuildID = $Config_File.Automation_Config.Out_Job.BID
$PFX = $Config_File.Automation_Config.Out_Job.PFX
$CRM_Conf = $Config_File.Automation_Config.Out_Job.CRM
$CountryConf = $Config_File.Automation_Config.Out_Job.Country
$Platform = $Config_File.Automation_Config.Out_Job.Platform
$TSJobcreate = Get-Date
$Output_JOB = #"
<?xml version="1.0" encoding="UTF-8"?>
<$Title>
<$Auto>
<$Proc>$Auto</$Proc>
<$PO_Conf>$po</$PO_Conf>
</$Auto>
<$BIDINFO>
<$BuildID>$BID</$BuildID>
<$PFX>$Prefix</$PFX>
<$CRM_Conf>$c</$CRM_Conf>
<$CountryConf>$cc</$CountryConf>
</$BIDINFO>
<$Platform>
$All_SSID
</$Platform>
<Timestamp>
<JobCreate>$TSJobcreate</JobCreate>
</Timestamp>
</$Title>
"#
$Output_JOB | Out-File "$Job_Path\$JobType`_$Prefix$BID`_$c.job" -NoNewline
Write-Host "Output"
}
catch{
Write-Output "Something wrong!"
}
}
Write-Output "Continue to create operational job"
Create_OpJob
}
else{
Write-Host "SWPO Not Found, Do Error checking file"
Error_Monitoring
}
#Error_Monitoring
}
I am trying to download a folder child from a given TFS project.
All i have done so far is connecting to the server using a url https://.visualstudio.com , username, a password and listing all the projects.
This is my code so far:
Add-Type -Path "$path1\Microsoft.TeamFoundation.Client.dll"
Add-Type -Path "$path1\Microsoft.TeamFoundation.Common.dll"
Add-Type -Path "$path1\Microsoft.TeamFoundation.WorkItemTracking.Client.dll"
Add-Type -Path "$path1\Microsoft.TeamFoundation.VersionControl.Client.dll"
Add-Type -Path "$path1\Microsoft.TeamFoundation.ProjectManagement.dll"
Add-Type -Path "$path2\Microsoft.TeamFoundation.PowerTools.PowerShell.dll"
$tfsurl = 'https://something.visualstudio.com'
$username = 'someuser#outlook.com'
$password = 'somepasswd'
$_tfs_server =[Microsoft.TeamFoundation.Client.TfsTeamProjectCollectionFactory]::GetTeamProjectCollection($tfs_uri)
$cred = New-Object System.Net.NetworkCredential($username,$password)
$_tfs_server.Credentials = $cred
$_tfs_server.EnsureAuthenticated()
if($_tfs_server.HasAuthenticated){
Write-Host -ForegroundColor Green "Connected to Team Foundation Server [" $tfs_uri "]"
$tfsConfigurationServer = [Microsoft.TeamFoundation.Client.TfsConfigurationServerFactory]::GetConfigurationServer($tfs_uri)
$tpcService = $tfsConfigurationServer.GetService("Microsoft.TeamFoundation.Framework.Client.ITeamProjectCollectionService")
$sortedCollection = $tpcService.GetCollections() | Sort-Object -Property Name
foreach($col in $sortedCollection){
Write-Host $col.Name
}
$cssService = $_tfs_server.GetService("Microsoft.TeamFoundation.Server.ICommonStructureService3")
$sortedProjects = $cssService.ListAllProjects() | Sort-Object -Property Name
Write-Host "Listing Projects"
foreach($project in $sortedProjects){
Write-Host (" - " + $project.Name)
}
}
else {
return;
}
https://i.stack.imgur.com/iCXNQ.jpg
Simple code to get files from source control:
$teamProjectCollection=new-object Microsoft.TeamFoundation.Client.TfsTeamProjectCollection($tfsCollectionUrl,$cret)
$teamProjectCollection.EnsureAuthenticated()
$VersionControl = $teamProjectCollection.GetService([Microsoft.TeamFoundation.VersionControl.Client.VersionControlServer])
$workspace = $VersionControl.CreateWorkspace("BasicSccExamplePS", $VersionControl.AuthorizedUser);
$workspace.Map("$/Agile2015/ClassLibrary2", "D:\\temp\\BasicSccExample")
$workspace.Get()
To check whether folder/file exists, you can use GetItems() method:
$items=$VersionControl.GetItems("$/ScrumStarain/CustomCode/Properties2");
Write-Output $items.Items.Count
If($items.Items.Count -ne 0)
{
}
How do I reference a specific email address in this code it always directs to
the default email account. I have multiple email accounts in my outlook and I want to download emails from a different account which I want to reference by that email address . I have a feeling
$folder = $namespace.getDefaultFolder($olFolders::olFolderInBox)
has to be changed please give suggestions.
`[CmdletBinding(DefaultParameterSetName="All")] `
`Param(
[Parameter(Mandatory=$true,
Position=0,
HelpMessage='Folder path to store emails. Do not use quotation marks even if the path has spaces.',
ValueFromPipelineByPropertyName=$true
)]
[Alias("Destination", "Dest", "FullName")]
[String]$DestinationPath, `
[Parameter(ParameterSetName="All")]
[Parameter(Mandatory=$true,ParameterSetName="Unread")]
[Switch]$UnreadOnly,
[Parameter(ParameterSetName="Unread")]
[Switch]$MarkRead
)
#Removes invalid Characters for file names from a string input and outputs
the clean string
` #Similar to VBA CleanString() Method
#Currently set to replace all illegal characters with a hyphen (-)
Function Remove-InvalidFileNameChars {`
param(
[Parameter(Mandatory=$true, Position=0)]
[String]$Name
)
return [RegEx]::Replace($Name, "[{0}]" -f ([RegEx]::Escape([String][System.IO.Path]::GetInvalidFileNameChars())), '-')
}
#Test for destination folder nonexistence
if (!(Test-Path $DestinationPath)) {
#Set values for prompt and menu
$yes = New-Object System.Management.Automation.Host.ChoiceDescription "&Yes", `
"Confirmation Choice"
$no = New-Object System.Management.Automation.Host.ChoiceDescription "&No", `
"Negative Response"
$options = [System.Management.Automation.Host.ChoiceDescription[]]($yes, $no)
$title = "Invalid Destination"
$message = "The folder you entered does not exist. Would you like to create the folder?"
#Prompt for folder creation and store answer
$result = $host.UI.PromptForChoice($title, $message, $options, 0)
#If yes, create.
if ($result -eq 0) {
New-Item $DestinationPath -ItemType Directory | Out-Null
Write-Host "Directory created."
}
#If no, exit
else {exit}
}
#Add a trailing "\" to the destination path if it doesn't already
if ($DestinationPath[-1] -ne "\") {
$DestinationPath += "\"
}
#Add Interop Assembly
Add-type -AssemblyName "Microsoft.Office.Interop.Outlook" | Out-Null
#Type declaration for Outlook Enumerations, Thank you Hey, Scripting Guy! blog for this demonstration
$olFolders = "Microsoft.Office.Interop.Outlook.olDefaultFolders" -as [type]
$olSaveType = "Microsoft.Office.Interop.Outlook.OlSaveAsType" -as [type]
$olClass = "Microsoft.Office.Interop.Outlook.OlObjectClass" -as [type]
#Add Outlook Com Object, MAPI namespace, and set folder to the Inbox
$outlook = New-Object -ComObject Outlook.Application
$namespace = $outlook.GetNameSpace("MAPI")
#Future Functionality to Receive Email before saving - Still Needs Testing
#$outlook.Session | Out-Null
#$outlook.Session.SendAndReceive($false) | Out-Null
$folder = $namespace.getDefaultFolder($olFolders::olFolderInBox)
#Iterate through each object in the chosen folder
foreach ($email in $folder.Items) {
#Get email's subject and date
[string]$subject = $email.Subject
[string]$sentOn = $email.SentOn
#Strip subject and date of illegal characters, add .msg extension, and combine
$fileName = Remove-InvalidFileNameChars -Name ($sentOn + "-" + $subject + ".msg")
#Combine destination path with stripped file name
$dest = $DestinationPath + $fileName
#Test if object is a MailItem
if ($email.Class -eq $olClass::olMail) {
#Test if UnreadOnly switch was used
if ($UnreadOnly) {
#Test if email is unread and save if true
if ($email.Unread) {
#Test if MarkRead switch was used and mark read
if ($MarkRead) {
$email.Unread = $false
}
$email.SaveAs($dest, $olSaveType::olMSG)
}
}
#UnreadOnly switch not used, save all
else {
$email.SaveAs($dest, $olSaveType::olMSG)
}
}
}
Think You can do something like this:
$outlook = New-Object -ComObject Outlook.Application
$namespace =$outlook.GetNameSpace("MAPI")
$namespace.Logon("Profilename","profilepassword",$false,$false)
Also you can use Assembly - Microsoft.Exchange.WebServices.dll and do something like this:
[Reflection.Assembly]::LoadFile("C:\Program Files (x86)\Microsoft\Exchange\Web Services\2.0\Microsoft.Exchange.WebServices.dll") > $nul
$getref = New-Object Microsoft.Exchange.WebServices.Data.ExchangeService([Microsoft.Exchange.WebServices.Data.ExchangeVersion]::Exchange2010_SP2)
$getref.Credentials = New-Object Net.NetworkCredential('Account', 'Password', 'domain.local')
$getref.AutodiscoverUrl("Account#domain.com")
$inbox = [Microsoft.Exchange.WebServices.Data.Folder]::Bind($getref,[Microsoft.Exchange.WebServices.Data.WellKnownFolderName]::Inbox)
#Write-Host "Total Messages:" $inbox.TotalCount
$psPropset = new-object Microsoft.Exchange.WebServices.Data.PropertySet([Microsoft.Exchange.WebServices.Data.BasePropertySet]::FirstClassProperties)
$ivItemView = New-Object Microsoft.Exchange.WebServices.Data.ItemView($inbox.TotalCount)
$fiItems = $getref.FindItems($Inbox.Id,$ivItemView)
[Void]$getref.LoadPropertiesForItems($fiItems,$psPropset)
foreach($Item in $fiItems.Items){
if ($Item.From -EQ "Somemail#domain.com") {
New-Object -TypeName PSObject -Property #{
Emails = $Item.From
} | select Emails
}
}
Hello! You can load a body text (to html) something like this:
foreach($Item in $fiItems.Items){
if ($Item.Subject -match "Something special") {
$Item.Load()
$Save = ((Get-Date -Format "yyMMdd") + "-" + $Item.Subject[0] + ".html")
New-Item -Path "C:\file\exch\" -name $Save -ItemType file -value $Item.Body.Text
}
}
I m trying to copy documents from list in one sharepoint to another :
this is my code :
*************************************************
$source= "\\...\s1"
$destination = "\\..\s2"
foreach ($result in $result )
{ copy-item -path $source -dest $destination}
*************************************************
-$result is the list of all documents that I got using web-services, it s type is system.array
-$source and $destination are UNC that refers to URL of the two sharepoint
the error is
" can not find the path \...\s1system.xml.Xml.XmlElement"
PS: I m not using server machine,it s just a client
Here is my code
*****************************************************
{
param (
[String]$Value,
[String]$Field,
[String]$RowLimit = "0",
[String]$Operator = "Contains",
[String]$WebURL = "https://.................../wer",
[String]$ListName = "Main documents",
[String]$ViewName,
[Switch]$Recurse
)
$ScriptDirectory = split-path $MyInvocation.MyCommand.Definition
$dllPath = "P:\SamlCookieAuth.dll" -f $ScriptDirectory
[void][System.Reflection.Assembly]::LoadFrom($dllPath)
$queryOptionsValue = ''
if ($Recurse)
{
$queryOptionsValue = '<ViewAttributes Scope="RecursiveAll"/>'
}
$WSUri = $WebURL + "/_vti_bin/Lists.asmx?wsdl"
$listsWebServiceReference = New-WebServiceProxy -Uri $WSUri -UseDefaultCredential
$listsWebServiceReference.Url = $webURL + "/_vti_bin/lists.asmx"
[System.Uri]$CookieUri = $WebURL
$listsWebServiceReference.CookieContainer = [ST.SamlCookieAuth.SamlCookieManager]::GetAuthenticatedCookiesContainer($CookieUri.AbsoluteUri, 0, 0)
[System.Xml.XmlDocument]$xmlDoc = New-Object -TypeName System.Xml.XmlDocument
[System.Xml.XmlElement]$queryOptions =$xmlDoc.CreateElement("QueryOptions")
$queryOptions.InnerXml = $queryOptionsValue
if ($PSBoundParameters.Keys.Contains("Value"))
{
[System.Xml.XmlElement]$query = $xmlDoc.CreateElement("Query")
$queryValue = "<Where><$Operator><FieldRef Name='$Field'/><Value Type='Text'>$Value</Value></$Operator></Where>"
$query.InnerXml = $queryValue
$result=$listsWebServiceReference.GetListItems($listName, $viewName, $query, $null, $rowLimit, $queryOptions, $null).data.row
}
else
{
$result=$listsWebServiceReference.GetListItems($listName, $viewName, $null, $null, $rowLimit, $queryOptions, $null).data.row
}
$destDirectory = "\\.............\TER\Main Documents"
foreach ($resul in $result)
{Copy-Item -path $resul -destination $destDirectory }
}
Perhaps the problem that you are having is the result of a conversion issue. You are trying to write content from one SP to another as a document, however, you cannot do so with an XmlElement.
Suggest checking out this post:
Converting system.xml.xmlelement to system.xml.xmldocument with PowerShell
It would be helpful to see the content of "-$result is the list of all documents that I got using web-services, it s type is system.array".
Also, for readability, I would suggest differentiating between $result and $result as follows:
foreach($document in $documentList){}
-or- (at minimum)
foreach($result in $results){}
I have a script already that can download email attachments using EWS to avoid having outlook installed/opened.
I'm now wanting to save email content, preferably as a HTML file, but otherwise as .eml or .msg.
My other thread about the attachments is here: Download attachments with multiple subjects from Exchange
I was hoping that the existing script could be adapted somehow, but honestly I have no idea.
$MailboxName = "me#mymail.com"
$Subjects = #(
'Subject1',
'Subject2'
)
[regex]$SubjectRegex = ‘^(?i)(‘ + (($Subjects |foreach {[regex]::escape($_)}) –join “|”) + ‘)$’
$downloadDirectory = "C:\temp"
Function FindTargetFolder($FolderPath){
$tfTargetidRoot = new-object Microsoft.Exchange.WebServices.Data.FolderId([Microsoft.Exchange.WebServices.Data.WellKnownFolderName]::MsgFolderRoot,$MailboxName)
$tfTargetFolder = [Microsoft.Exchange.WebServices.Data.Folder]::Bind($service,$tfTargetidRoot)
for ($lint = 1; $lint -lt $pfArray.Length; $lint++) {
$pfArray[$lint]
$fvFolderView = new-object Microsoft.Exchange.WebServices.Data.FolderView(1)
$SfSearchFilter = new-object Microsoft.Exchange.WebServices.Data.SearchFilter+isEqualTo([Microsoft.Exchange.WebServices.Data.FolderSchema]::DisplayName,$pfArray[$lint])
$findFolderResults = $service.FindFolders($tfTargetFolder.Id,$SfSearchFilter,$fvFolderView)
if ($findFolderResults.TotalCount -gt 0){
foreach($folder in $findFolderResults.Folders){
$tfTargetFolder = $folder
}
}
else{
"Error Folder Not Found"
$tfTargetFolder = $null
break
}
}
$Global:findFolder = $tfTargetFolder
}
$dllpath = "C:\Program Files\Microsoft\Exchange\Web Services\2.0\Microsoft.Exchange.WebServices.dll"
[void][Reflection.Assembly]::LoadFile($dllpath)
$service = New-Object Microsoft.Exchange.WebServices.Data.ExchangeService([Microsoft.Exchange.WebServices.Data.ExchangeVersion]::Exchange2007_SP1)
$windowsIdentity = [System.Security.Principal.WindowsIdentity]::GetCurrent()
$sidbind = "LDAP://<SID=" + $windowsIdentity.user.Value.ToString() + ">"
$aceuser = [ADSI]$sidbind
$uri=[system.URI] "https://webmail.com/EWS/Exchange.asmx"
$service.Url = $uri
FindTargetFolder($ProcessedFolderPath)
$folderid = new-object Microsoft.Exchange.WebServices.Data.FolderId([Microsoft.Exchange.WebServices.Data.WellKnownFolderName]::Inbox,$MailboxName)
$InboxFolder = [Microsoft.Exchange.WebServices.Data.Folder]::Bind($service,$folderid)
$Sfsub = new-object Microsoft.Exchange.WebServices.Data.SearchFilter+IsEqualTo([Microsoft.Exchange.WebServices.Data.ItemSchema]::Subject,$Subject[0])
$sfCollection = new-object Microsoft.Exchange.WebServices.Data.SearchFilter+SearchFilterCollection([Microsoft.Exchange.WebServices.Data.LogicalOperator]::And);
$sfCollection.add($Sfsub)
$sfCollection.add($Sfha)
$view = new-object Microsoft.Exchange.WebServices.Data.ItemView(2000)
$frFolderResult = $InboxFolder.FindItems($sfCollection,$view)
foreach ($miMailItems in $frFolderResult.Items)
{
$miMailItems.body.text | set-content C:\temp
}
Using the foreach loop from your other script:
foreach ($miMailItems in $frFolderResult.Items)
{
$miMailItems.body.text | set-content <filepath>
}
You'll need to come up with a file naming scheme for the output files, but getting the email body text out to a file is relatively trivial.