Skip to content

Instantly share code, notes, and snippets.

@nils-a
Last active February 6, 2024 10:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nils-a/60e687103f4dafc853f7292c29780efa to your computer and use it in GitHub Desktop.
Save nils-a/60e687103f4dafc853f7292c29780efa to your computer and use it in GitHub Desktop.

Code snippets that are displayed in my Blog.

include in WordPress

Use GistPress

General (first file)

[gist id="60e687103f4dafc853f7292c29780efa"]

specific file

[gist id="60e687103f4dafc853f7292c29780efa" file="media-control-snippet.php"]

show only selected lines

[gist id="60e687103f4dafc853f7292c29780efa" lines="2-5"]

highlight some lines

[gist id="60e687103f4dafc853f7292c29780efa" highlight="2-5,8"]
<#
.SYNOPSIS
Uploads a Folder, including all Files and subfolders
.Notes
This Cmdlet assumes you have PNP installed and Connect-PNPOnline was issued before this command.
.Example
Add-PNPFolderRecursive -Path C:\temp -Folder /SiteAssets -NoRootFolderCreation
Uploads all of c:\temp to /SiteAssets
.Example
Add-PNPFolderRecursive -Path C:\temp -Folder /SiteAssets
Creates a "temp" folder in /SiteAssets, then uploads all of c:\temp to the newly created /SiteAssets/temp
#>
[CmdletBinding()]
param(
[Parameter(Position=0,
Mandatory=$true)]
$Path,
[Parameter(Position=1,
Mandatory=$true)]
$Folder,
[Parameter(Mandatory=$false)]
[switch]$NoRootFolderCreation
)
$ErrorActionPreference="Stop"
$dstFolder = Get-PNPFolder $Folder
Write-Verbose "Acquired folder: $($dstFolder.ServerRelativeUrl)"
if(!$NoRootFolderCreation.IsPresent) {
$folderName = Split-Path -Leaf $Path
Write-Verbose "Creating target-folder $folderName"
Add-PNPFolder -Name $folderName -Folder $dstFolder.ServerRelativeUrl
$dstFolder = Get-PNPFolder "$($dstFolder.ServerRelativeUrl)/$($folderName)"
Write-Verbose "Acquired folder: $($dstFolder.ServerRelativeUrl)"
}
# get all childs of "path" and upload the files...
$files = Get-ChildItem -File -Path $Path
$files | % {
Write-Verbose "Uploading $($_.FullName)"
Add-PNPFile -Path $_.FullName -Folder $dstFolder.ServerRelativeUrl | Out-Null
}
# recursive call subfolders
$foders = Get-ChildItem -Directory -Path $Path
$foders | %{
Write-Verbose "Descending to Folder: $($_.FullName)"
Invoke-Expression -Command ($PSCommandPath + " -Path $($_.FullName) -Folder $($dstFolder.ServerRelativeUrl) ")
}
Write-verbose "Done for $Path"
public void AppendContent(string urlToDocInSharePoint, string contentToAdd)
{
if (string.IsNullOrEmpty(urlToDocInSharePoint))
{
throw new ArgumentException("file-url must be given.", "urlToDocInSharePoint");
}
if (string.IsNullOrEmpty(contentToAdd))
{
// nothing to do..
return;
}
using (var site = new SPSite(urlToDocInSharePoint))
using (var web = site.OpenWeb())
{
var webAppUrl = site.Url.Replace(web.ServerRelativeUrl, string.Empty);
var siteRelativeDocumentUrl = urlToDocInSharePoint.Replace(webAppUrl, string.Empty);
if (!siteRelativeDocumentUrl.StartsWith("/"))
{
siteRelativeDocumentUrl = "/" + siteRelativeDocumentUrl;
}
var file = web.GetFile(siteRelativeDocumentUrl);
if (!file.Exists)
{
throw new FileNotFoundException(string.Format("The given file \"{0}\" in site \"{1}\" with relative url \"{2}\" could not be found. No such file exists.",
urlToDocInSharePoint, site.Url, siteRelativeDocumentUrl));
}
if (!file.InDocumentLibrary)
{
throw new ArgumentException(string.Format("The given file \"{0}\" is not in a DocumentLibrary. Unable to modify.", siteRelativeDocumentUrl), "context");
}
var html = contentToAdd;
if (!html.StartsWith("<html", StringComparison.InvariantCultureIgnoreCase))
{
html = string.Format("<html>{0}</html>", html);
}
// according to https://stackoverflow.com/questions/18089921/add-html-string-to-openxml-docx-document the html-bytes must be UTF8-encoded with Preamble...
var htmlBytes = new UTF8Encoding(true).GetPreamble().Concat(Encoding.UTF8.GetBytes(html)).ToArray();
using (var newDoc = new MemoryStream())
{
// copy file from SP to memory
using (var spStream = file.OpenBinaryStream(SPOpenBinaryOptions.None))
{
spStream.CopyTo(newDoc);
}
newDoc.Seek(0, 0);
//open & modify docx
using (var docx = WordprocessingDocument.Open(newDoc, true))
using (var htmlStream = new MemoryStream(htmlBytes))
{
var mainDoc = docx.MainDocumentPart;
// add html as "alternative format" to document, then reference it in the main body....
var partId = string.Format("SPAdded{0:N}",Guid.NewGuid());
var part = mainDoc.AddAlternativeFormatImportPart(AlternativeFormatImportPartType.Html, partId);
part.FeedData(htmlStream);
var partRef = new AltChunk {Id = partId};
var body = mainDoc.Document.Body;
body.InsertAfter(partRef, body.Elements().Last());
mainDoc.Document.Save();
}
newDoc.Seek(0, 0);
//push newDoc as new Version to list
var folder = file.ParentFolder;
if (folder.RequiresCheckout)
{
file.CheckOut();
}
var uploaded = folder.Files.Add(file.Url, newDoc, true);
uploaded.Update();
if (folder.RequiresCheckout)
{
uploaded.CheckIn("Updated via WebService", SPCheckinType.MajorCheckIn);
uploaded.Publish("Updated via WebService");
}
}
}
}
// open some docx-document
using (var docx = WordprocessingDocument.Open(newDoc, true))
using (var htmlStream = new MemoryStream(htmlBytes))
{
var mainDoc = docx.MainDocumentPart;
// some id to use for adding first & referencing later
var partId = string.Format("SPAdded{0:N}",Guid.NewGuid());
// the new AlternativeFormatImportPart
var part = mainDoc.AddAlternativeFormatImportPart(AlternativeFormatImportPartType.Html, partId);
part.FeedData(htmlStream);
// an AltChunk (referencing the AlternativeFormatImportPart by use of ID)
var partRef = new AltChunk {Id = partId};
// add the AltChunk after the last element of the document
var body = mainDoc.Document.Body;
body.InsertAfter(partRef, body.Elements().Last());
// save the document
mainDoc.Document.Save();
}
#!/bin/bash
pushd $(dirname $0) > /dev/null
lftp -c "set ftp:list-options -a;
open -u user,pass ftp://server.dom.de;
lcd backup-dir;
mirror \
--use-cache \
--delete \
--allow-chown \
--allow-suid \
--no-umask \
--parallel=2 \
--exclude .listing \
--exclude .configs \
--exclude atd \
--log=../mirror.log" \
2> error.log \
> /dev/null
if [ "$?" -ne 0 ]; then
cat > last.mail.eml <<EOF
Subject: BACKUP server.dom.de FEHLGESCHLAGEN !!!
X-Priority: 1
Importance: High
---- ERROR-LOG: ----
EOF
cat error.log >> last.mail.eml
cat >> last.mail.eml <<EOF
---- MIROR-LOG: ----
EOF
cat mirror.log >> last.mail.eml
/usr/sbin/sendmail -i USER < last.mail.eml
fi
popd > /dev/null
_csv2qif_possible_csvFiles()
{
local csvs optfiles
optfiles=""
csvs=$(find . -maxdepth 1 -iname "*.csv" | sed "s/\.\///g")
for file in ${csvs}; do
if [ ! -f ${file/\.csv/.qif} ]; then
optfiles="${optfiles} ${file}"
fi
done
echo $optfiles
}
_csv2qif()
{
local cur opts
cur="${COMP_WORDS[COMP_CWORD]}"
opts=$(_csv2qif_possible_csvFiles)
COMPREPLY=( $(compgen -W "${opts}" -- ${cur}) )
return 0
}
complete -F _csv2qif csv2qif.py
_csv2qif_possible_csvFiles()
{
local curWord csvs optfiles
curWord=${1}
optfiles=""
csvs=$( compgen -f -X "!*.csv" -- "${curWord}" )
for file in ${csvs}; do
if [ ! -f ${file/\.csv/.qif} ]; then
optfiles="${optfiles} ${file}"
fi
done
echo $optfiles
}
_csv2qif()
{
local cur opts
cur="${COMP_WORDS[COMP_CWORD]}"
opts=$(_csv2qif_possible_csvFiles ${cur})
COMPREPLY=( $(compgen -W "${opts}" -- ${cur}) )
return 0
}
complete -o plusdirs -F _csv2qif csv2qif.py
public partial class MyEntities
{
partial void OnContextCreated()
{
this.SavingChanges += HandleSavingChanges;
}
private static void HandleSavingChanges(object sender, EventArgs e)
{
MyEntities context = (MyEntities) sender;
//code....
}
}
<Import Project="$(VSToolsPath)\SharePointTools\Microsoft.VisualStudio.SharePoint.targets" Condition="'$(VSToolsPath)' != ''" />
<PropertyGroup>
<BuildDependsOn>
$(BuildDependsOn);
CreatePackage;
</BuildDependsOn>
</PropertyGroup>
#!/usr/bin/python
# -*- coding: utf-8 -*-
import urllib
import easygui
import logging
import nautilus
import os
CCDFOLDERS = [
'source',
'bin',
'build',
'lib',
'resource',
]
class CcdDirStructureExtension(nautilus.MenuProvider):
def __init__(self):
pass
def _alertError(self, message):
easygui.msgbox(message, title='Alert', ok_button='Mist!')
def _create_ccd_structure(self, foldername):
ok = easygui.ynbox(msg=u'wirklich eine CCD-Struktur ersellen in\n' + foldername,
title=u'Erstellen bestägen', choices=('Ja, bitte', 'Nein, danke'))
if ok == 0:
return
if not os.path.isdir(foldername):
self._alertError(foldername + u'\nist kein Verzeichnis. Abgebrochen.')
return
try:
for ccd in CCDFOLDERS:
dir = os.path.join(foldername, ccd)
os.mkdir(dir)
except Exception, e:
self._alertError(e)
raise
def menu_activate(self, menu, file):
"""Called when the user selects the menu."""
filename = urllib.unquote(file.get_uri()[7:])
self._create_ccd_structure(filename)
def get_file_items(self, window, files):
"""Called when the user selects a file in Nautilus."""
if len(files) != 1:
return
file = files[0]
if not file.is_directory() or file.get_uri_scheme() != 'file':
return
return self._get_MenuItemForFile(file)
def get_background_items(self, window, file):
"""Called when the user clicks the background of a Nautilus-Window"""
if not file.is_directory() or file.get_uri_scheme() != 'file':
return
return self._get_MenuItemForFile(file)
def _get_MenuItemForFile(self, file):
item = nautilus.MenuItem("NautilusPython::ccd-dir::create",
"CCD-Struktur",
"erstellt eine CCD-Verzeichnisstruktur in %s" % file.get_name())
item.connect("activate", self.menu_activate, file)
return item,
if __name__ == '__main__':
print 'This is a Nautilus extenion. Copy it to ${HOME}/.nautilus/python-extensions/ and restart Nautilus. Have fun.'
# -*- coding: utf-8 -*-
# Erstellt einen Eintrag im Context-Menü des Explorers: CCD-Verzeichnis erstellen
# bei Click wird im gewählten Verzeichnis eine CCD-Verzeichnisstrukur
# (bin, build, lib, source, resources) erstellt.
import os.path
import pythoncom
from win32com.shell import shell, shellcon
import win32gui
import win32con
IContextMenu_Methods = ["QueryContextMenu", "InvokeCommand", "GetCommandString"]
IShellExtInit_Methods = ["Initialize"]
# HKCR Key Affected object types
# * All files
#AllFileSystemObjects All regular files and file folders
# Folder All folders, virtual and filesystem
# Directory File folders
#Directory\Background Directory-Background (Folder is open, one clicks on the white background...)
# Drive Root folders of all system drives
# Network Entire network
# NetShare All network shares
TYPES = [
'Directory\\Background',
'Directory',
]
SUBKEY = 'CCD-Verzeichnis'
CCDFOLDERS = [
'source',
'bin',
'build',
'lib',
'resource',
]
def alertError(hwnd, exc):
win32gui.MessageBox(hwnd, str(exc), str(exc.__class__), win32con.MB_OK)
class ShellExtension:
_reg_progid_ = "CCD.Verzeichnisersteller.ShellExtension.ContextMenu"
_reg_desc_ = "CCD-Verzeichnis Shell Extension (context menu)"
_reg_clsid_ = "{5C664DC4-5ADA-4385-9DEB-EDB51320A668}"
_com_interfaces_ = [shell.IID_IShellExtInit, shell.IID_IContextMenu]
_public_methods_ = IContextMenu_Methods + IShellExtInit_Methods
def Initialize(self, folder, dataobj, hkey):
self.dataobj = dataobj
def QueryContextMenu(self, hMenu, indexMenu, idCmdFirst, idCmdLast, uFlags):
try:
msg = 'CCD-Verzeichnis ersellen'
idCmd = idCmdFirst
items = []
if (uFlags &amp; 0x000F) == shellcon.CMF_NORMAL:
items.append(msg)
elif uFlags &amp; shellcon.CMF_VERBSONLY:
items.append(msg)
elif uFlags &amp; shellcon.CMF_EXPLORE:
items.append(msg)
else:
pass
win32gui.InsertMenu(hMenu, indexMenu,
win32con.MF_SEPARATOR|win32con.MF_BYPOSITION,
0, None)
indexMenu += 1
for item in items:
win32gui.InsertMenu(hMenu, indexMenu,
win32con.MF_STRING|win32con.MF_BYPOSITION,
idCmd, item)
indexMenu += 1
idCmd += 1
win32gui.InsertMenu(hMenu, indexMenu,
win32con.MF_SEPARATOR|win32con.MF_BYPOSITION,
0, None)
indexMenu += 1
return idCmd-idCmdFirst
except Exception, e:
alertError(None, e)
raise
def InvokeCommand(self, ci):
mask, hwnd, verb, params, dir, nShow, hotkey, hicon = ci
try:
if self.dataobj is None:
#background-click
fname = dir
else:
#get Files from dragObject
files = self.getDragFiles()
if not files:
return
fname = files[0]
self.CreateCCDFolderStructure(hwnd, fname)
except Exception, e:
alertError(hwnd, e)
raise
return
def GetCommandString(self, cmd, typ):
return "Erstellt eine CCD-Verzeichnisstruktur"
def getDragFiles(self):
# Format the DataObject using a formatec, then get DragQueryFile from it...
format_etc = win32con.CF_HDROP, None, 1, -1, pythoncom.TYMED_HGLOBAL
sm = self.dataobj.GetData(format_etc)
num_files = shell.DragQueryFile(sm.data_handle, -1)
files = [shell.DragQueryFile(sm.data_handle, i) for i in range(num_files)]
return files
def CreateCCDFolderStructure(self, hwnd, folder):
ok = win32gui.MessageBox(hwnd, u'wirklich eine CCD-Struktur ersellen in\n' + folder,
u'Erstellen bestägen',
win32con.MB_YESNO|win32con.MB_ICONQUESTION|win32con.MB_TASKMODAL|win32con.MB_SETFOREGROUND)
if ok != win32con.IDYES:
return
if not os.path.isdir(folder):
alertError(hwnd, folder + u'\nist kein Verzeichnis. Abgebrochen.')
try:
for ccd in CCDFOLDERS:
dir = os.path.join(folder, ccd)
os.mkdir(dir)
except Exception, e:
alertError(hwnd, e)
raise
return
def DllRegisterServer():
import _winreg
for typ in TYPES:
key = _winreg.CreateKey(_winreg.HKEY_CLASSES_ROOT, "%s\\shellex" % typ)
subkey = _winreg.CreateKey(key, "ContextMenuHandlers")
subkey2 = _winreg.CreateKey(subkey, SUBKEY)
_winreg.SetValueEx(subkey2, None, 0, _winreg.REG_SZ, ShellExtension._reg_clsid_)
print ShellExtension._reg_desc_, "registration complete."
def DllUnregisterServer():
import _winreg
for typ in TYPES:
try:
key = _winreg.DeleteKey(_winreg.HKEY_CLASSES_ROOT, "%s\\shellex\\ContextMenuHandlers\\%s" % (typ, SUBKEY))
except WindowsError, details:
import errno
if details.errno != errno.ENOENT:
raise
print ShellExtension._reg_desc_, "unregistration complete."
def main(argv):
from win32com.server import register
register.UseCommandLine(ShellExtension,
finalize_register = DllRegisterServer,
finalize_unregister = DllUnregisterServer)
if __name__=='__main__':
import sys
main(sys.argv)
Dism.exe /online /Cleanup-Image /StartComponentCleanup /ResetBase
Dism.exe /online /Cleanup-Image /SPSuperseded
Get-ChildItem HKLM:SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\VolumeCaches | %{ $_| Set-ItemProperty -Name "StateFlags1234" -Value 2 }
cleanmgr.exe /sagerun:1234
udefrag.exe --optimize --repeat C:
sdelete.exe -q -z C:
find -depth -name "* *" | while read file; do
filePath="$(dirname "${file}")"
oldFileName="$(basename "${file}")"
newFileName=${oldFileName//[^a-zA-Z0-9\.]/_}
mv "${filePath}"/"${oldFileName}" "${filePath}"/"${newFileName}"
done
Sub ConcatenateAllWordFiles()
Dim mypath
mypath = BrowseFolder("Verzeichnis Wählen")
Set fso = CreateObject("Scripting.FileSystemObject")
Set Folder = fso.GetFolder(mypath)
Set allFiles = Folder.Files
Set newDoc = Documents.Add
For Each file In allFiles
If Right(file, 5) = ".docx" Then
Documents.Open FileName:=file.Path
current = ActiveDocument.Name
Selection.WholeStory
Selection.Copy
Documents(current).Close
newDoc.Activate
Selection.Paste
Selection.EndKey Unit:=wdLine
End If
Next
End Sub
Function BrowseFolder(Title As String, _
Optional InitialFolder As String = vbNullString, _
Optional InitialView As Office.MsoFileDialogView = _
msoFileDialogViewList) As String
Dim V As Variant
Dim InitFolder As String
With Application.FileDialog(msoFileDialogFolderPicker)
.Title = Title
.InitialView = InitialView
If Len(InitialFolder) > 0 Then
If Dir(InitialFolder, vbDirectory) <> vbNullString Then
InitFolder = InitialFolder
If Right(InitFolder, 1) <> "\" Then
InitFolder = InitFolder & "\"
End If
.InitialFileName = InitFolder
End If
End If
.Show
On Error Resume Next
Err.Clear
V = .SelectedItems(1)
If Err.Number <> 0 Then
V = vbNullString
End If
End With
BrowseFolder = CStr(V)
End Function
[System.Reflection.Assembly]::LoadWithPartialName("Microsoft.Office.Server")
[System.Reflection.Assembly]::LoadWithPartialName("Microsoft.Office.Server.UserProfiles")
$ctx = [Microsoft.Office.Server.ServerContext]::GetContext((Get-SPWebApplication | Select -First 1))
$upm = new-object Microsoft.Office.Server.UserProfiles.UserProfileManager -ArgumentList @($ctx)
$lang = "de-DE,en-US"
$enum = $upm.GetEnumerator()
while ($enum.MoveNext()) {
$up = $enum.Current
write-host "$($up.DisplayName) ($($up.AccountName))"
$up["SPS-MUILanguages"].Value = $lang
$up["SPS-ContentLanguages"].Value= $lang
$up.Commit()
}
[System.Reflection.Assembly]::LoadWithPartialName("Microsoft.Office.Server") | out-null
[System.Reflection.Assembly]::LoadWithPartialName("Microsoft.Office.Server.UserProfiles") | out-null
$ctx = [Microsoft.Office.Server.ServerContext]::GetContext((Get-SPWebApplication | Select -First 1))
$upm = new-object Microsoft.Office.Server.UserProfiles.UserProfileManager -ArgumentList @($ctx)
$lang = "de-DE,en-US"
$enum = $upm.GetEnumerator()
while ($enum.MoveNext()) {
$up = $enum.Current
write-host "$($up.DisplayName) ($($up.AccountName))"
$up["SPS-MUILanguages"].Value = $lang
$up["SPS-ContentLanguages"].Value= $lang
$up["SPS-RegionalSettings-Initialized"].Value = $true
$up.Commit()
}
Get-SPTimerJob | ?{ $_.Name -like "*user*profile*languageandregion*" } | %{ $_.RunNow() }
internal BenutzerVerwaltung()
{
InitializeComponent();
ContextMenuNotEnabledBugHelper.Workaround(this);
}
/// <summary>
/// Helper to Work around the ContextMenu[Not]EnabledBug of wpf.
/// see http://social.msdn.microsoft.com/forums/en-US/wpf/thread/7bd75a7c-eab4-4f3a-967b-94a9534a7455/
/// and http://www.wiredprairie.us/journal/2007/04/commandtarget_menuitem_context.html
/// regarding this...
/// </summary>
public static class ContextMenuNotEnabledBugHelper
{
public static void Workaround(Window window)
{
foreach (object child in RecurseChildren(window))
{
if (HasContextMenu(child))
{
Workaround(window, GetContextMenu(child));
}
}
}
private static bool HasContextMenu(object o)
{
return GetContextMenu(o) != null;
}
private static ContextMenu GetContextMenu(object o)
{
if (o is DependencyObject)
{
return (ContextMenu)((DependencyObject)o).GetValue(ContextMenuService.ContextMenuProperty);
}
return null;
}
private static void Workaround(Window window, ContextMenu contextMenu)
{
foreach (object o in LogicalTreeHelper.GetChildren(contextMenu))
{
if (o is MenuItem)
{
MenuItem menuItem = (MenuItem)o;
IInputElement oldTarget = menuItem.CommandTarget;
menuItem.CommandTarget = window; // <-- this is the Workaround !
if (oldTarget != null)
{
menuItem.CommandTarget = oldTarget;
}
}
}
}
private static IEnumerable RecurseChildren(DependencyObject current)
{
foreach (object child in LogicalTreeHelper.GetChildren(current))
{
yield return child;
if (child is DependencyObject)
{
foreach (object chlidsChild in RecurseChildren((DependencyObject)child))
{
yield return chlidsChild;
}
}
}
}
}
<#
.SYNOPSIS
Creates a StringCollection from a array of strings
.PARAMETER txt
strings to convert
.EXAMPLE
@("foo", "bar") | Create-StringCollection
#>
[CmdletBinding()]
[OutputType([System.Collections.Specialized.StringCollection])]
param (
[Parameter(Mandatory=$true, ValueFromPipeline=$True)]
[string[]]$txt
)
Begin {
$coll = New-Object System.Collections.Specialized.StringCollection;
}
Process {
$coll.Add($txt) | Out-Null;
}
End {
,$coll; # hack to prevent powershell from "unrolling" the enumerable
}
(function($){
$.fn.countdown = function(from, to, config){
var localDate = new Date(),
loop = function() {
var currentDate = new Date(),
localDiff = currentDate.getTime() - localDate.getTime(),
param = {
current: new Date(from),
target: new Date(to),
};
param.current.setTime(param.current.getTime() + localDiff);
param.millis = param.target.getTime() - param.current.getTime();
param.days = Math.floor(param.millis / 86400000);
param.millis -= param.days * 86400000;
param.hours = Math.floor(param.millis / 3600000);
param.millis -= param.hours * 3600000;
param.minutes = Math.floor(param.millis / 60000);
param.millis -= param.minutes * 60000;
param.seconds = Math.floor(param.millis / 1000);
param.millis -= param.seconds * 1000;
// Abbruch oder weiter..
if(param.current.getTime() >= param.target.getTime()) {
// callback rufen und abbruch
config.callback.call(this, param);
} else {
// text setzen und weiter
config.printDate.call(this, param);
window.setTimeout(loop.bind(this), config.timeout);
}
};
// config sicher stellen
if(!config) {
config = {};
}
if(!config.printDate) {
config.printDate = function(x) {
$(this).text(x.days + "d " + x.hours + "h " + x.minutes + "m " + x.seconds+ "s " + x.millis);
};
}
if(!config.callback) {
config.callback=function(){};
}
if(!config.timeout) {
config.timeout=1000;
}
loop.call(this);
return this;
};
})(jQuery);
<#
.SYNOPSIS
Decode HResult (hr) codes.. or die trying...
.EXAMPLE
Decode-HResult 0x80070718
Shows info about "Quota Exceeded"...
#>
[CmdletBinding()]
param(
[Parameter(Position=0)]
[int]$hr
)
function bitshift {
# https://stackoverflow.com/questions/35116636/bit-shifting-in-powershell-2-0
param(
[Parameter(Position=0)]
[int]$x,
[Parameter(ParameterSetName='Left')]
[int]$Left,
[Parameter(ParameterSetName='Right')]
[int]$Right
)
$shift = if($PSCmdlet.ParameterSetName -eq 'Left')
{
$Left
}
else
{
-$Right
}
return [math]::Floor($x * [math]::Pow(2,$shift))
}
$i = [int]$hr
$hex = "0x$([Convert]::ToString($i, 16))"
$bin = [Convert]::ToString($i, 2)
write-verbose "code as int: $i"
write-verbose "code as hex: $hex"
write-verbose "code as bin: $bin"
write-verbose ""
write-verbose "decoding:"
write-verbose $bin.PadLeft(32, " ")
write-verbose "SRCNX|- facil -||---- code ----|"
## see https://en.wikipedia.org/wiki/HRESULT
## and https://msdn.microsoft.com/en-us/library/cc231198.aspx
## and https://docs.microsoft.com/en-us/windows/desktop/com/structure-of-com-error-codes
# lowest 2 bytes for code
$code = $i -band 0xffff
# then 11 bit for facility
$fac = $i -band 0x7ff0000
if($fac -ne 0) { $fac = (bitshift $fac -Right 16)}
# 2 bit reserved, then 1 bit for customer
$cust = $i -band 0x20000000
if($cust -ne 0x0) { $cust = (bitshift $cust -Right 29)}
# 1 bit reserved (severe?) then 1 bit success (probably always 1?)
$nok = $i -band 0x80000000
if($nok -ne 0) { $nok = 1 }
write-host "hr = $hex"
write-host "Severity: $( if($nok -ne 0){"Fail"} else {"Success"} )"
write-host "code: 0x$([Convert]::ToString($code, 16))"
write-host "facility: 0x$([Convert]::ToString($fac, 16))"
if($cust -eq 0) {
write-host "the code was Microsoft-defined. "
Write-host " So you can lookup facility ($fac) under https://msdn.microsoft.com/en-us/library/cc231198.aspx"
write-host " and the code ($code) under https://docs.microsoft.com/en-us/windows/desktop/debug/system-error-codes"
} else {
write-host "the code was Cutomer-defined"
}
<#
.SYNOPSIS
Disable warning-messages when attaching VS to iis/w3wp.
.DESCRIPTION
When you attach VS to iis/w3wp for debugging, VS displays a warning.
This script disables theese warnings by modifying the registry accordingly.
WARNING: Make sure VS is not running when you start this script!
.PARAMETER VsVersion
The VS-version to modify - e.g. 10.0 for VS2010 or 14.0 for VS2015
.PARAMETER AllVersions
modify all installed Versions of VS
.PARAMETER ReEnable
Undo the changes done by this script - i.e. enable the warnings
.PARAMETER IgnoreRunningVS
continue script execution, even if a running VS is detected.
.EXAMPLE
.\Disable-VsDebuggerWarning.ps1 -VsVersion 12.0
Disable the warning only for VS2013
#>
[CmdletBinding(DefaultParameterSetName="all")]
param (
[Parameter(Mandatory=$false, ParameterSetName="all")]
[switch]$AllVersions = $false,
[Parameter(Mandatory=$true, ParameterSetName="one")]
[string]$VsVersion,
[Parameter(Mandatory=$false, ParameterSetName="all")]
[Parameter(Mandatory=$false, ParameterSetName="one")]
[switch]$ReEnable = $false,
[Parameter(Mandatory=$false, ParameterSetName="all")]
[Parameter(Mandatory=$false, ParameterSetName="one")]
[switch]$IgnoreRunningVS = $false
)
$vsPath = "HKCU:\Software\Microsoft\VisualStudio\";
function Get-AllVsVersions()
{
if(!(Test-Path $vsPath ))
{
Write-Error "No VisualStudio installations found. Exiting";
Exit;
}
$versions = Get-ChildItem $vsPath | Where-Object { !$_.Name.EndsWith("_Config") } | Split-Path -Leaf
Write-Host "$($versions.Length) VS installations found in registry: $versions"
return $versions;
}
function Disable-Warning($version)
{
$key = "DisableAttachSecurityWarning";
$basePath = Join-Path $vsPath ($version + "\Debugger");
$path = Join-Path $basePath $key;
Write-Output "Setting $path to DWORD: $dword";
# it's possible the key does not exist (e.g. in VS2015)
$nonExistingItem = ((Get-ItemProperty $basePath -Name $key -ErrorAction SilentlyContinue) -eq $null);
if($nonExistingItem)
{
if(!(Test-Path $basePath))
{
Write-Error "$basePath does not exist! Unable to proceed! Exiting";
return;
}
New-ItemProperty $basePath -Name $key -Value $dword -PropertyType "DWord"
}
else
{
Set-ItemProperty $basePath -Name $key -Value $dword
}
}
$isVsRunning = ((Get-Process | where { $_.Name -eq "devenv" }).length -gt 0)
if($isVsRunning)
{
Write-Host "A running VisualStudio was detected..." -ForegroundColor Red;
if(!$IgnoreRunningVS)
{
Write-Output "If you want to prceed anyway, use the ""-IgnoreRunningVS""-Switch. Exiting.";
Exit;
}
Write-Host "Ignoring the running VisualStudio... WARNING: this might not acually work! You have been warned!" -ForegroundColor Yellow;
}
$dword = 1;
if($ReEnable)
{
$dword = 0;
}
$versions = @();
if($AllVersions)
{
$versions = Get-AllVsVersions
}
elseif(![string]::IsNullOrWhiteSpace($VsVersion))
{
$versions += $VsVersion
}
else
{
Write-Host "Neither -VsVersion nor -AllVersions given. Nothing to do. :-(" -ForegroundColor Yellow
}
$versions | %{ Disable-Warning $_ }
<#
.SYNOPSIS
List or Remove elements from RecycleBin(s) of a WebApplication
.DESCRIPTION
This script lists- and optionally removes all items from all RecycleBins
of a WebApplication, including the End-Users (1st Stage) and
Administrators (2nd Stage) RecycleBins.
.NOTES
File Name : Delete-Site-Recycle-Bin.ps1
Author : Nils Andresen - nils@nils-andresen.de
.Example
.\Empty-SPRecycleBin.ps1 -WebApp http://sp.dev/ -FirstStageCleanup RemovePermanent -SecondStageCleanup RemovePermanent
Removes all deleted items (1st and 2nd stage) from all Sites/Webs of the WebApplication
#>
[CmdletBinding()]
param(
[Parameter(Mandatory=$True, HelpMessage = "Url to the WebApp")]
[string]$WebApp,
[Parameter(HelpMessage = "What to do with the 1st-stage Recycle Bins")]
[ValidateSet("ListOnly", "MoveTo2nd", "RemovePermanent")]
[string]$FirstStageCleanup = "ListOnly",
[Parameter(HelpMessage = "What to do with the 2nd-stage Recycle Bins")]
[ValidateSet("ListOnly", "RemovePermanent")]
[string]$SecondStageCleanup = "ListOnly"
)
if((Get-PSSnapin Microsoft.SharePoint.PowerShell -Registered -ErrorAction Ignore) -eq $null) {
Add-PSSnapin Microsoft.SharePoint.PowerShell
}
$Global:TotalRemovedSize = 0;
function Format-ForPc {
[CmdletBinding()]
param(
[Parameter(Position=0,
Mandatory=$true,
ValueFromPipeline=$true,
ValueFromPipelineByPropertyName=$true)]
[int]$size
)
if($size -lt 1MB) {
return "{0:0.0#}KB" -f ($size / 1KB);
}
if($size -lt 1GB) {
return "{0:0.0#}MB" -f ($size / 1MB);
}
if($size -lt 1TB) {
return "{0:0.0#}GB" -f ($size / 1GB);
}
return "{0:0.0#}TB" -f ($size / 1TB);
}
function Process-Web {
[CmdletBinding()]
param(
[Parameter(Position=0,
Mandatory=$true,
ValueFromPipeline=$true,
ValueFromPipelineByPropertyName=$true)]
[Microsoft.SharePoint.SPWeb[]]$web
)
Process {
Write-Verbose "Accessing Web: $($web.Url)";
if((-not $web.RecycleBinEnabled) -or ($web.RecycleBin.Count -lt 1)) {
return;
}
$bin = ,$web.RecycleBin; # mind the "," - no unrolling here...
$size = 0;
$bin | %{ $size += $_.Size }
Write-Output "Web $($web.Title) has $($bin.Count) items ($($size | Format-ForPc)) in Users-RecycleBin";
switch ($FirstStageCleanup) {
"ListOnly" {
$bin | %{ Write-Output "- $($_.ItemType):$($_.Title) ($($_.Size | Format-ForPc), Deleted by $($_.DeletedByName))" }
}
"RemovePermanent" {
$bin.DeleteAll();
$Global:TotalRemovedSize += $size;
Write-Output "- Deleted permanently";
}
"MoveTo2nd" {
$bin.MoveAllToSecondStage();
Write-Output "- Moved to second stage";
}
}
}
}
function Process-Site {
[CmdletBinding()]
param(
[Parameter(Position=0,
Mandatory=$true,
ValueFromPipeline=$true,
ValueFromPipelineByPropertyName=$true)]
[Microsoft.SharePoint.SPSite[]]$site
)
Process {
Write-Verbose "Accessing Site: $($site.Url)";
$secondStage = $site.RecycleBin | ? { $_.ItemState -eq [Microsoft.SharePoint.SPRecycleBinItemState]::SecondStageRecycleBin }
$site.AllWebs | Process-Web
if($secondStage.length -lt 1) {
return;
}
$size = 0;
$secondStage | %{ $size += $_.Size }
Write-Output "Site $($site.Title) ($($site.Url)) has $($secondStage.Length) items ($($size | Format-ForPc)) in Admin-RecycleBin";
switch ($SecondStageCleanup) {
"ListOnly" {
$secondStage | %{ Write-Output "- $($_.ItemType):$($_.Title) ($($_.Size | Format-ForPc), Deleted by $($_.DeletedByName))" }
}
"RemovePermanent" {
$secondStage | %{ $_.Delete(); }
$Global:TotalRemovedSize += $size;
Write-Output "- Deleted permanently";
}
}
}
}
$sa = Start-SPAssignment
$w = Get-SPWebApplication $WebApp -AssignmentCollection $sa;
$w.Sites | Process-Site;
Stop-SPAssignment $sa
if($SecondStageCleanup -eq "RemovePermanent" -and $FirstStageCleanup -eq "MoveTo2nd") {
Write-Warning "The selected combination of removing from second stage and moving from first to second possibly leaves items undeleted."
}
if($Global:TotalRemovedSize -gt 0) {
Write-Output "$($Global:TotalRemovedSize | Format-ForPc) were removed permanently.";
}
<#
.SYNOPSIS
Set your SharePoint webApplication to use debugging JS-files
instead of minified.
.DESCRIPTION
SharePoint uses minified JavaScript (e.g. SP.js) but is also able to
use debugging versions of the files instead. (e.g. SP.debug.js)
Setting SharePoint to deliver debug-JS requires a setting
in web.config.
This script sets the required value by adding a SpWebConfigModifaction
to your WebApplication.
.PARAMETER WebApplication
URL to WebApplication
.PARAMETER Remove
Remove this modification (and thereby restore the original web.config)
.EXAMPLE
.\Enable-SpJsDebugging.ps1 -WebApplication http:/your.farm/site/
Apply webConfig-Modification to allow for debugging-js to be used.
.EXAMPLE
.\Enable-SpJsDebugging.ps1 -WebApplication http:/your.farm/site/ -Remove
Remove webConfig-Modification and retore original web.config
#>
[CmdletBinding()]
param (
[Parameter(Mandatory=$true)]
[string]$WebApplication,
[Parameter(Mandatory=$false)]
[switch]$Remove = $false
)
if ( (Get-PSSnapin -Name Microsoft.SharePoint.PowerShell -Registered -ErrorAction Ignore) -eq $null )
{
Add-PSSnapin Microsoft.SharePoint.PowerShell
}
$name = "PowerShell.Scripts.EnableSpJsDebugging";
function Get-Modifications([Microsoft.SharePoint.Administration.SPWebApplication]$webApp){
return $webApp.WebConfigModifications | ?{ $_.Owner -eq $name }
}
function Remove-Modifications([Microsoft.SharePoint.Administration.SPWebApplication]$webApp,
[Microsoft.SharePoint.Administration.SPWebService]$contentService){
$mods = @();
$removed = @()
Get-Modifications($webApp) | %{ $mods = $mods + $_};
$mods | %{ $removed += $webApp.WebConfigModifications.Remove($_) };
$webApp.Update();
$contentService.ApplyWebConfigModifications();
$success = $removed | ?{ $_ -eq $true };
$fails = $removed | ?{ $_ -eq $false };
Write-Output "Removed $($success.Length) modifications.";
if($fails.length > 0) {
Write-Output "$($fails.Length) tries failed.";
}
}
function Add-Modification([Microsoft.SharePoint.Administration.SPWebApplication]$webApp,
[Microsoft.SharePoint.Administration.SPWebService]$contentService){
$mod = New-Object "Microsoft.SharePoint.Administration.SPWebConfigModification";
$mod.Path = "configuration/system.web/compilation";
$mod.Name = "debug";
$mod.Sequence = 0;
$mod.Owner = $name;
$mod.Type = [Microsoft.SharePoint.Administration.SPWebConfigModification+SPWebConfigModificationType]::EnsureAttribute;
$mod.Value = "true";
$unused = $webApp.WebConfigModifications.Add($mod);
$webApp.Update();
$contentService.ApplyWebConfigModifications();
Write-Output "Added modification.";
}
$gc = Start-SPAssignment
try {
$webApp = Get-SPWebApplication $WebApplication -AssignmentCollection $gc;
$contentService = [Microsoft.SharePoint.Administration.SPWebService]::ContentService
if($Remove){
Remove-Modifications $webApp $contentService;
Exit;
}
if((Get-Modifications $webApp).length -gt 0) {
Write-Output "Modification already applied...";
Exit;
}
Add-Modification $webApp $contentService;
} finally {
Stop-SPAssignment $gc
}
SP.SOD.executeOrDelayUntilScriptLoaded(function(){
alert('Hallo, Welt.');
}, 'sp.js');
SP.SOD.executeFunc('sp.js', null, function() {
alert('Hallo, Welt!');
});
if(!SP.SOD.executeOrDelayUntilScriptLoaded(function(){
alert('Hallo, Welt.');
}, 'sp.js')) {
// sp.js war nocht nicht angefordert...
SP.SOD.executeFunc('sp.js', null, function(){});
}
[hooks]
preupdate.finalbuilder = python:C:\wo\das\skript\liegt.py:preupdate
#!/usr/bin/python
# -*- coding: utf-8 -*-
import os
def preupdate(ui, repo, **kwargs):
basepath = repo.origroot
rev = kwargs['parent1']
node = repo.changelog.lookup(rev)
_,_,_,files,_,_ = repo.changelog.read(node)
for file in files:
if os.path.splitext(file)[1] != '.fbz6':
continue
fb_file = os.path.join(basepath, file)
fb_lockfile = os.path.splitext(fb_file)[0] + '.fb6lck'
if os.path.exists(fb_lockfile):
ui.write('Fehler: Die Finalbuilder-Datei\n%s\nsoll geändert werden, ist aber noch gelockt.\nSchließen sie Finalbuilder um das Update durchzuführen.\n' % fb_file)
ui.write('(Hinweis: Wenn sie (wirklich...) keinen Finalbuilder mehr geöffnet haben,\nsollten sie die lock-datei löschen.\n diese findet sich unter:\n%s)\n' % fb_lockfile)
return True
return False
<#
.SYNOPSIS
Find UPN for user from old netbios (i.e. domain\samAccountName) name
.PARAMETER Username
username in the netbios (i.e. domain\samAccountName) format
.EXAMPLE
Find-Upn -Username contoso\andresen
finds the user in AD and returns the UPN
#>
[CmdletBinding()]
param (
[Parameter(Mandatory=$true)]
[string]$Username
)
$ErrorActionPreference="Stop"
$parts = $Username.Split(@("\"), "None")
if($parts.Length -ne 2){
throw "Unable to parse '$($username)' into the domain\samAccountName-Syntax"
}
$netBiosDomain = $parts[0]
$samAccountName = $parts[1]
Write-Verbose "searching for netbios-domain:$($netBiosDomain)"
$rootDse = ([adsi]"LDAP://RootDSE")
if($null -eq $rootDse.dnsHostName) {
throw "no connection to AD."
}
$server = $rootDse.dnsHostName[0]
$rootDc = $rootDse.rootDomainNamingContext[0]
Write-Verbose "Root-DC is '$($rootDC)' at $($server)"
$connection = ([adsi]"LDAP://$($server)/CN=Partitions,CN=Configuration,$($rootDc)")
$searcher = ([adsisearcher]$connection)
$searcher.SearchScope = "Subtree"
$searcher.Filter = "netbiosname=$($netBiosDomain)"
$searcher.PropertiesToLoad.Add("ncname") | Out-Null
$domainDc = $searcher.FindOne().Properties.ncname[0]
Write-Verbose "Domain-DC is '$($domainDc)'"
$connection = ([adsi]"LDAP://$($server)/$($domainDc)")
$searcher = ([adsisearcher]$connection)
$searcher.PropertiesToLoad.Add("userprincipalname") | Out-Null
$searcher.SearchScope = "Subtree"
$searcher.Filter = "(&(objectClass=user)(samAccountName=$($samAccountName)))"
$user = $searcher.FindOne()
if($null -eq $user) {
throw "Could not find $($samAccountName) in AD-Subtree of '$($domainDc)'"
}
Write-Output $user.properties.userprincipalname[0]
(function($){
var classesInUse = {
_definedProperties: []
},
selectorsInUse = {
_definedProperties: []
};
//
// find all used classes
//
$('[class]').each(function(){
var $this = $(this),
className = this.className,
classes = className.split(/\s+/);
$.each(classes, function(_,c) {
if(c) {
//console.log('found a usage of class ' + c);
if(!classesInUse[c]) {
classesInUse[c] = {
elems: [$this]
};
classesInUse._definedProperties.push(c);
} else {
classesInUse[c].elems.push($this);
}
}
});
});
classesInUse._definedProperties.sort();
$.each(classesInUse._definedProperties, function(_, p){
console.log('class ' + p + ' was used ' + classesInUse[p].elems.length + ' times in HTML.');
});
//
// find all defined css selectors
//
$.each(document.styleSheets, function(_, style) {
$.each(style.cssRules, function(_, rule) {
var selector = rule.selectorText;
if(selector) {
//console.log('found a definition of css-selector ' + selector);
if(!selectorsInUse[selector]) {
selectorsInUse[selector] = {
count: 1
};
selectorsInUse._definedProperties.push(selector);
} else {
selectorsInUse[selector].count += 1;
}
}
});
});
selectorsInUse._definedProperties.sort();
$.each(selectorsInUse._definedProperties, function(_, p){
console.log('selector "' + p + '" was defined ' + selectorsInUse[p].count + ' times in CSS.');
});
//
// compare classes & selectors
//
$.each(classesInUse._definedProperties, function(_, klass){
var classSelector = '.' + klass,
usages = 0;
$.each(selectorsInUse._definedProperties, function(_, cssSelector){
if(cssSelector.indexOf(classSelector) > -1) {
usages += 1;
}
});
classesInUse[klass].usagesInCss = usages;
if(usages === 0) {
console.log('class ' + klass + ' was not used in CSS!');
} else {
console.log('class ' + klass + ' was used in CSS ' + usages + ' times.');
}
});
})(jQuery);
using System;
using System.DirectoryServices;
namespace FindUpn
{
internal class Program
{
private static void Main(string[] args)
{
var userName = "contoso\\andresen"; // should be dynamic, actually
string server;
string rootDc;
string domainDc = null;
// split userName in netbios-domain and samAccountName
var parts = userName.Split('\\');
var samAccountName = parts[1];
var netBiosDomain = parts[0];
// 1. first query AD for base-settings
// search RootDSE for some global properties
var connection = "LDAP://RootDSE";
Console.WriteLine("connection: " + connection);
using (var rootDse = new DirectoryEntry(connection)) // RootDSE is always available...
{
server = rootDse.Properties["dnsHostName"].Value as string;
rootDc = rootDse.Properties["rootDomainNamingContext"].Value as string;
Console.WriteLine(" - found server: " + server);
Console.WriteLine(" - found rootDc: " + rootDc);
}
// 2. query config for netbios-domain
// search rootDC-config for the corresponding DC of the netbios-domain
Console.WriteLine();
connection = string.Format("LDAP://{0}/CN=Partitions,CN=Configuration,{1}", server, rootDc);
Console.WriteLine("connection: " + connection);
using (var entry = new DirectoryEntry(connection))
using (var searcher = new DirectorySearcher(entry))
{
searcher.SearchScope = SearchScope.Subtree;
searcher.PropertiesToLoad.Add("nCName");
searcher.Filter = string.Format("netBiosName={0}", netBiosDomain);
var cfgEntry = searcher.FindOne();
if (cfgEntry == null)
{
Console.WriteLine("Domain not found!"); // TODO: Handle...
}
else
{
domainDc = cfgEntry.Properties["nCName"][0] as string;
Console.WriteLine(" - found domainDc: " + domainDc);
}
}
// 2. now create the "real" query...
// search in domainDC for "user"-objects and samaccountname
Console.WriteLine();
connection = string.Format("LDAP://{0}/{1}", server, domainDc);
Console.WriteLine("connection: " + connection);
using (var entry = new DirectoryEntry(connection))
using (var searcher = new DirectorySearcher(entry))
{
searcher.SearchScope = SearchScope.Subtree;
searcher.PropertiesToLoad.Add("userPrincipalName");
searcher.Filter = string.Format("(&(objectClass=user)(samAccountName={0}))", samAccountName);
var user = searcher.FindOne();
if (user == null)
{
Console.WriteLine("Nothing found"); // TODO: Handle...
}
else
{
var upn = user.Properties["userPrincipalName"][0] as string;
Console.WriteLine(" - UPN: " + upn);
}
}
#if DEBUG
Console.WriteLine("Done");
Console.ReadKey();
#endif
}
}
}
<#
.SYNOPSIS
List all items with broken inheritance
.DESCRIPTION
Lists all Webs, Lists, Folders and Items with broken inheritance.
This script was heavily inspired by http://techtrainingnotes.blogspot.de/2014/07/sharepoint-powershellfind-all-broken.html
.PARAMETER SiteCollectionUrl
Url to SiteCollection
.PARAMETER Site
Site. Can be Piped in.
.PARAMETER StopAtWeb
Stop the search at Web-Level. Do not search Lists/Folders/Items.
.PARAMETER StopAtList
Stop the search at List-Level. Do not search Folders/Items.
.PARAMETER StopAtFolder
Stop the search at Folder-Level. Do not search Items.
.INPUTS
Site
.OUTPUTS
Grid of Securable | Item | Url | Parent
where
Securable is one of "Web", "List", "Folder" or "Item"
Item is the Name or Title
Url is the url to the item
Parent is the url to the parent-item
.EXAMPLE
.\Get-SpBrokenInheritances.ps1 -SiteCollectionUrl http://my.lovely.site/
#>
[CmdletBinding()]
param (
[Parameter(ParameterSetName='SiteByUrl')]
[string]$SiteCollectionUrl,
[Parameter(ParameterSetName='SiteByObject', ValueFromPipeline=$true)]
[Microsoft.SharePoint.SPSite]$Site,
[Parameter()]
[switch]$StopAtWeb = $false,
[Parameter()]
[switch]$StopAtList = $false,
[Parameter()]
[switch]$StopAtFolder = $false
)
Set-StrictMode -Version Latest
$script:ErrorActionPreference = "Stop";
function Get-ParentUrl {
[CmdletBinding()]
param (
[Parameter(Mandatory=$true)]
[Microsoft.SharePoint.SPListItem]$Item
)
$List = $Item.ParentList;
if ($List.BaseType -eq [Microsoft.SharePoint.SPBaseType]::DocumentLibrary) {
return "$($_.ParentList.ParentWeb.ServerRelativeUrl)/$($_.File.ParentFolder.Url)";
} else {
# SPListItem.Url looks like /<listName>/<Folder1>/<folder2>/<ID>_.000 - I have no idea how to get the folder Url "correctly"
$FolderUrl = $Item.Url.Substring(0, $Item.Url.LastIndexOf("/"));
return "$($List.ParentWeb.ServerRelativeUrl)/$FolderUrl";
}
}
function Get-Url {
[CmdletBinding()]
param (
[Parameter(Mandatory=$true)]
[Microsoft.SharePoint.SPListItem]$Item
)
$List = $Item.ParentList;
if ($List.BaseType -eq [Microsoft.SharePoint.SPBaseType]::DocumentLibrary) {
return "$($List.ParentWeb.ServerRelativeUrl)/$($Item.Url)";
} else {
# e.g. /blubb/Lists/Test12/DispForm.aspx?ID=1
return "$($Item.ParentList.DefaultDisplayFormUrl)?ID=$($Item.Id)";
}
}
function Process-Lists {
[CmdletBinding()]
param (
[Parameter(Mandatory=$true)]
[Microsoft.SharePoint.SPList[]]$Lists
)
$Folders = $Lists | Select -ExpandProperty Folders;
$Folders | ? { $_.HasUniqueRoleAssignments } |
Select @{Label="Securable"; Expression={"Folder"}},
@{Label="Item"; Expression={$_.Title}},
@{Label="Url"; Expression={"$($_.ParentList.ParentWeb.ServerRelativeUrl)/$($_.Url)"}},
@{Label="Parent"; Expression={"$($_.ParentList.ParentWeb.ServerRelativeUrl)/$($_.ParentList.RootFolder.Url)"}} | Write-Output
if($StopAtFolder) {
return;
}
$Items = $Lists | Select -ExpandProperty Items;
$Items | ? { $_.HasUniqueRoleAssignments } |
Select @{Label="Securable"; Expression={"Item"}},
@{Label="Item"; Expression={$_.Name}},
@{Label="Url"; Expression={Get-Url -Item $_ }},
@{Label="Parent"; Expression={Get-ParentUrl -Item $_ }} | Write-Output
}
function Process-Webs {
[CmdletBinding()]
param (
[Parameter(Mandatory=$true)]
$Webs
)
$Lists = $Webs | Select -ExpandProperty Lists | ? { $_.EntityTypeName -ne "PublishedFeedList" -and -not $_.Hidden }
$Lists | ?{ $_.HasUniqueRoleAssignments } |
Select @{Label="Securable"; Expression={"List"}},
@{Label="Item"; Expression={$_.Title}},
@{Label="Url"; Expression={"$($_.ParentWeb.ServerRelativeUrl)/$($_.RootFolder.Url)"}},
@{Label="Parent"; Expression={$_.ParentWebUrl}} | Write-Output
if($StopAtList) {
return;
}
Process-Lists -Lists $Lists
}
function Process-Site {
[CmdletBinding()]
param (
[Parameter(Mandatory=$true)]
[Microsoft.SharePoint.SPSite]$Site
)
Write-Verbose "Process-Site $($Site.RootWeb.Title)";
$WebGc = Start-SPAssignment;
try {
$Webs = $Site | Get-SPWeb -AssignmentCollection $WebGc -Limit All;
$Webs | ?{ $_.HasUniqueRoleAssignments -and $_.ParentWeb -ne $Null } |
Select @{Label="Securable"; Expression={"Web"}},
@{Label="Item"; Expression={$_.Title}},
@{Label="Url"; Expression={$_.ServerRelativeUrl}},
@{Label="Parent"; Expression={$_.ParentWeb.ServerRelativeUrl}} | Write-Output
if($StopAtWeb) {
return;
}
Process-Webs -Webs $Webs
} finally {
Stop-SPAssignment $WebGc;
}
}
if((Get-PSSnapin Microsoft.SharePoint.PowerShell -Registered -ErrorAction Ignore) -eq $null) {
Add-PSSnapin Microsoft.SharePoint.PowerShell -ErrorAction Stop
}
$gc = Start-SPAssignment;
try{
if(!$Site) {
Write-Verbose "Site was neither given, nor in Pipe. Fetching Site from Url:$SiteCollectionUrl";
if(!$SiteCollectionUrl) {
Write-Error "Neither -Site, nor -SiteCollectionUrl was given.";
Exit -1;
}
$Site = Get-SpSite -Identity $SiteCollectionUrl -AssignmentCollection $gc -ErrorAction SilentlyContinue;
if ($Site -eq $null)
{
Write-Error "No SiteCollection with Identity '$SiteCollectionUrl' found. Exiting...";
Exit -1;
}
}
Process-Site -Site $Site;
} finally {
Stop-SPAssignment $gc;
}
<#
.SYNOPSIS
Lists all E-Mail enabled lists
If all is fine here you'll need to check
Resolve-DnsName <your-mail-domain-here> -Type MX #make sure the "right" server is the MX
Get-WindowsFeature smtp-server #make sure InstallState is "installed"
Get-Service SMTPSVC #make sure Status is "running"
.EXAMPLE
Get-SPEmailEnabledLists
Gets all e-Mail enabled lists from all webs in all site collections from all WebApplications. This may be a lot to check: You have been warned.
.EXAMPLE
Get-SPEmailEnabledLists -WebApplication (Get-SPWebApplication http://sp.dev/)
Gets all e-Mail enabled lists from all webs in all site collections of the given WebApplication
.EXAMPLE
Get-SPSite | ?{$_.Url - match "my."} | Get-SPEmailEnabledLists
Gets all e-Mail enabled lists from all webs in the given site collections
.EXAMPLE
Get-SPWeb http://sp.dev/sites/simple/sub | Get-SPEmailEnabledLists
Gets all e-Mail enabled lists from the given web
#>
[CmdletBinding()]
param(
[Parameter(
HelpMessage="restrict search to this web",
ValueFromPipeline=$true)]
[Microsoft.SharePoint.SPWeb[]]$Web,
[Parameter(
HelpMessage="restrict search to this site collection",
ValueFromPipeline=$true)]
[Microsoft.SharePoint.SPSite[]]$Site,
[Parameter(
HelpMessage="restrict search to this webApplication",
ValueFromPipeline=$true)]
[Microsoft.SharePoint.Administration.SPWebApplication[]]$WebApplication
)
if((Get-PSSnapin Microsoft.SharePoint.PowerShell -Registered -ErrorAction Ignore) -eq $null) {
Add-PSSnapin Microsoft.SharePoint.PowerShell -ErrorAction Stop
}
# check incoming mail settings
$serverAddr = "<unconfigured>";
$settings = (Get-SPFarm).Services | ?{ $_.TypeName -match "incoming e-mail" } | select -First 1
if((-not $settings) -or (-not $settings.Enabled)){
$url = "_admin/IncomingEmail.aspx";
$ca = (Get-SPWebApplication -IncludeCentralAdministration) | ?{ $_.IsAdministrationWebApplication } | select -First 1
if($ca) {
$url = $ca.Url + $url;
} else {
$url = "http://<your central admin>/$url";
}
Write-Warning "No incoming email-settings found, or incoming email is deactivated. check $url !"
} else {
$serverAddr = $settings.ServerDisplayAddress;
}
# collect the lists to check
if(-not $Web) {
Write-Verbose "no web given - getting all webs from site";
if(-not $Site) {
Write-Verbose "no site given - getting all sites from webApplication";
if(-not $WebApplication) {
Write-Verbose "no webApplication given - getting all webApplications";
$WebApplication = Get-SPWebApplication;
}
$Site = $WebApplication | % { $_.Sites };
}
$Web = $Site | %{ $_.AllWebs };
}
# check the lists
$lists = $Web | %{ $_.Lists }
Write-Verbose "checking $($lists.Count) lists...";
$lists | %{
if(($_.CanReceiveEmail) -and ($_.EmailAlias)) {
[PSCustomObject]@{
Title = $_.Title;
Url = "$($_.ParentWeb.Url)/$($_.RootFolder.Url)";
EmailAlias = "$($_.EmailAlias)@$serverAddr";
}
}
}
Get-SPSite | select url, @{label="Size in MB";Expression={$_.usage.storage/1MB}}
<#
.SYNOPSIS
Measures the size of an SPWeb - be warned that this is only an estimate,
as SharePoint has no OOTB function to measure the size of an web.
.PARAMETER Web
the web to measure
.PARAMETER HumanReadable
whether the output should be human-readable (KB, MB, GB, TB)
.EXAMPLE
Get-SPWeb path/to/web | Get-SPWebSize -HumanReadable GB
#>
[CmdletBinding()]
param (
[Parameter(Mandatory=$true, ValueFromPipeline=$True, HelpMessage = "the SPWeb to measure")]
[Microsoft.SharePoint.SPWeb]$Web,
[Parameter(Mandatory=$false, HelpMessage = "set to a size to measure in (e.g. KB or GB)")]
[ValidateSet("None", "KB", "MB", "GB", "TB")]
[string]$HumanReadable = "None",
[Parameter(Mandatory=$false, HelpMessage = "Suppress the startup-warning")]
[Switch]$SuppressWarn = $false
)
if(-not $SuppressWarn) {
Write-Warning "Be aware, that the calculated size is only an estimate!";
}
if((Get-PSSnapin Microsoft.SharePoint.PowerShell -Registered -ErrorAction Ignore) -eq $null) {
Add-PSSnapin Microsoft.SharePoint.PowerShell
}
function Get-FolderSize {
[CmdletBinding()]
param (
[Parameter(Mandatory=$true, ValueFromPipeline=$True)]
[Microsoft.SharePoint.SPFolder]$Folder
)
[long]$size = 0;
$Folder.Files | %{
$size += $_.Length;
}
$Folder.SubFolders | %{
$size += $_ | Get-FolderSize
}
Write-Verbose "Folder $($Folder.ParentWeb.Url +"/"+ $Folder.Url) has size of $size";
$size
}
function Get-SubWebSize {
[CmdletBinding()]
param (
[Parameter(Mandatory=$true, ValueFromPipeline=$True)]
[Microsoft.SharePoint.SPWeb]$Web
)
[long]$size = 0;
$Web.Folders | %{
$size += $_ | Get-FolderSize
}
$Web.Webs | %{
$size += $_ | Get-SubWebSize
}
Write-Verbose "Web $($Web.Url) has size of $size";
$size
}
$size = $Web | Get-SubWebSize
if ($HumanReadable -ne "None") {
$size = Invoke-Expression "$size / 1$HumanReadable";
}
$size
<#
.SYNOPSIS
Gets SQL-Aliases on multiple machines
.PARAMETER Use32Bit
set this flag to get 32bit aliases only
.PARAMETER Use64Bit
set this flag to get 64bit aliases only
.PARAMETER Machines
list of machines to connect. Default is local
.EXAMPLE
Get-SqlAlias
gets all 32 and 64 Bit aliases of the local machine.
.EXAMPLE
Get-SqlAlias -Use64Bit -Machines ((Get-SPFarm).Servers | ?{ $_.Role -ne "Invalid"} | Select-Object -ExpandProperty Address)
Gets all 64 Bit aliases for all machines of a SharePoint-Farm.
#>
[CmdletBinding()]
param(
[Parameter()]
[switch]$Use32Bit,
[Parameter()]
[switch]$Use64Bit,
[Parameter()]
[string[]]$Machines
)
$ErrorActionPreference="Stop"
if((-not $Use64Bit) -and (-not $Use32Bit)){
# default is 32 and 64
$Use64Bit = $true
$Use32Bit = $true
}
if($Use64Bit -and (-not [Environment]::Is64BitProcess)){
throw "Unable to access 64Bit-Registry from a non-64Bit-Process. Use 64Bit PowerShell."
}
if($Machines -eq $null -or $Machines.Length -eq 0){
$Machines = @($env:COMPUTERNAME)
}
$regViews = @();
if($Use32Bit) {
$regViews += [Microsoft.Win32.RegistryView]::Registry32
}
if($Use64Bit) {
$regViews += [Microsoft.Win32.RegistryView]::Registry64
}
$Machines | % {
$machine = $_
$regViews | % {
$view = $_
Write-Verbose "Accessing '$($machine)' for $($view)"
try {
$regEdit = [Microsoft.Win32.RegistryKey]::OpenRemoteBaseKey("LocalMachine", $machine, $view)
}
catch [IO.IOException] {
throw "Unable to connect to '$($machine)'. Error: $($_.Exception.Message)"
}
$key = $regEdit.OpenSubKey("SOFTWARE\Microsoft\MSSQLServer\Client\ConnectTo", $true)
if($key -eq $null) {
$regEdit.Close()
return
}
$names = $key.GetValueNames()
$names | % {
$parts = $key.GetValue($_).Split(",")
$server = $parts[1]
$port = ""
if($parts.Length -gt 2) {
$port = $parts[2]
}
[pscustomobject]@{
Machine = $machine;
RegistryView = $view;
Alias = $_;
Server = $server;
Port = $port
}
}
$regEdit.Close()
}
}
private static IList GetIListOfGenericType(Type t)
{
Type genericList = typeof (List<>).MakeGenericType(new[] {t});
return (IList)Activator.CreateInstance(genericList);
}
function getManagementUrl(idPathsArray) {
if(typeof idPathsArray.join !== "function") {
idPathsArray = [idPathsArray];
}
return _spPageContextInfo.webAbsoluteUrl.replace(/\/?$/, "/" + (_spPageContextInfo.layoutsUrl || "_layouts") + '/termstoremanager.aspx?termPath=' + idPathsArray.join('|'))
}
IUnityContainer container = UnityContainerProvider.UnityContainer;
container.RegisterType<IDbAdapter, DbAdapter>();
container.RegisterType<IRepository, PersonRepository>("Person");
container.RegisterType<IRepository, VorgangRepository>("Vorgang");
container.Configure<InjectedMembers>().ConfigureInjectionFor<DbAdapter>(
new InjectionConstructor(
new ResolvedParameter<IRepository>("Person"),
new ResolvedParameter<IRepository>("Vorgang")
));
if((Get-PSSnapin Microsoft.SharePoint.PowerShell -Registered -ErrorAction Ignore) -eq $null) {
Add-PSSnapin Microsoft.SharePoint.PowerShell -ErrorAction Stop
}
[Reflection.Assembly]::LoadWithPartialName("Microsoft.Office.SecureStore.dll") | Out-Null
[Reflection.Assembly]::LoadWithPartialName("Microsoft.Office.SecureStoreService") | Out-Null
$site = ((Get-SPWebApplication -IncludeCentralAdministration) | ?{ $_.IsAdministrationWebApplication } | select -First 1).Sites[0]
$secs = [Microsoft.Office.SecureStoreService.Server.SecureStoreProviderFactory]::Create()
$secs.Context = Get-SPServiceContext -Site $site
$apps = $secs.GetTargetApplications()
Write-Host "$($apps.count) applications in SecureStore..."
$apps | %{
$type = [Enum]::GetName([Microsoft.BusinessData.Infrastructure.SecureStore.TargetApplicationType], $_.Type)
Write-Host "$($_.Name):$($_.ApplicationId) ($type)"
$fields = $secs.GetTargetApplicationFields($_.ApplicationId);
$creds = $secs.GetCredentials($_.ApplicationId)
$creds | %{
$c = $_
$f = $fields | ?{ $_.CredentialType -eq $c.CredentialType}
$ptr = [IntPtr]::Zero
$ptr = [Runtime.InteropServices.Marshal]::SecureStringToGlobalAllocUnicode($c.Credential)
$str = [Runtime.InteropServices.Marshal]::PtrToStringUni($ptr);
[Runtime.InteropServices.Marshal]::ZeroFreeGlobalAllocUnicode($ptr);
Write-Host " - $($f.Name) ($($c.CredentialType)): $($str)"
}
}
Sub KommentarlisteInNeuemDokument()
'
' KommentarlisteInNeuemDokument Makro
' Erstellt eine Liste aller Kommentare des aktuellen Dokumentes in ein neues Dokument.
'
Dim oThisDoc As Document
Dim oThatDoc As Document
Dim c As Comment
Dim sTemp As String
Dim iPage As Integer
Set oThisDoc = ActiveDocument
Set oThatDoc = Documents.Add
Application.ScreenUpdating = False
For Each c In oThisDoc.Comments
'Find page number of comment
oThisDoc.Select
c.Reference.Select
iPage = Selection.Information(wdActiveEndAdjustedPageNumber)
'Put info in new document
oThatDoc.Select
Selection.EndKey Unit:=wdStory
sTemp = "Seite: " & iPage
Selection.TypeText Text:=sTemp
Selection.TypeParagraph
sTemp = "[" & c.Initial & c.Index & "] " & c.Range
Selection.TypeText Text:=sTemp
Selection.TypeParagraph
Next
Application.ScreenUpdating = True
End Sub
Option Explicit
Public Sub Mail2Task()
Dim olTask As Outlook.TaskItem
Dim olMail As MailItem
Dim olIns As Inspector
Dim olExp As Explorer
Set olTask = Application.CreateItem(olTaskItem)
Set olExp = Application.ActiveExplorer
If olExp.Selection.Count <> 1 Then
MsgBox "Funktioniert nur mit genau einer E-Mail"
Exit Sub
End If
If Not TypeOf olExp.Selection.Item(1) Is Outlook.MailItem Then
MsgBox "Funktioniert nur mit E-Mails !"
Exit Sub
End If
Set olMail = olExp.Selection.Item(1)
With olTask
.Subject = olMail.Subject
.Body = olMail.Subject & vbCrLf & vbCrLf
.StartDate = Now
.DueDate = DateAdd("d", 7, Date)
.ReminderSet = False
.Status = olTaskInProgress
End With
olTask.Attachments.Add olMail
Set olIns = olTask.GetInspector
olIns.Display ("True")
End Sub
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<configSections>
<sectionGroup name="NUnit">
<section name="TestRunner" type="System.Configuration.NameValueSectionHandler"/>
</sectionGroup>
</configSections>
<NUnit>
<TestRunner>
<!-- Valid values are STA,MTA. Others ignored. -->
<add key="ApartmentState" value="STA" />
<!-- See ThreadPriority enum for other valid values -->
<add key="ThreadPriority" value="Normal" />
</TestRunner>
</NUnit>
</configuration>
<Association Name="FK_Foo_Bar">
<End Role="Bar" Type="FooBarModel.Store.Bar" Multiplicity="1">
<OnDelete Action="Cascade" />
</End>
<End Role="Foo" Type="FooBarModel.Store.Foo" Multiplicity="*" />
<ReferentialConstraint>
<Principal Role="Bar">
<PropertyRef Name="ID" />
</Principal>
<Dependent Role="Foo">
<PropertyRef Name="BarId" />
</Dependent>
</ReferentialConstraint>
</Association>
<Association Name="FK_Foo_Bar">
<End Role="Bar" Type="FooBarModel.Bar" Multiplicity="1">
<OnDelete Action="Cascade" />
</End>
<End Role="Foo" Type="FooBarModel.Foo" Multiplicity="*" />
</Association>
public string MyTitle
{
get
{
return this.Title;
}
set
{
this.Title = value;
}
}
partial void OnTitleChanging(string unused)
{
OnPropertyChanging("MyTitle");
}
partial void OnTitleChanged()
{
OnPropertyChanged("MyTitle");
}
document.location =
document.location.href.replace(document.location.pathname, '') +
_spPageContextInfo.webServerRelativeUrl.replace(/\/?$/, '/' +
(_spPageContextInfo.layoutsUrl || '_layouts') +
'/listedit.aspx?List=' +
encodeURIComponent(_spPageContextInfo.pageListId))
public class PersonExtension : MarkupExtension
{
public string Nachname { get; set;}
public override object ProvideValue(IServiceProvider serviceProvider)
{
//Target herausfinden…
IProvideValueTarget provideValueTarget = (IProvideValueTarget) serviceProvider.GetService(typeof (IProvideValueTarget));
DependencyProperty dependencyProperty = provideValueTarget.TargetProperty as DependencyProperty;
if (dependencyProperty == null)
{
return null;
}
//dependencyProperty ist nun das Target, dass gesetzt werden soll (hier „Person“) –
//wichtig, damit Personen nur den Richtigen Properties zugewiesen werden
return dependencyProperty.PropertyType!=typeof(Person) ? null : Person.FindByNachname(this.Nachname);
}
}
<xaml>
<personenanzeigecontrol person = " { my:Person nachname=Müller } " />
</xaml>
// setup LightCore
var builder = new ContainerBuilder();
/* some fancy setup here */
var container = builder.Build();
// setup Quartz
var scheduler = await new StdSchedulerFactory()
.GetScheduler()
.UseLightCoreResolverJobFacotry(container);
scheduler.ScheduleJob(
JobBuilder.Create<ThisJobWillBeInstanciatedUsingLightCore>().Build(),
TriggerBuilder.Create().StartNow().Build());
function redirectToApp(appName){
var ctx = SP.ClientContext.get_current(),
web = ctx.get_web(),
appInstances = SP.AppCatalog.getAppInstances(ctx, web);
ctx.load(appInstances);
ctx.executeQueryAsync(function(){
var apps = appInstances.getEnumerator(),
app;
while(apps.moveNext()){
app = apps.get_current();
if(app.get_title() === appName){
break;
}
}
if(!app){
throw "No app found:"+appName
}
var redirectUrl = _spPageContextInfo.webAbsoluteUrl.replace(/\/?$/, '/'+_spPageContextInfo.layoutsUrl) +
'/appredirect.aspx?instance_id={' +app.get_id() + '}';
document.location = redirectUrl;
}, function(){ throw 'Error loading app-instances..'; });
}
<#
.SYNOPSIS
Run reflection on a given commandlet
.DESCRIPTION
Run reflection on any CmdLet
.NOTES
This code was heavily inspired from OISIN GREHAN, see http://www.nivot.org/post/2008/10/30/ATrickToJumpDirectlyToACmdletsImplementationInReflector
.Example
Get-Command Get-ChildItem | Reflect-Cmdlet -Reflect ShowDllOnly
.Example
Reflect-Cmdlet -CmdLet (Get-Command Get-ChildItem) -Reflect ShowDllOnly
#>
[CmdletBinding()]
param(
[Parameter(Position=0,
Mandatory=$true,
ValueFromPipeline=$true,
ValueFromPipelineByPropertyName=$true,
HelpMessage = "The CmdLet to reflect")]
[Management.Automation.CommandInfo]$CmdLet,
[Parameter(HelpMessage = "Which reflector to use.. ")]
[ValidateSet("ShowDllOnly", "Reflector", "JustDecompile", "ILSpy")]
[string]$Reflect = "ShowDllOnly"
)
# resolve to command if this is an alias
while ($CmdLet.CommandType -eq "Alias") {
$def = $CmdLet.definition;
Write-Verbose "$CmdLet is an alias. Using Definition: $def";
$CmdLet = Get-Command $def
}
Write-Verbose "Reflecting $CmdLet.";
$name = $CmdLet.ImplementingType
$DLL = $CmdLet.DLL
if($DLL -eq $null) {
Write-Warning "$CmdLet is not implemented in any DLL. Possibly a script?";
if($CmdLet.Path -ne $null) {
Write-Warning "Have a look at: $($CmdLet.Path)"
}
#$CmdLet | gm
Exit;
}
Write-Verbose "Type:$name, DLL:$DLL";
switch ($Reflect) {
"ShowDllOnly" {
Write-Output "$CmdLet is implemented in $name in the dll:$DLL";
}
"Reflector" {
if (-not (Get-Command reflector.exe -ErrorAction SilentlyContinue)) {
throw "Reflector.exe is not in your path."
}
Write-Verbose "Starting Reflector.";
reflector /select:$name $DLL
}
"JustDecompile" {
$regKey = Get-Item HKCU:\Software\Telerik\JustDecompile -ErrorAction SilentlyContinue
if($regKey -eq $null) {
throw "It seems JustDecompile is not installed."
}
$exe = $regKey.GetValue("ExecutablePath") ;
Write-Verbose "invoking $exe";
&$exe """$DLL""" ; #TODO: select the right type...
}
"ILSpy" {
if (-not (Get-Command ilspy.exe -ErrorAction SilentlyContinue)) {
throw "ilspy.exe is not in your path."
}
Write-Verbose "Starting ILSpy.";
ilspy $DLL /navigateTo:T:$name
}
}
Get-ChildItem -Recurse | where { $_.Name -Match "^1" } | Rename-Item -NewName { $_.Name.Substring(4) }
Selection.Find.ClearFormatting
Selection.Find.Font.Size = 10
Selection.Find.Replacement.ClearFormatting
Selection.Find.Replacement.Font.Size = 8
With Selection.Find
.Text = "^?"
.Replacement.Text = "^&"
.Forward = True
.Wrap = wdFindContinue
.Format = True
.MatchCase = False
.MatchWholeWord = False
.MatchWildcards = False
.MatchSoundsLike = False
.MatchAllWordForms = False
End With
Selection.Find.Execute Replace:=wdReplaceAll
<#
.SYNOPSIS
Sends a Test-Mail using SharePoint-Standard Tools
returns "TRUE", if the mail was successfully "taken in" with SharePoint (most probably also given to smtp...)
and "FALSE" if there was any failure to do so.
Check your ULS-Logs for further investigation if the result is FALSE, or your smtp-server-logs if the result is TRUE
.PARAMETER To
"TO" field of the mail.
.PARAMETER Web
The Url to the SPWeb to access via the SharePoint e-Mail utilities
.PARAMETER From
"FROM" field of the mail. defaults to "someone@example.com"
.PARAMETER Subject
"SUBJECT" field of the mail. Defaults to "Test" and a Date.
.PARAMETER Body
"BODY" of the mail. Defaults to some nice text.
.EXAMPLE
Send-SPTestMail -Web http://path.to/Web -From me@acme.com
Sends a simple mail using all the nice deafults..
#>
[CmdletBinding()]
param (
[Parameter(Mandatory=$true)]
[string]$Web,
[Parameter(Mandatory=$true)]
[string]$To,
[Parameter(Mandatory=$false)]
[string]$From = "someone@example.com",
[Parameter(Mandatory=$false)]
[string]$Subject = $null,
[Parameter(Mandatory=$false)]
[string]$Body = $null
)
$ErrorActionPreference="Stop"
if((Get-PSSnapin Microsoft.SharePoint.PowerShell -Registered -ErrorAction Ignore) -eq $null) {
Add-PSSnapin Microsoft.SharePoint.PowerShell -ErrorAction Stop
}
$headers = new-object System.collections.Specialized.StringDictionary
if(!$Subject) {
$Subject = "Test @ $(Get-Date)";
}
$headers.add("to",$To)
$headers.add("from",$From)
$headers.add("Subject",$Subject)
if(!$Body){
$Body = "Auto-Generated body of test-mail <ul><li>Generated at $(Get-Date)</li><li>Headers:<ul>";
$headers | % { $Body += "<li>$($_.Name): $($_.Value)</li>"; }
$Body += "</ul></li><li>Sent via SharePoint-Web at $($Web)</li></ul>";
}
$spweb = $null;
try {
$spweb = Get-SPWeb $Web -ErrorAction Stop
[Microsoft.SharePoint.Utilities.SPUtility]::SendEmail($spweb,$headers,$Body)
} finally {
if($spweb -ne $null) {
$spweb.Dispose();
}
}
<#
.SYNOPSIS
Sets SQL-Aliases on multiple machines
.PARAMETER Alias
The Alias to use
.PARAMETER Server
The server to point to
.PARAMETER Port
The port to point to
.PARAMETER Use32Bit
set this flag to add the alias to 32bit only
.PARAMETER Use64Bit
set this flag to add the alias to 64bit only
.PARAMETER Machines
list of machines to set the alias on. Default is local
.EXAMPLE
Set-SqlAlias -Alias "sql1" -Server RealSqlServer
Sets a SQL-Alias from sql1 to point to RealSqlServer for 32 and 64Bit on the local machine only.
.EXAMPLE
Set-SqlAlias -Alias "oldServer\instance" -Server "newServer\Instance" -Use64Bit -Machines ((Get-SPFarm).Servers | ?{ $_.Role -ne "Invalid"} | Select-Object -ExpandProperty Address)
Sets a SQL-Alias from "oldServer\instance" to point to "newServer\Instance" for 64Bit only. This will be set on all machines of a SharePoint-Farm.
#>
[CmdletBinding()]
param(
[Parameter(Mandatory=$true)]
[string]$Alias,
[Parameter(Mandatory=$true)]
[string]$Server,
[Parameter()]
[int]$Port,
[Parameter()]
[switch]$Use32Bit,
[Parameter()]
[switch]$Use64Bit,
[Parameter()]
[string[]]$Machines
)
$ErrorActionPreference="Stop"
if((-not $Use64Bit) -and (-not $Use32Bit)){
# default is 32 and 64
$Use64Bit = $true
$Use32Bit = $true
}
if($Use64Bit -and (-not [Environment]::Is64BitProcess)){
throw "Unable to access 64Bit-Registry from a non-64Bit-Process. Use 64Bit PowerShell."
}
if($Machines -eq $null -or $Machines.Length -eq 0){
$Machines = @($env:COMPUTERNAME)
}
$regViews = @();
if($Use32Bit) {
$regViews += [Microsoft.Win32.RegistryView]::Registry32
}
if($Use64Bit) {
$regViews += [Microsoft.Win32.RegistryView]::Registry64
}
$Machines | % {
$machine = $_
$regViews | % {
$view = $_
Write-Verbose "Accessing '$($machine)' for $($view)"
try {
$regEdit = [Microsoft.Win32.RegistryKey]::OpenRemoteBaseKey("LocalMachine", $machine, $view)
}
catch [IO.IOException] {
throw "Unable to connect to '$($machine)'. Error: $($_.Exception.Message)"
}
$key = $regEdit.OpenSubKey("SOFTWARE\Microsoft\MSSQLServer\Client\ConnectTo", $true)
if($key -eq $null) {
$key = $regEdit.OpenSubKey("SOFTWARE\Microsoft\MSSQLServer\Client", $true)
if($key -eq $null) {
throw "SQL-ClientTools not installed on $($machine)"
}
$key = $key.CreateSubKey("ConnectTo", $true)
if($key -eq $null) {
throw "Unable to access HKLM:SOFTWARE\Microsoft\MSSQLServer\Client\ConnectTo on '$($machine)'."
}
}
$val = "DBMSSOCN,$($Server)"
if($Port -gt 0) {
$val += ",$($Port)"
}
$key.SetValue($Alias, $val)
$regEdit.Close()
}
}
# https://www.powershellgallery.com/packages/PSWindowsUpdate/
Install-Module PSWindowsUpdate
# hide SharePoint updates
(Get-WindowsUpdate -MicrosoftUpdate) | ? { $_.Title -like "*sharepoint*" } | % { Hide-WindowsUpdate -KBArticle $_.KB -Confirm:$false }
# hide all SharePoint updates
do { $x = (Get-WindowsUpdate -MicrosoftUpdate) | ? { $_.Title -like "*sharepoint*" }; $x | % { Hide-WindowsUpdate -KBArticle $_.KB -Confirm:$false } } while ($x)
/_api/web/list/getbytitle('foo')/items(2)/FieldValuesAsText
/_api/web/list/getbytitle('foo')/items?$expand=FieldValuesAsText&$select=Id,FieldValuesAsText/FileRef,FieldValuesAsText/FileLeafRef
/_api/web/maptoicon(filename='filename.ext',progid='',size=0)
if (!!window.Type) {
//this is "normal"
Type.registerNamespace("SpSyntaxHighlighter");
} else {
//this happend on i.e. EditBlog.aspx
window.SpSyntaxHighlighter = window.SpSyntaxHighlighter || {};
}
SpSyntaxHighlighter.canApplySyntaxHighlighter = function () {
/// <summary>Check, if SyntaxHighlighter should be applied. I.e. returns false, if something is in edit mode..</summary>
/// <returns type="bool">fals, if loading of SyntaxHighlighter should be disabled</returns>
var rteFields = document.getElementsByClassName('ms-rtefield');
// check if page is in edit-mode or edit-form or something..
// do not (!) modify source in an editor - because that will lead to the modification being saved...
if (rteFields.length > 0) {
SP.UI.Notify.addNotification('Edit-Mode detected. SyntaxHighlighter disabled.', false);
return false;
}
return true;
};
SpSyntaxHighlighter.shAutoConfig = [[ 'applescript' , '~siteCollection/SiteAssets/SpSyntaxHighlighter/syntaxhighlighter/scripts/shBrushAppleScript.js'],
[ 'actionscript3', 'as3' , '~siteCollection/SiteAssets/SpSyntaxHighlighter/syntaxhighlighter/scripts/shBrushAS3.js'],
[ 'bash', 'shell' , '~siteCollection/SiteAssets/SpSyntaxHighlighter/syntaxhighlighter/scripts/shBrushBash.js'],
[ 'coldfusion','cf' , '~siteCollection/SiteAssets/SpSyntaxHighlighter/syntaxhighlighter/scripts/shBrushColdFusion.js'],
[ 'cpp', 'c' , '~siteCollection/SiteAssets/SpSyntaxHighlighter/syntaxhighlighter/scripts/shBrushCpp.js'],
[ 'c#', 'c-sharp', 'csharp' , '~siteCollection/SiteAssets/SpSyntaxHighlighter/syntaxhighlighter/scripts/shBrushCSharp.js'],
[ 'css' , '~siteCollection/SiteAssets/SpSyntaxHighlighter/syntaxhighlighter/scripts/shBrushCss.js'],
[ 'delphi', 'pascal', 'pas' , '~siteCollection/SiteAssets/SpSyntaxHighlighter/syntaxhighlighter/scripts/shBrushDelphi.js'],
[ 'diff', 'patch' , '~siteCollection/SiteAssets/SpSyntaxHighlighter/syntaxhighlighter/scripts/shBrushDiff.js'],
[ 'erl', 'erlang' , '~siteCollection/SiteAssets/SpSyntaxHighlighter/syntaxhighlighter/scripts/shBrushErlang.js'],
[ 'groovy' , '~siteCollection/SiteAssets/SpSyntaxHighlighter/syntaxhighlighter/scripts/shBrushGroovy.js'],
[ 'java' , '~siteCollection/SiteAssets/SpSyntaxHighlighter/syntaxhighlighter/scripts/shBrushJava.js'],
[ 'jfx', 'javafx' , '~siteCollection/SiteAssets/SpSyntaxHighlighter/syntaxhighlighter/scripts/shBrushJavaFX.js'],
[ 'js', 'jscript', 'javascript' , '~siteCollection/SiteAssets/SpSyntaxHighlighter/syntaxhighlighter/scripts/shBrushJScript.js'],
[ 'perl', 'Perl', 'pl' , '~siteCollection/SiteAssets/SpSyntaxHighlighter/syntaxhighlighter/scripts/shBrushPerl.js'],
[ 'php' , '~siteCollection/SiteAssets/SpSyntaxHighlighter/syntaxhighlighter/scripts/shBrushPhp.js'],
[ 'text', 'plain' , '~siteCollection/SiteAssets/SpSyntaxHighlighter/syntaxhighlighter/scripts/shBrushPlain.js'],
[ 'powershell', 'ps' , '~siteCollection/SiteAssets/SpSyntaxHighlighter/syntaxhighlighter/scripts/shBrushPowerShell.js'],
[ 'py', 'python' , '~siteCollection/SiteAssets/SpSyntaxHighlighter/syntaxhighlighter/scripts/shBrushPython.js'],
[ 'ruby', 'rails', 'ror', 'rb' , '~siteCollection/SiteAssets/SpSyntaxHighlighter/syntaxhighlighter/scripts/shBrushRuby.js'],
[ 'sass', 'scss' , '~siteCollection/SiteAssets/SpSyntaxHighlighter/syntaxhighlighter/scripts/shBrushSass.js'],
[ 'scala' , '~siteCollection/SiteAssets/SpSyntaxHighlighter/syntaxhighlighter/scripts/shBrushScala.js'],
[ 'sql' , '~siteCollection/SiteAssets/SpSyntaxHighlighter/syntaxhighlighter/scripts/shBrushSql.js'],
[ 'vb', 'vbnet' , '~siteCollection/SiteAssets/SpSyntaxHighlighter/syntaxhighlighter/scripts/shBrushVb.js'],
[ 'xml', 'xhtml', 'xslt', 'html' , '~siteCollection/SiteAssets/SpSyntaxHighlighter/syntaxhighlighter/scripts/shBrushXml.js']];
SpSyntaxHighlighter.runSyntaxHighlighter = function () {
/// <summary>
/// Re-Run SyntaxHighlighter, make sure SyntaxHighlighter was loaded before calling.
/// i.e. call loadSyntaxHighlighter first.
/// this functions does nothing, if an RichTextEditor is opened in the page!
/// </summary>
if (!SpSyntaxHighlighter.canApplySyntaxHighlighter()) return;
// restore the global SH-object if it was garbage-collected by MDS
if (!window.SyntaxHighlighter) {
window.SyntaxHighlighter = SpSyntaxHighlighter.SyntaxHighlighter;
}
window.SyntaxHighlighter.autoloader.apply(undefined, SpSyntaxHighlighter.shAutoConfig);
window.SyntaxHighlighter.vars.discoveredBrushes = null; // let SyntaxHighlighter re-run brush-discovery
window.SyntaxHighlighter.all();
// There is something itchy in autoloader.. SyntaxHighlighter.all() can not be called twice, if SyntaxHighlighter.autoloader was loaded :-(
//TODO: don't use autoloader...
window.setTimeout(window.SyntaxHighlighter.highlight.bind(window.SyntaxHighlighter), 100);
};
SpSyntaxHighlighter.loadSyntaxHighlighter = function () {
var csspath = '~siteCollection/SiteAssets/SpSyntaxHighlighter/syntaxhighlighter/styles/',
scriptpath = '~siteCollection/SiteAssets/SpSyntaxHighlighter/syntaxhighlighter/scripts/',
shTheme = 'shThemeDefault.css', //Possible Themes: shThemeDefault.css, shThemeDjango.css, shThemeEclipse.css, shThemeEmacs.css, shThemeFadeToGrey.css, shThemeMDUltra.css, shThemeMidnight.css, shThemeRDark.css
addEvent = function (elm, evt, func) {
if (elm.addEventListener) {
elm.addEventListener(evt, func);
} else if (elm.attachEvent) {
elm.attachEvent('on' + evt, func);
} else {
elm['on' + evt] = func;
}
},
removeEvent = function (elm, evt, func) {
if (elm.removeEventListener) {
elm.removeEventListener(evt, func);
} else if (elm.detachEvent) {
elm.detachEvent('on' + evt, func);
} else {
elm['on' + evt] = null;
}
},
loadScript = function (url, successHandler, errorHandler) {
var script = document.createElement('script'),
loaded, error;
script.src = url;
script.type = 'text/javascript';
script.language = 'javascript';
loaded = function () {
removeEvent(script, 'load', loaded);
removeEvent(script, 'error', error);
if (successHandler) {
successHandler(script);
}
};
error = function () {
removeEvent(script, 'load', loaded);
removeEvent(script, 'error', error);
if (errorHandler) {
errorHandler();
}
};
addEvent(script, 'load', loaded);
addEvent(script, 'error', error);
document.body.appendChild(script);
},
loadCss = function (url) {
var link = document.createElement('link');
link.href = url;
link.type = 'text/css';
link.rel = 'stylesheet';
document.head.appendChild(link);
},
loadSyntaxHighlighter = function () {
// add SyntaxHighlighter, styles and autoloader, then run autoloader
loadCss(csspath + 'shCore.css');
loadCss(csspath + shTheme);
loadScript(scriptpath + 'shCore.js', function () {
SpSyntaxHighlighter.SyntaxHighlighter = window.SyntaxHighlighter; // store SyntaxHighlighter in namespace...
loadScript(scriptpath + 'shAutoLoader.js', function () {
SpSyntaxHighlighter.runSyntaxHighlighter();
});
});
},
siteLoadFialed = function (err) {
if (!!(console && console.log)) {
console.log('accessing siteCollecion failed. ');
console.log('err was: ' + err);
console.log('execution aborted. :-(');
}
// this is the end of it. sadly.
},
siteLoadSucceded = function () {
var siteCollectionUrl = siteCollection.get_url(),
i, len, brushCfg, brushPath;
// fix up paths...
csspath = csspath.replace("~siteCollection", siteCollectionUrl);
scriptpath = scriptpath.replace("~siteCollection", siteCollectionUrl);
len = SpSyntaxHighlighter.shAutoConfig.length;
for (i = 0; i < len; i += 1) {
brushCfg = SpSyntaxHighlighter.shAutoConfig[i];
brushPath = brushCfg[brushCfg.length - 1];
brushCfg[brushCfg.length - 1] = brushPath.replace("~siteCollection", siteCollectionUrl);
}
// now start loading SyntaxHighlighter
loadSyntaxHighlighter();
},
siteCollection,
clientContext = SP.ClientContext.get_current(),
highlightable = document.getElementsByTagName('pre');
// check if syntaxHighlighter ist needed
if (highlightable.length < 1) return;
if (!SpSyntaxHighlighter.canApplySyntaxHighlighter()) return;
// load siteCollectionData then continue
siteCollection = clientContext.get_site();
clientContext.load(siteCollection);
clientContext.executeQueryAsync(siteLoadSucceded, siteLoadFialed);
};
SpSyntaxHighlighter.preLoadSyntaxHighlighter = function () {
if (!!SpSyntaxHighlighter.SyntaxHighlighter) {
//we've been here before :-)
SpSyntaxHighlighter.runSyntaxHighlighter();
return;
}
// load all from scratch...
SP.SOD.executeFunc('sp.js', 'SP.ClientContext', SpSyntaxHighlighter.loadSyntaxHighlighter);
};
SpSyntaxHighlighter.register = function () {
var thisUrl;
SpSyntaxHighlighter.preLoadSyntaxHighlighter();
if (!!window._spPageContextInfo) {
thisUrl = '~siteCollection/SiteAssets/SpSyntaxHighlighter/ShLoader.js'.replace('~siteCollection/', window._spPageContextInfo.siteServerRelativeUrl);
window.RegisterModuleInit(thisUrl, SpSyntaxHighlighter.preLoadSyntaxHighlighter);
}
};
//Simulate LoadAfterUi=true
window._spBodyOnLoadFunctionNames.push("SpSyntaxHighlighter.register");
@echo off
C:
chdir C:\cygwin\bin
start rxvt -sr -sl 10000 -fg white -bg black -fn "Lucida Console-10" -tn cygwin -e /bin/bash --login -i
Get-SPServiceApplication | `
? { $_.TypeName -match "^Search Service" } | `
% { Get-SPEnterpriseSearchCrawlContentSource -SearchApplication $_ } | `
? { $_.CrawlStatus -ne "Idle" } | `
% { Write-Host -NoNewline "Stopping $($_.Name) "; $_.StopCrawl(); do {Write-Host -NoNewline "."; Start-Sleep -Seconds 1} while ($_.CrawlStatus -ne "Idle"); Write-Host " stopped." }
select table_name
from INFORMATION_SCHEMA.TABLES
where
TABLE_NAME not in
(
select distinct table_name
from INFORMATION_SCHEMA.TABLE_CONSTRAINTS
where CONSTRAINT_TYPE = 'PRIMARY KEY '
)
and TABLE_TYPE = 'BASE TABLE'
function Test-Credential {
<#
.SYNOPSIS
checks some credentials.
.PARAMETER Credential
The Credentials to check
.PARAMETER Retry
retry on fail.
.EXAMPLE
Get-Credential dev\developer | Test-Credential -Verbose -Retry
#>
[OutputType([System.Management.Automation.PSCredential])]
[CmdletBinding()]
Param (
[Parameter(
Mandatory = $true,
ValueFromPipeLine = $true,
ValueFromPipelineByPropertyName = $true
)]
[Alias( 'PSCredential' )]
[ValidateNotNull()]
[System.Management.Automation.PSCredential]
[System.Management.Automation.Credential()]
$Credential = [System.Management.Automation.PSCredential]::Empty,
[switch]$Retry=$false
)
$processing = $true;
while($processing) {
$UserName = $Credential.username
$networkCred = $Credential.GetNetworkCredential();
$password = $networkCred.Password
$domain = $networkCred.Domain
Write-Verbose "Credentials supplied for user: $UserName"
if(!$domain) {
if($UserName -match "@") {
# user was foo@bar.baz...
Write-Verbose "User in UPN-Form. No domain-parsing will be done.."
} else {
# current domain
$domain = "LDAP://" + ([ADSI]"").DistinguishedName
Write-Verbose "No domain given. DistinguishedName of current domain: $domain"
}
} else {
Write-Verbose "domain given as $domain in old NT-syntax."
$test = Get-Command Get-ADDomain -ErrorAction SilentlyContinue
if($test -eq $null) {
$guess = "$($UserName.Substring($domain.length+1))@$domain";
Write-Verbose "CMDLet Get-ADDomain is not available. Guessing UPN-form for user as $guess";
$UserName = $guess;
$domain = "";
} else {
Write-Verbose "CMDLet Get-ADDomain is available. Fetching DistinguishedName..";
$domain = Get-ADDomain $domain -ErrorAction Stop;
$domain = "LDAP://" + $domain.DistinguishedName;
Write-Verbose "DistinguishedName of domain is: $domain";
}
}
# now re-fetch the current domain using the supplied credentials.
Write-Verbose "Validating credentials"
$entry = New-Object System.DirectoryServices.DirectoryEntry($domain,$UserName,$Password)
if ($entry.name -eq $null)
{
Write-Verbose "Authentication failed."
$abort = $false;
if($Retry) {
$Credential = Get-Credential -UserName $user -Message "Failed. Please rety..." -ErrorAction SilentlyContinue
if($Credential -eq $null) {
$abort = $true;
}
}
if(!$Retry -or $abort) {
throw "Validation failed..."
return $null;
}
}
else
{
Write-Verbose "Authentication succeeded."
$processing = $false;
return $Credential;
}
}
}
<#
.SYNOPSIS
Tests the WordAutomationService by submitting a document and waiting for the results.
.PARAMETER InFile
Url (in SharePoint) that points to the document to convert
This documents should exist.
.PARAMETER OutFile
Url (in SharePoint) to place the converted document
This documents should *not* exist.
.PARAMETER Format
Format of the output. PDF or XPS. Default: PDF
.EXAMPLE
Test-WordAutomationService -InFile https://my.sp.farm/documents/word-doc.docx -OutFile https://my.sp.farm/documents/converted.pdf
Converts https://my.sp.farm/documents/word-doc.docx to pdf and saves the result to https://my.sp.farm/documents/converted.pdf
#>
[CmdletBinding()]
[OutputType([System.Collections.Specialized.StringCollection])]
param (
[Parameter(Mandatory=$true)]
[string]$InFile,
[Parameter(Mandatory=$true)]
[string]$OutFile,
[Parameter(Mandatory=$false)]
[ValidateSet("pdf", "xps")]
[string]$Format = "pdf"
)
$ErrorActionPreference="Stop"
if((Get-PSSnapin Microsoft.SharePoint.PowerShell -Registered -ErrorAction Ignore) -eq $null) {
Add-PSSnapin Microsoft.SharePoint.PowerShell -ErrorAction Stop
}
$tmp = [Reflection.Assembly]::LoadWithPartialName("Microsoft.Office.Word.Server")
if($tmp -eq $null) {
throw "Could not load Microsoft.Office.Word.Server.dll. Somethong is not right..."
}
Write-Verbose "Assembly $($tmp.GetName().Name) is present and loaded"
$serviceApp = Get-SPServiceApplication | Where-Object { $_.TypeName -eq "Word Automation Services" } | Select-Object -First 1
if($null -eq $serviceApp) {
throw "Could not find Word Automation Services Service Application. Somethong is not right..."
}
Write-Verbose "Using Service-Application $($serviceApp.Name)."
#TODO: Service app as param? what if there's more than one?!
$serviceAppProxy = Get-SPServiceApplicationProxy | Where-Object { $_.ServiceEndpointUri -eq $serviceApp.Uri.AbsoluteUri }
Write-Verbose "Using Service-ApplicationProxy $($serviceAppProxy.Name)."
$web = $null
$url = $InFile
while ($null -eq $web) {
if([string]::isNullOrEmpty($url)){
throw "could not find a viable web from url: $($InFile)"
}
$url = (Split-Path -Path $url -Parent).Replace("\", "/")
$web = Get-SPWeb $url -ErrorAction Ignore
}
Write-Verbose "Using web: $($web) ($($web.Url))"
$setting = New-Object "Microsoft.Office.Word.Server.Conversions.ConversionJobSettings"
$setting.OutputFormat = $Format.ToUpperInvariant()
$job = New-Object "Microsoft.Office.Word.Server.Conversions.ConversionJob" -ArgumentList @($serviceAppProxy.Id, $setting)
$job.UserToken = $web.CurrentUser.UserToken
$job.AddFile($InFile, $OutFile)
$job.Start()
Write-Verbose "Started conversion-job with id: $($job.JobId)"
$timer = Get-SPTimerJob | Where-Object { $_.TypeName -like "Word Automation Services Timer Job" } | Select-Object -First 1
Start-SPTimerJob $timer
Write-Verbose "TimerJob '$($timer.DisplayName)' started."
$status = New-Object "Microsoft.Office.Word.Server.Conversions.ConversionJobStatus" -ArgumentList @($serviceAppProxy.Id, $job.JobId, $null);
while (($status.NotStarted -ge 1) -or ($status.InProgress -ge 1)) {
Write-Verbose "In Progress: $($status.InProgress)"
Start-Sleep -Seconds 1
$status.Refresh()
}
$items = $status.GetItems("Succeeded,Failed,Canceled")
Write-Verbose "Job ended. $($items.Length) items in this job."
,($items) #write them...
(Get-SPSite http://mein.sharepoint).AllWebs `
| select -ExpandProperty Lists `
| select -ExpandProperty Fields `
| %{ $_.Update() }
(Get-SPSite http://mein.sharepoint).AllWebs `
| select -ExpandProperty Lists `
| select -ExpandProperty Fields `
| ToArray `
| %{ $_.Update() }
function ToArray {
begin {
$output = @();
}
process {
$output += $_;
}
end {
return ,$output;
}
}
<TokenReplacementFileExtensions>svc</TokenReplacementFileExtensions>
<TokenReplacementFileExtensions>$(TokenReplacementFileExtensions);svc</TokenReplacementFileExtensions>
// setup LightCore
var builder = new ContainerBuilder();
/* some fancy setup here */
var container = builder.Build();
// setup Topshelf
var host = HostFactory.Run(x =>
{
x.UseLightCore(container); // Enable LightCore
x.Service<FakeSevice>(s =>
{
s.ConstructUsingLightCore<ThisServiceWillBeInstanciatedUsingLightCore>(); // Construct service using LightCore
s.WhenStarted(tc => tc.Start());
s.WhenStopped(tc => tc.Stop());
/* more Topshelf code... */
});
});
<#
.SYNOPSIS
Updates the DisplayProperties of the ResultItemTypes.
.Notes
This script currently only updates Site-Level-ResultTypes.
.Example
Update-ResultItemTypesProperties -SiteUrl https://my.sharepoint.com/sites/search
Updates DisplayProperties of all non builtin ResultTypes
#>
[CmdletBinding()]
param(
[Parameter(Mandatory=$true)]
[string]$SiteUrl
)
$ErrorActionPreference="Stop"
$site = Get-SPSite $SiteUrl
$ssa = Get-SPEnterpriseSearchServiceApplication
$owner = Get-SPEnterpriseSearchOwner -Level SPSite -SPWeb $site.RootWeb
# TODO: Ssa and SPWeb are also possible locations for owner...
$masterPageGallery = $site.GetCatalog("MasterPageCatalog")
$resultTypes = Get-SPEnterpriseSearchResultItemType -Owner $owner -SearchApplication $ssa | ? { -not $_.Builtin }
$resultTypes | % {
Write-Verbose "Processing: $($_.Name)"
$displayTemplateFileName = Split-Path -Path $_.DisplayTemplateUrl -Leaf
$displayTemplate = $masterPageGallery.Items | ? {$_.Name -eq $displayTemplateFileName}
$propPairs = $displayTemplate[[guid]"a0dd6c22-0988-453e-b3e2-77479dc9f014"];
$propsString = ""
if(-not [string]::IsNullOrWhiteSpace($propPairs)){
$props = $propPairs.Split(",") | %{ $_.Split(":") | Select -Last 1 } | %{ $_.Trim("'") }
$propsString = [string]::Join(",", $props)
}
if($_.DisplayProperties -eq $propsString) {
# match
return;
}
Set-SPEnterpriseSearchResultItemType -Identity $_ -Owner $owner -SearchApplication $ssa -DisplayProperties $propsString
}
<Binding Path="Person"
Mode="TwoWay">
<Binding.ValidationRules>
<ui:PersonValidationRule />
</Binding.ValidationRules>
</Binding>
<Window [blah...]
Validation.Error="ValidationError">
<Binding Path="Person"
Mode="TwoWay"
NotifyOnValidationError="True">
<Binding.ValidationRules>
<ui:PersonValidationRule />
</Binding.ValidationRules>
</Binding>
private int errorsInForm;
private void ValidationError(object sender, ValidationErrorEventArgs e)
{
switch (e.Action)
{
case ValidationErrorEventAction.Added:
this.errorsInForm++;
break;
case ValidationErrorEventAction.Removed:
this.errorsInForm--;
break;
}
}
private bool WindowHasErrors
{
get
{
return this.errorsInForm>0;
}
}
<Project xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup>
<SourceWebConfig>$(ProjectDir)\Web.config</SourceWebConfig>
<OutputPath Condition="'$(OutputPath)' == ''">$(ProjectDir)\bin</OutputPath>
<TempWebConfig>$(OutputPath)\Web.Temp.config</TempWebConfig>
<TransformationsBaseDir>$(ProjectDir)\Configs</TransformationsBaseDir>
<VisualStudioVersion Condition="'$(VisualStudioVersion)' == ''">11.0</VisualStudioVersion>
<VSToolsPath Condition="'$(VSToolsPath)' == ''">$(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion)</VSToolsPath>
</PropertyGroup>
<Import Project="$(VSToolsPath)\WebApplications\Microsoft.WebApplication.targets"/>
<ItemGroup>
<WebConfigTransforms Include="$(TransformationsBaseDir)/*.config">
<TransformDest>$(OutputPath)\%(WebConfigTransforms.Filename).config</TransformDest>
</WebConfigTransforms>
</ItemGroup>
<Target Name="TransformAllWebConfigs">
<!-- Does the real transformation of all web-config transforms... -->
<Copy SourceFiles="$(SourceWebConfig)"
DestinationFiles="$(TempWebConfig)" />
<Message Text="transforming %(WebConfigTransforms.Identity) to %(WebConfigTransforms.TransformDest)"
Importance="high"/>
<TransformXml Source="$(TempWebConfig)"
Transform="%(WebConfigTransforms.Identity)"
Destination="%(WebConfigTransforms.TransformDest)"
StackTrace="true" />
<Delete Files="$(TempWebConfig)" />
</Target>
<Target Name="TransformAfterBuild"
AfterTargets="Build">
<!-- after build, build all web.configs, too -->
<CallTarget Targets="TransformAllWebConfigs" />
<Message Text="TransformAllWebConfigs has run after build!"
Importance="high"/>
</Target>
<Target Name="MimicVsTransforms"
AfterTargets="PreTransformWebConfig">
<!-- this should mimic the original VS-behaviour -->
<CallTarget Targets="TransformAllWebConfigs" />
</Target>
<Target Name="CopyTransformedForPublish"
AfterTargets="CopyAllFilesToSingleFolderForPackage">
<!-- "GatherAllFilesToPublish" as AfterTarges seems to work, too. But only when Publish is called from within VS. -->
<Copy SourceFiles="@(WebConfigTransforms->'%(TransformDest)')"
DestinationFolder="$(WPPAllFilesInSingleFolder)" />
</Target>
</Project>
<Import Project="$(ProjectDir)\..\TransformWebConfig.targets" Condition="'$(TransformationsBaseDir)' == ''" />
<ItemGroup>
<WebConfigTransforms Include="$(TransformationsBaseDir)\**\web.config">
<StageName>$([System.String]::new('%(RecursiveDir)').TrimEnd('\\'))</StageName>
<TransformDest>$(OutputPath)\web.%(StageName).config</TransformDest>
</WebConfigTransforms>
</ItemGroup>
<?xml version="1.0"?>
<configuration>
<system.webServer>
<staticContent>
<mimeMap fileExtension=".json" mimeType="application/json" />
</staticContent>
</system.webServer>
</configuration>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment