full_path
stringlengths 31
232
| filename
stringlengths 4
167
| content
stringlengths 0
48.3M
|
|---|---|---|
PowerShellCorpus/PowerShellGallery/PSObjectInspector/0.0.1/build/dotSource/New-CommentBasedHelp.ps1
|
New-CommentBasedHelp.ps1
|
function Script:New-CommentBasedHelp {
<#
.SYNOPSIS
Create comment based help for a function.
.DESCRIPTION
Create comment based help for a function.
.PARAMETER Code
Multi-line or piped lines of code to process.
.PARAMETER ScriptParameters
Process the script parameters as the source of the comment based help.
.EXAMPLE
PS > $testfile = 'C:\temp\test.ps1'
PS > $test = Get-Content $testfile -raw
PS > $test | New-CommentBasedHelp | clip
Takes C:\temp\test.ps1 as input, creates basic comment based help and puts the result in the clipboard
to be pasted elsewhere for review.
.EXAMPLE
PS > $CBH = Get-Content 'C:\EWSModule\Get-EWSContact.ps1' -Raw | New-CommentBasedHelp -Verbose -Advanced
PS > ($CBH | Where {$FunctionName -eq 'Get-EWSContact'}).CBH
Consumes Get-EWSContact.ps1 and generates advanced CBH templates for all functions found within. Print out to the screen the advanced
CBH for just the Get-EWSContact function.
.NOTES
Author: Zachary Loeber
Site: http://www.the-little-things.net/
Requires: Powershell 3.0
Version History
1.0.0 - Initial release
1.0.1 - Updated for PSModuleBuild
#>
[CmdletBinding()]
param(
[parameter(Position=0, ValueFromPipeline=$true, HelpMessage='Lines of code to process.')]
[string[]]$Code,
[parameter(Position=1, HelpMessage='Process the script parameters as the source of the comment based help.')]
[switch]$ScriptParameters
)
begin {
$FunctionName = $MyInvocation.MyCommand.Name
Write-Verbose "$($FunctionName): Begin."
function Get-FunctionParameter {
<#
.SYNOPSIS
Return all parameters for each function found in a code block.
.DESCRIPTION
Return all parameters for each function found in a code block.
.PARAMETER Code
Multi-line or piped lines of code to process.
.PARAMETER Name
Name of fuction to process. If no funciton is given first the entire script will be processed for general parameters. If none are found every function in the script will be processed.
.PARAMETER ScriptParameters
Parse for script parameters only.
.EXAMPLE
PS > $testfile = 'C:\temp\test.ps1'
PS > $test = Get-Content $testfile -raw
PS > $test | Get-FunctionParameter -ScriptParameters
Takes C:\temp\test.ps1 as input, gathers any script's parameters and prints the output to the screen.
.NOTES
Author: Zachary Loeber
Site: http://www.the-little-things.net/
Requires: Powershell 3.0
Version History
1.0.0 - Initial release
1.0.1 - Updated function name to remove plural format
Added Name parameter and logic for getting script parameters if no function is defined.
Added ScriptParameters parameter to include parameters for a script (not just ones associated with defined functions)
#>
[CmdletBinding()]
param(
[parameter(ValueFromPipeline=$true, HelpMessage='Lines of code to process.')]
[string[]]$Code,
[parameter(Position=1, HelpMessage='Name of function to process.')]
[string]$Name,
[parameter(Position=2, HelpMessage='Try to parse for script parameters as well.')]
[switch]$ScriptParameters
)
begin {
$FunctionName = $MyInvocation.MyCommand.Name
Write-Verbose "$($FunctionName): Begin."
$Codeblock = @()
$ParseError = $null
$Tokens = $null
# These are essentially our AST filters
$functionpredicate = { ($args[0] -is [System.Management.Automation.Language.FunctionDefinitionAst]) }
$parampredicate = { ($args[0] -is [System.Management.Automation.Language.ParameterAst]) }
$typepredicate = { ($args[0] -is [System.Management.Automation.Language.TypeConstraintAst]) }
$paramattributes = { ($args[0] -is [System.Management.Automation.Language.NamedAttributeArgumentAst]) }
$output = @()
}
process {
$Codeblock += $Code
}
end {
$ScriptText = ($Codeblock | Out-String).trim("`r`n")
Write-Verbose "$($FunctionName): Attempting to parse AST."
$AST = [System.Management.Automation.Language.Parser]::ParseInput($ScriptText, [ref]$Tokens, [ref]$ParseError)
if($ParseError) {
$ParseError | Write-Error
throw "$($FunctionName): Will not work properly with errors in the script, please modify based on the above errors and retry."
}
if (-not $ScriptParameters) {
$functions = $ast.FindAll($functionpredicate, $true)
if (-not [string]::IsNullOrEmpty($Name)) {
$functions = $functions | where {$_.Name -eq $Name}
}
# get the begin and end positions of every for loop
foreach ($function in $functions) {
Write-Verbose "$($FunctionName): Processing function - $($function.Name.ToString())"
$Parameters = $function.FindAll($parampredicate, $true)
foreach ($p in $Parameters) {
$ParamType = $p.FindAll($typepredicate, $true)
Write-Verbose "$($FunctionName): Processing Parameter of type [$($ParamType.typeName.FullName)] - $($p.Name.VariablePath.ToString())"
$OutProps = @{
'FunctionName' = $function.Name.ToString()
'ParameterName' = $p.Name.VariablePath.ToString()
'ParameterType' = $ParamType[0].typeName.FullName
}
# This will add in any other parameter attributes if they are specified (default attributes are thus not included and output may not be normalized)
$p.FindAll($paramattributes, $true) | Foreach {
$OutProps.($_.ArgumentName) = $_.Argument.Value
}
$Output += New-Object -TypeName PSObject -Property $OutProps
}
}
}
else {
Write-Verbose "$($FunctionName): Processing Script parameters"
if ($ast.ParamBlock -ne $null) {
$scriptparams = $ast.ParamBlock
$Parameters = $scriptparams.FindAll($parampredicate, $true)
foreach ($p in $Parameters) {
$ParamType = $p.FindAll($typepredicate, $true)
Write-Verbose "$($FunctionName): Processing Parameter of type [$($ParamType.typeName.FullName)] - $($p.Name.VariablePath.ToString())"
$OutProps = @{
'FunctionName' = 'Script'
'ParameterName' = $p.Name.VariablePath.ToString()
'ParameterType' = $ParamType[0].typeName.FullName
}
# This will add in any other parameter attributes if they are specified (default attributes are thus not included and output may not be normalized)
$p.FindAll($paramattributes, $true) | Foreach {
$OutProps.($_.ArgumentName) = $_.Argument.Value
}
$Output += New-Object -TypeName PSObject -Property $OutProps
}
}
else {
Write-Verbose "$($FunctionName): There were no script parameters found"
}
}
$Output
Write-Verbose "$($FunctionName): End."
}
}
$CBH_PARAM = @'
.PARAMETER %%PARAM%%
%%PARAMHELP%%
'@
$Codeblock = @()
}
process {
$Codeblock += $Code
}
end {
$ScriptText = ($Codeblock | Out-String).trim("`r`n")
Write-Verbose "$($FunctionName): Attempting to parse parameters."
$FuncParams = @{}
if ($ScriptParameters) {
$FuncParams.ScriptParameters = $true
}
$AllParams = Get-FunctionParameter @FuncParams -Code $Codeblock | Sort-Object -Property FunctionName
$AllFunctions = @($AllParams.FunctionName | Select -unique)
foreach ($f in $AllFunctions) {
$OutCBH = @{}
$OutCBH.'FunctionName' = $f
[string]$OutParams = ''
$fparams = @($AllParams | Where {$_.FunctionName -eq $f} | Sort-Object -Property Position)
$fparams | foreach {
$ParamHelpMessage = if ([string]::IsNullOrEmpty($_.HelpMessage)) {' ' + $_.ParameterName + " explanation`n`r"} else {' ' + $_.HelpMessage + "`n`r"}
$OutParams += $CBH_PARAM -replace '%%PARAM%%',$_.ParameterName -replace '%%PARAMHELP%%',$ParamHelpMessage
}
$OutCBH.'CBH' = $Script:CBHTemplate -replace '%%PARAMETER%%',$OutParams
New-Object PSObject -Property $OutCBH
}
Write-Verbose "$($FunctionName): End."
}
}
|
PowerShellCorpus/PowerShellGallery/PSObjectInspector/0.0.1/build/dotSource/Update-PSGalleryProjectProfile.ps1
|
Update-PSGalleryProjectProfile.ps1
|
#Requires -version 5
function Script:Update-PSGalleryProjectProfile {
<#
.SYNOPSIS
Update a powershell Gallery module upload profile
.DESCRIPTION
Update a powershell Gallery module upload profile
.PARAMETER Name
Module short name.
.PARAMETER Path
Path of module project files to upload.
.PARAMETER ProjectUri
Module project website.
.PARAMETER Tags
Tags used to search for the module (separated by spaces)
.PARAMETER RequiredVersion
Module version
.PARAMETER Repository
Destination gallery (default is PSGallery)
.PARAMETER ReleaseNotes
Release notes.
.PARAMETER LicenseUri
License website.
.PARAMETER IconUri
Icon web path.
.PARAMETER APIKey
API key for the powershellgallery.com site.
.PARAMETER OutputFile
Input module configuration file (default is .psgallery)
.EXAMPLE
.NOTES
Author: Zachary Loeber
Site: http://www.the-little-things.net/
Version History
1.0.0 - Initial release
#>
[CmdletBinding()]
param(
[parameter(Position=0, HelpMessage='Module short name.')]
[string]$Name,
[parameter(Position=1, HelpMessage='Path of module project files to upload.')]
[string]$Path,
[parameter(Position=2, HelpMessage='Module project website.')]
[string]$ProjectUri,
[parameter(Position=3, HelpMessage='Tags used to search for the module (separated by spaces)')]
[string]$Tags,
[parameter(Position=4, HelpMessage='Required powershell version (default is 2)')]
[string]$RequiredVersion,
[parameter(Position=5, HelpMessage='Destination gallery (default is PSGallery)')]
[string]$Repository,
[parameter(Position=6, HelpMessage='Release notes.')]
[string]$ReleaseNotes,
[parameter(Position=7, HelpMessage='License website.')]
[string]$LicenseUri,
[parameter(Position=9, HelpMessage='Icon web path.')]
[string]$IconUri,
[parameter(Position=10, HelpMessage='API key for the powershellgallery.com site.')]
[string]$NuGetApiKey,
[parameter(Position=11, HelpMessage='Input module configuration file (default is .psgallery)')]
[string]$InputFile = '.psgallery'
)
if (Test-Path $InputFile) {
$PublishParams = Import-Clixml $InputFile
$MyParams = $PSCmdlet.MyInvocation.BoundParameters
$MyParams.Keys | Where {$_ -ne 'InputFile'} | ForEach {
Write-Verbose "Updating $($_)"
if ($PublishParams.$_ -ne $null) {
$PublishParams.$_ = $MyParams[$_]
}
}
$PublishParams | Export-Clixml -Path $InputFile -Force
}
else {
Write-Warning "InputFile was not found: $($InputFile)"
}
}
|
PowerShellCorpus/PowerShellGallery/PSObjectInspector/0.0.1/build/dotSource/Prompt-ForBuildBreak.ps1
|
Prompt-ForBuildBreak.ps1
|
Function Script:Prompt-ForBuildBreak {
param (
[Parameter(Position=0)]
[System.Object]$LastError,
[Parameter(Position=1)]
$CustomError = $null
)
$yes = New-Object System.Management.Automation.Host.ChoiceDescription "&Yes", "End the build."
$no = New-Object System.Management.Automation.Host.ChoiceDescription "&No", "Stop the build."
$ContinueBuildPrompt = [System.Management.Automation.Host.ChoiceDescription[]]($yes, $no)
if (($host.ui.PromptForChoice('Stop the build?', 'Should the build stop here?', $ContinueBuildPrompt, 0)) -eq 0) {
if ($CustomError -ne $null) {
throw $CustomError
}
else {
throw $LastError
}
}
else {
Write-Output "Contining the build process despite the following error:"
if ($CustomError -ne $null) {
Write-Output $CustomError
}
else {
Write-Output $LastError.Exception
}
}
}
|
PowerShellCorpus/PowerShellGallery/PSObjectInspector/0.0.1/build/dotSource/Convert-ArrayToString.ps1
|
Convert-ArrayToString.ps1
|
function Script:Convert-ArrayToString
{
[cmdletbinding()]
Param
(
[Parameter(Mandatory=$true,Position=0)]
[AllowEmptyCollection()]
[Array]$Array,
[Parameter(Mandatory=$False)]
[switch]$Flatten
)
Begin{
If($Flatten)
{
$Mode = 'Append'
}
Else
{
$Mode = 'AppendLine'
}
If($Flatten -or $Array.Count -eq 0)
{
$Indenting = ''
$RecursiveIndenting = ''
}
Else{
$Indenting = ' '
$RecursiveIndenting = ' ' * (Get-PSCallStack).Where({$_.Command -match 'Convert-ArrayToString|Convert-HashToSTring' -and $_.InvocationInfo.CommandOrigin -eq 'Internal' -and $_.InvocationInfo.Line -notmatch '\$This'}).Count
}
}
Process{
$StringBuilder = [System.Text.StringBuilder]::new()
If($Array.Count -ge 1)
{
[void]$StringBuilder.$Mode("@(")
}
Else
{
[void]$StringBuilder.Append("@(")
}
For($i = 0; $i -lt $Array.Count; $i++)
{
$Item = $Array[$i]
If($Item -is [String])
{
[void]$StringBuilder.Append($Indenting + $RecursiveIndenting + "'$Item'")
}
ElseIf($Item -is [int] -or $Value -is [double])
{
[void]$StringBuilder.Append($Indenting + $RecursiveIndenting + "$($Item.ToString())")
}
ElseIf($Item -is [bool])
{
[void]$StringBuilder.Append($Indenting + $RecursiveIndenting + "`$$Item")
}
ElseIf($Item -is [array])
{
$Value = Convert-ArrayToString -Array $Item -Flatten:$Flatten
[void]$StringBuilder.Append($Indenting + $RecursiveIndenting + $Value)
}
ElseIf($Item -is [hashtable])
{
$Value = Convert-HashToSTring -Hashtable $Item -Flatten:$Flatten
[void]$StringBuilder.Append($Indenting + $RecursiveIndenting + $Value)
}
Else
{
Throw "Array element is not of known type."
}
If($i -lt ($Array.Count - 1))
{
[void]$StringBuilder.$Mode(', ')
}
ElseIf(-not $Flatten)
{
[void]$StringBuilder.AppendLine('')
}
}
[void]$StringBuilder.Append($RecursiveIndenting + ')')
$StringBuilder.ToString()
}
End{}
}
|
PowerShellCorpus/PowerShellGallery/PSObjectInspector/0.0.1/build/dotSource/Convert-HashToString.ps1
|
Convert-HashToString.ps1
|
function Script:Convert-HashToString
{
[cmdletbinding()]
Param (
[Parameter(Mandatory=$true,Position=0)]
[Hashtable]$Hashtable,
[Parameter(Mandatory=$False)]
[switch]$Flatten
)
Begin{
If($Flatten -or $Hashtable.Keys.Count -eq 0)
{
$Mode = 'Append'
$Indenting = ''
$RecursiveIndenting = ''
}
Else{
$Mode = 'Appendline'
$Indenting = ' '
$RecursiveIndenting = ' ' * (Get-PSCallStack).Where({$_.Command -match 'Convert-ArrayToString|Convert-HashToSTring' -and $_.InvocationInfo.CommandOrigin -eq 'Internal' -and $_.InvocationInfo.Line -notmatch '\$This'}).Count
}
}
Process{
$StringBuilder = [System.Text.StringBuilder]::new()
If($Hashtable.Keys.Count -ge 1)
{
[void]$StringBuilder.$Mode("@{")
}
Else
{
[void]$StringBuilder.Append("@{")
}
Foreach($Key in $Hashtable.Keys)
{
$Value = $Hashtable[$Key]
If($Key -match '\s')
{
$Key = "'$Key'"
}
If($Value -is [String])
{
[void]$StringBuilder.$Mode($Indenting + $RecursiveIndenting + "$Key = '$Value'")
}
ElseIf($Value -is [int] -or $Value -is [double])
{
[void]$StringBuilder.$Mode($Indenting + $RecursiveIndenting + "$Key = $($Value.ToString())")
}
ElseIf($Value -is [bool])
{
[void]$StringBuilder.$Mode($Indenting + $RecursiveIndenting + "$Key = `$$Value")
}
ElseIf($Value -is [array])
{
$Value = Convert-ArrayToString -Array $Value -Flatten:$Flatten
[void]$StringBuilder.$Mode($Indenting + $RecursiveIndenting + "$Key = $Value")
}
ElseIf($Value -is [hashtable])
{
$Value = Convert-HashToSTring -Hashtable $Value -Flatten:$Flatten
[void]$StringBuilder.$Mode($Indenting + $RecursiveIndenting + "$Key = $Value")
}
Else
{
Throw "Key value is not of known type."
}
If($Flatten){[void]$StringBuilder.Append("; ")}
}
[void]$StringBuilder.Append($RecursiveIndenting + "}")
$StringBuilder.ToString().Replace("; }",'}')
}
End{}
}
#Remove-TypeData -TypeName System.Collections.HashTable -ErrorAction SilentlyContinue
#Update-TypeData -TypeName System.Collections.HashTable -MemberType ScriptMethod -MemberName ToString -Value {Convert-HashToString $This}
|
PowerShellCorpus/PowerShellGallery/PSObjectInspector/0.0.1/build/dotSource/Replace-FileString.ps1
|
Replace-FileString.ps1
|
function Script:Replace-FileString {
<#
.SYNOPSIS
Replaces strings in files using a regular expression.
.DESCRIPTION
Replaces strings in files using a regular expression. Supports
multi-line searching and replacing.
.PARAMETER Pattern
Specifies the regular expression pattern.
.PARAMETER Replacement
Specifies the regular expression replacement pattern.
.PARAMETER Path
Specifies the path to one or more files. Wildcards are permitted. Each
file is read entirely into memory to support multi-line searching and
replacing, so performance may be slow for large files.
.PARAMETER LiteralPath
Specifies the path to one or more files. The value of the this
parameter is used exactly as it is typed. No characters are interpreted
as wildcards. Each file is read entirely into memory to support
multi-line searching and replacing, so performance may be slow for
large files.
.PARAMETER CaseSensitive
Specifies case-sensitive matching. The default is to ignore case.
.PARAMETER Multiline
Changes the meaning of ^ and $ so they match at the beginning and end,
respectively, of any line, and not just the beginning and end of the
entire file. The default is that ^ and $, respectively, match the
beginning and end of the entire file.
.PARAMETER UnixText
Causes $ to match only linefeed (\n) characters. By default, $ matches
carriage return+linefeed (\r\n). (Windows-based text files usually use
\r\n as line terminators, while Unix-based text files usually use only
\n.)
.PARAMETER Overwrite
Overwrites a file by creating a temporary file containing all
replacements and then replacing the original file with the temporary
file. The default is to output but not overwrite.
.PARAMETER Force
Allows overwriting of read-only files. Note that this parameter cannot
override security restrictions.
.PARAMETER Encoding
Specifies the encoding for the file when -Overwrite is used. Possible
values are: ASCII, BigEndianUnicode, Unicode, UTF32, UTF7, or UTF8. The
default value is ASCII.
.INPUTS
System.IO.FileInfo.
.OUTPUTS
System.String without the -Overwrite parameter, or nothing with the
-Overwrite parameter.
.LINK
about_Regular_Expressions
.EXAMPLE
C:\>Replace-FileString.ps1 '(Ferb) and (Phineas)' '$2 and $1' Story.txt
This command replaces the string 'Ferb and Phineas' with the string
'Phineas and Ferb' in the file Story.txt and outputs the file. Note
that the pattern and replacement strings are enclosed in single quotes
to prevent variable expansion.
.EXAMPLE
C:\>Replace-FileString.ps1 'Perry' 'Agent P' Ferb.txt -Overwrite
This command replaces the string 'Perry' with the string 'Agent P' in
the file Ferb.txt and overwrites the file.
#>
[CmdletBinding(DefaultParameterSetName="Path",
SupportsShouldProcess=$TRUE)]
param(
[parameter(Mandatory=$TRUE,Position=0)]
[String] $Pattern,
[parameter(Mandatory=$TRUE,Position=1)]
[String] [AllowEmptyString()] $Replacement,
[parameter(Mandatory=$TRUE,ParameterSetName="Path",
Position=2,ValueFromPipeline=$TRUE)]
[String[]] $Path,
[parameter(Mandatory=$TRUE,ParameterSetName="LiteralPath",
Position=2)]
[String[]] $LiteralPath,
[Switch] $CaseSensitive,
[Switch] $Multiline,
[Switch] $UnixText,
[Switch] $Overwrite,
[Switch] $Force,
[String] $Encoding="ASCII"
)
begin {
# Throw an error if $Encoding is not valid.
$encodings = @("ASCII","BigEndianUnicode","Unicode","UTF32","UTF7",
"UTF8")
if ($encodings -notcontains $Encoding) {
throw "Encoding must be one of the following: $encodings"
}
# Extended test-path: Check the parameter set name to see if we
# should use -literalpath or not.
function test-pathEx($path) {
switch ($PSCmdlet.ParameterSetName) {
"Path" {
test-path $path
}
"LiteralPath" {
test-path -literalpath $path
}
}
}
# Extended get-childitem: Check the parameter set name to see if we
# should use -literalpath or not.
function get-childitemEx($path) {
switch ($PSCmdlet.ParameterSetName) {
"Path" {
get-childitem $path -force
}
"LiteralPath" {
get-childitem -literalpath $path -force
}
}
}
# Outputs the full name of a temporary file in the specified path.
function get-tempname($path) {
do {
$tempname = join-path $path ([IO.Path]::GetRandomFilename())
}
while (test-path $tempname)
$tempname
}
# Use '\r$' instead of '$' unless -UnixText specified because
# '$' alone matches '\n', not '\r\n'. Ignore '\$' (literal '$').
if (-not $UnixText) {
$Pattern = $Pattern -replace '(?<!\\)\$', '\r$'
}
# Build an array of Regex options and create the Regex object.
$opts = @()
if (-not $CaseSensitive) { $opts += "IgnoreCase" }
if ($MultiLine) { $opts += "Multiline" }
if ($opts.Length -eq 0) { $opts += "None" }
$regex = new-object Text.RegularExpressions.Regex $Pattern, $opts
}
process {
# The list of items to iterate depends on the parameter set name.
switch ($PSCmdlet.ParameterSetName) {
"Path" { $list = $Path }
"LiteralPath" { $list = $LiteralPath }
}
# Iterate the items in the list of paths. If an item does not exist,
# continue to the next item in the list.
foreach ($item in $list) {
if (-not (test-pathEx $item)) {
write-error "Unable to find '$item'."
continue
}
# Iterate each item in the path. If an item is not a file,
# skip all remaining items.
foreach ($file in get-childitemEx $item) {
if ($file -isnot [IO.FileInfo]) {
write-error "'$file' is not in the file system."
break
}
# Get a temporary file name in the file's directory and create
# it as a empty file. If set-content fails, continue to the next
# file. Better to fail before than after reading the file for
# performance reasons.
if ($Overwrite) {
$tempname = get-tempname $file.DirectoryName
set-content $tempname $NULL -confirm:$FALSE
if (-not $?) { continue }
write-verbose "Created file '$tempname'."
}
# Read all the text from the file into a single string. We have
# to do it this way to be able to search across line breaks.
try {
write-verbose "Reading '$file'."
$text = [IO.File]::ReadAllText($file.FullName)
write-verbose "Finished reading '$file'."
}
catch [Management.Automation.MethodInvocationException] {
write-error $ERROR[0]
continue
}
# If -Overwrite not specified, output the result of the Replace
# method and continue to the next file.
if (-not $Overwrite) {
$regex.Replace($text, $Replacement)
continue
}
# Do nothing further if we're in 'what if' mode.
if ($WHATIFPREFERENCE) { continue }
try {
write-verbose "Writing '$tempname'."
[IO.File]::WriteAllText("$tempname", $regex.Replace($text,
$Replacement), [Text.Encoding]::$Encoding)
write-verbose "Finished writing '$tempname'."
write-verbose "Copying '$tempname' to '$file'."
copy-item $tempname $file -force:$Force -erroraction Continue
if ($?) {
write-verbose "Finished copying '$tempname' to '$file'."
}
remove-item $tempname
if ($?) {
write-verbose "Removed file '$tempname'."
}
}
catch [Management.Automation.MethodInvocationException] {
write-error $ERROR[0]
}
} # foreach $file
} # foreach $item
} # process
end { }
}
|
PowerShellCorpus/PowerShellGallery/PSObjectInspector/0.0.1/build/dotSource/Remove-Signature.ps1
|
Remove-Signature.ps1
|
#requires -Version 2
function Script:Remove-Signature
{
[cmdletbinding()]
Param(
[Parameter(Mandatory = $False,Position = 0,ValueFromPipeline = $True,ValueFromPipelineByPropertyName = $True)]
[Alias('Path')]
[system.io.fileinfo[]]$FilePath
)
Begin{
Push-Location -Path $env:USERPROFILE
}
Process{
$FilePath |
ForEach-Object -Process {
$Item = $_
If($Item.Extension -match '\.ps1|\.psm1|\.psd1|\.ps1xml')
{
Try
{
$Content = Get-Content -Path $Item.FullName -ErrorAction Stop
$StringBuilder = New-Object -TypeName System.Text.StringBuilder -ErrorAction Stop
Foreach($Line in $Content)
{
If($Line -match '^# SIG # Begin signature block|^<!-- SIG # Begin signature block -->')
{
Break
}
Else
{
$null = $StringBuilder.AppendLine($Line)
}
}
Set-Content -Path $Item.FullName -Value $StringBuilder.ToString()
}
Catch
{
Write-Error -Message $_.Exception.Message
}
}
}
}
End{
Pop-Location
}
}
|
PowerShellCorpus/PowerShellGallery/PSObjectInspector/0.0.1/temp/src/other/PostLoad.ps1
|
PostLoad.ps1
|
# Use this variable for any path-sepecific actions (like loading dlls and such) to ensure it will work in testing and after being built
$MyModulePath = $(
Function Get-ScriptPath {
$Invocation = (Get-Variable MyInvocation -Scope 1).Value
if($Invocation.PSScriptRoot) {
$Invocation.PSScriptRoot
}
Elseif($Invocation.MyCommand.Path) {
Split-Path $Invocation.MyCommand.Path
}
elseif ($Invocation.InvocationName.Length -eq 0) {
(Get-Location).Path
}
else {
$Invocation.InvocationName.Substring(0,$Invocation.InvocationName.LastIndexOf("\"));
}
}
Get-ScriptPath
)
if ($host.Name -ne "Windows PowerShell ISE Host")
{
Write-Warning "Runtime Inspector is a PowerShell ISE Addon"
} else {
Add-Type -Path $MyModulePath\RuntimeInspector.dll -PassThru
$typeRuntimeInspector = [IseAddons.VariableExplorer]
$psISE.CurrentPowerShellTab.VerticalAddOnTools.Add("RuntimeInspector", $typeRuntimeInspector, $true)
}
#region Module Cleanup
$ExecutionContext.SessionState.Module.OnRemove = {
# Action to take if the module is removed
$RITab = $psISE.CurrentPowerShellTab.VerticalAddOnTools | Where-Object { $_.Name -eq "RuntimeInspector" }
$OITab = $psISE.CurrentPowerShellTab.HorizontalAddOnTools | Where-Object { $_.Name -eq "OutputInspector" }
if ($RITab) {
$null = $psISE.CurrentPowerShellTab.VerticalAddOnTools.Remove($RITab)
}
if ($OITab) {
$null = $psISE.CurrentPowerShellTab.HorizontalAddOnTools.Remove($OITab)
}
}
$null = Register-EngineEvent -SourceIdentifier ( [System.Management.Automation.PsEngineEvent]::Exiting ) -Action {
# Action to take if the whole pssession is killed
}
#endregion Module Cleanup
# Exported members
#Export-ModuleMember -Variable SomeVariable -Function *
|
PowerShellCorpus/PowerShellGallery/PSObjectInspector/0.0.1/temp/src/public/ObjectModule.ps1
|
ObjectModule.ps1
|
Function Show-Object-Flat {
<#
.SYNOPSIS
Flatten an object to simplify discovery of data
.DESCRIPTION
Flatten an object. This function will take an object, and flatten the properties using their full path into a single object with one layer of properties.
You can use this to flatten XML, JSON, and other arbitrary objects.
This can simplify initial exploration and discovery of data returned by APIs, interfaces, and other technologies.
NOTE:
Use tools like Get-Member, Select-Object, and Show-Object to further explore objects.
This function does not handle certain data types well. It was original designed to expand XML and JSON.
.PARAMETER InputObject
Object to flatten
.PARAMETER Exclude
Exclude any nodes in this list. Accepts wildcards.
Example:
-Exclude price, title
.PARAMETER ExcludeDefault
Exclude default properties for sub objects. True by default.
This simplifies views of many objects (e.g. XML) but may exclude data for others (e.g. if flattening a process, ProcessThread properties will be excluded)
.PARAMETER Include
Include only leaves in this list. Accepts wildcards.
Example:
-Include Author, Title
.PARAMETER Value
Include only leaves with values like these arguments. Accepts wildcards.
.PARAMETER MaxDepth
Stop recursion at this depth.
.INPUTS
Any object
.OUTPUTS
System.Management.Automation.PSCustomObject
.EXAMPLE
#Pull unanswered PowerShell questions from StackExchange, Flatten the data to date a feel for the schema
Invoke-RestMethod "https://api.stackexchange.com/2.0/questions/unanswered?order=desc&sort=activity&tagged=powershell&pagesize=10&site=stackoverflow" |
ConvertTo-FlatObject -Include Title, Link, View_Count
$object.items[0].owner.link : http://stackoverflow.com/users/1946412/julealgon
$object.items[0].view_count : 7
$object.items[0].link : http://stackoverflow.com/questions/26910789/is-it-possible-to-reuse-a-param-block-across-multiple-functions
$object.items[0].title : Is it possible to reuse a 'param' block across multiple functions?
$object.items[1].owner.link : http://stackoverflow.com/users/4248278/nitin-tyagi
$object.items[1].view_count : 8
$object.items[1].link : http://stackoverflow.com/questions/26909879/use-powershell-to-retreive-activated-features-for-sharepoint-2010
$object.items[1].title : Use powershell to retreive Activated features for sharepoint 2010
...
.EXAMPLE
#Set up some XML to work with
$object = [xml]'
<catalog>
<book id="bk101">
<author>Gambardella, Matthew</author>
<title>XML Developers Guide</title>
<genre>Computer</genre>
<price>44.95</price>
</book>
<book id="bk102">
<author>Ralls, Kim</author>
<title>Midnight Rain</title>
<genre>Fantasy</genre>
<price>5.95</price>
</book>
</catalog>'
#Call the flatten command against this XML
ConvertTo-FlatObject $object -Include Author, Title, Price
#Result is a flattened object with the full path to the node, using $object as the root.
#Only leaf properties we specified are included (author,title,price)
$object.catalog.book[0].author : Gambardella, Matthew
$object.catalog.book[0].title : XML Developers Guide
$object.catalog.book[0].price : 44.95
$object.catalog.book[1].author : Ralls, Kim
$object.catalog.book[1].title : Midnight Rain
$object.catalog.book[1].price : 5.95
#Invoking the property names should return their data if the orginal object is in $object:
$object.catalog.book[1].price
5.95
$object.catalog.book[0].title
XML Developers Guide
.EXAMPLE
#Set up some XML to work with
[xml]'<catalog>
<book id="bk101">
<author>Gambardella, Matthew</author>
<title>XML Developers Guide</title>
<genre>Computer</genre>
<price>44.95</price>
</book>
<book id="bk102">
<author>Ralls, Kim</author>
<title>Midnight Rain</title>
<genre>Fantasy</genre>
<price>5.95</price>
</book>
</catalog>' |
ConvertTo-FlatObject -exclude price, title, id
Result is a flattened object with the full path to the node, using XML as the root. Price and title are excluded.
$Object.catalog : catalog
$Object.catalog.book : {book, book}
$object.catalog.book[0].author : Gambardella, Matthew
$object.catalog.book[0].genre : Computer
$object.catalog.book[1].author : Ralls, Kim
$object.catalog.book[1].genre : Fantasy
.EXAMPLE
#Set up some XML to work with
[xml]'<catalog>
<book id="bk101">
<author>Gambardella, Matthew</author>
<title>XML Developers Guide</title>
<genre>Computer</genre>
<price>44.95</price>
</book>
<book id="bk102">
<author>Ralls, Kim</author>
<title>Midnight Rain</title>
<genre>Fantasy</genre>
<price>5.95</price>
</book>
</catalog>' |
ConvertTo-FlatObject -Value XML*, Fantasy
Result is a flattened object filtered by leaves that matched XML* or Fantasy
$Object.catalog.book[0].title : XML Developers Guide
$Object.catalog.book[1].genre : Fantasy
.EXAMPLE
#Get a single process with all props, flatten this object. Don't exclude default properties
Get-Process | select -first 1 -skip 10 -Property * | ConvertTo-FlatObject -ExcludeDefault $false
#NOTE - There will likely be bugs for certain complex objects like this.
For example, $Object.StartInfo.Verbs.SyncRoot.SyncRoot... will loop until we hit MaxDepth. (Note: SyncRoot is now addressed individually)
.NOTES
I have trouble with algorithms. If you have a better way to handle this, please let me know!
.FUNCTIONALITY
General Command
#>
[cmdletbinding()]
param(
[parameter( Mandatory = $True,
ValueFromPipeline = $True)]
[PSObject[]]$InputObject,
[string[]]$Exclude = "",
[bool]$ExcludeDefault = $True,
[string[]]$Include = $null,
[string[]]$Value = $null,
[int]$MaxDepth = 10
)
Begin
{
#region FUNCTIONS
#Before adding a property, verify that it matches a Like comparison to strings in $Include...
Function IsIn-Include {
param($prop)
if(-not $Include) {$True}
else {
foreach($Inc in $Include)
{
if($Prop -like $Inc)
{
$True
}
}
}
}
#Before adding a value, verify that it matches a Like comparison to strings in $Value...
Function IsIn-Value {
param($val)
if(-not $Value) {$True}
else {
foreach($string in $Value)
{
if($val -like $string)
{
$True
}
}
}
}
Function Get-Exclude {
[cmdletbinding()]
param($obj)
#Exclude default props if specified, and anything the user specified. Thanks to Jaykul for the hint on [type]!
if($ExcludeDefault)
{
Try
{
$DefaultTypeProps = @( $obj.gettype().GetProperties() | Select -ExpandProperty Name -ErrorAction Stop )
if($DefaultTypeProps.count -gt 0)
{
Write-Verbose "Excluding default properties for $($obj.gettype().Fullname):`n$($DefaultTypeProps | Out-String)"
}
}
Catch
{
Write-Verbose "Failed to extract properties from $($obj.gettype().Fullname): $_"
$DefaultTypeProps = @()
}
}
@( $Exclude + $DefaultTypeProps ) | Select -Unique
}
#Function to recurse the Object, add properties to object
Function Recurse-Object {
[cmdletbinding()]
param(
$Object,
[string[]]$path = '$Object',
[psobject]$Output,
$depth = 0
)
# Handle initial call
Write-Verbose "Working in path $Path at depth $depth"
Write-Debug "Recurse Object called with PSBoundParameters:`n$($PSBoundParameters | Out-String)"
$Depth++
#Exclude default props if specified, and anything the user specified.
$ExcludeProps = @( Get-Exclude $object )
#Get the children we care about, and their names
$Children = $object.psobject.properties | Where {$ExcludeProps -notcontains $_.Name }
Write-Debug "Working on properties:`n$($Children | select -ExpandProperty Name | Out-String)"
#Loop through the children properties.
foreach($Child in @($Children))
{
$ChildName = $Child.Name
$ChildValue = $Child.Value
Write-Debug "Working on property $ChildName with value $($ChildValue | Out-String)"
# Handle special characters...
if($ChildName -match '[^a-zA-Z0-9_]')
{
$FriendlyChildName = "'$ChildName'"
}
else
{
$FriendlyChildName = $ChildName
}
#Add the property.
if((IsIn-Include $ChildName) -and (IsIn-Value $ChildValue) -and $Depth -le $MaxDepth)
{
$ThisPath = @( $Path + $FriendlyChildName ) -join "."
$Output | Add-Member -MemberType NoteProperty -Name $ThisPath -Value $ChildValue
Write-Verbose "Adding member '$ThisPath'"
}
#Handle null...
if($ChildValue -eq $null)
{
Write-Verbose "Skipping NULL $ChildName"
continue
}
#Handle evil looping. Will likely need to expand this. Any thoughts on a better approach?
if(
(
$ChildValue.GetType() -eq $Object.GetType() -and
$ChildValue -is [datetime]
) -or
(
$ChildName -eq "SyncRoot" -and
-not $ChildValue
)
)
{
Write-Verbose "Skipping $ChildName with type $($ChildValue.GetType().fullname)"
continue
}
#Check for arrays
$IsArray = @($ChildValue).count -gt 1
$count = 0
#Set up the path to this node and the data...
$CurrentPath = @( $Path + $FriendlyChildName ) -join "."
#Exclude default props if specified, and anything the user specified.
$ExcludeProps = @( Get-Exclude $ChildValue )
#Get the children's children we care about, and their names. Also look for signs of a hashtable like type
$ChildrensChildren = $ChildValue.psobject.properties | Where {$ExcludeProps -notcontains $_.Name }
$HashKeys = if($ChildValue.Keys -notlike $null -and $ChildValue.Values)
{
$ChildValue.Keys
}
else
{
$null
}
Write-Debug "Found children's children $($ChildrensChildren | select -ExpandProperty Name | Out-String)"
#If we aren't at max depth or a leaf...
if(
(@($ChildrensChildren).count -ne 0 -or $HashKeys) -and
$Depth -lt $MaxDepth
)
{
#This handles hashtables. But it won't recurse...
if($HashKeys)
{
Write-Verbose "Working on hashtable $CurrentPath"
foreach($key in $HashKeys)
{
Write-Verbose "Adding value from hashtable $CurrentPath['$key']"
$Output | Add-Member -MemberType NoteProperty -name "$CurrentPath['$key']" -value $ChildValue["$key"]
$Output = Recurse-Object -Object $ChildValue["$key"] -Path "$CurrentPath['$key']" -Output $Output -depth $depth
}
}
#Sub children? Recurse!
else
{
if($IsArray)
{
foreach($item in @($ChildValue))
{
Write-Verbose "Recursing through array node '$CurrentPath'"
$Output = Recurse-Object -Object $item -Path "$CurrentPath[$count]" -Output $Output -depth $depth
$Count++
}
}
else
{
Write-Verbose "Recursing through node '$CurrentPath'"
$Output = Recurse-Object -Object $ChildValue -Path $CurrentPath -Output $Output -depth $depth
}
}
}
}
$Output
}
#endregion FUNCTIONS
}
Process
{
Foreach($Object in $InputObject)
{
#Flatten the XML and write it to the pipeline
Recurse-Object -Object $Object -Output $( New-Object -TypeName PSObject )
}
}
}
function Show-Object-Detail
{
<#
.SYNOPSIS
Decorate an object with
- A TypeName
- New properties
- Default parameters
.DESCRIPTION
Helper function to decorate an object with
- A TypeName
- New properties
- Default parameters
.PARAMETER InputObject
Object to decorate. Accepts pipeline input.
.PARAMETER TypeName
Typename to insert.
This will show up when you use Get-Member against the resulting object.
.PARAMETER PropertyToAdd
Add these noteproperties.
Format is a hashtable with Key (Property Name) = Value (Property Value).
Example to add a One and Date property:
-PropertyToAdd @{
One = 1
Date = (Get-Date)
}
.PARAMETER DefaultProperties
Change the default properties that show up
.PARAMETER Passthru
Whether to pass the resulting object on. Defaults to true
.EXAMPLE
#
# Create an object to work with
$Object = [PSCustomObject]@{
First = 'Cookie'
Last = 'Monster'
Account = 'CMonster'
}
#Add a type name and a random property
Add-ObjectDetail -InputObject $Object -TypeName 'ApplicationX.Account' -PropertyToAdd @{ AnotherProperty = 5 }
# First Last Account AnotherProperty
# ----- ---- ------- ---------------
# Cookie Monster CMonster 5
#Verify that get-member shows us the right type
$Object | Get-Member
# TypeName: ApplicationX.Account ...
.EXAMPLE
#
# Create an object to work with
$Object = [PSCustomObject]@{
First = 'Cookie'
Last = 'Monster'
Account = 'CMonster'
}
#Add a random property, set a default property set so we only see two props by default
Add-ObjectDetail -InputObject $Object -PropertyToAdd @{ AnotherProperty = 5 } -DefaultProperties Account, AnotherProperty
# Account AnotherProperty
# ------- ---------------
# CMonster 5
#Verify that the other properties are around
$Object | Select -Property *
# First Last Account AnotherProperty
# ----- ---- ------- ---------------
# Cookie Monster CMonster 5
.NOTES
This breaks the 'do one thing' rule from certain perspectives...
The goal is to decorate an object all in one shot
This abstraction simplifies decorating an object, with a slight trade-off in performance. For example:
10,000 objects, add a property and typename:
Add-ObjectDetail: ~4.6 seconds
Add-Member + PSObject.TypeNames.Insert: ~3 seconds
Initial code borrowed from Shay Levy:
http://blogs.microsoft.co.il/scriptfanatic/2012/04/13/custom-objects-default-display-in-powershell-30/
.LINK
http://ramblingcookiemonster.github.io/Decorating-Objects/
.FUNCTIONALITY
PowerShell Language
#>
[CmdletBinding()]
param(
[Parameter( Mandatory = $true,
Position=0,
ValueFromPipeline=$true )]
[ValidateNotNullOrEmpty()]
[psobject[]]$InputObject,
[Parameter( Mandatory = $false,
Position=1)]
[string]$TypeName,
[Parameter( Mandatory = $false,
Position=2)]
[System.Collections.Hashtable]$PropertyToAdd,
[Parameter( Mandatory = $false,
Position=3)]
[ValidateNotNullOrEmpty()]
[Alias('dp')]
[System.String[]]$DefaultProperties,
[boolean]$Passthru = $True
)
Begin
{
if($PSBoundParameters.ContainsKey('DefaultProperties'))
{
# define a subset of properties
$ddps = New-Object System.Management.Automation.PSPropertySet DefaultDisplayPropertySet,$DefaultProperties
$PSStandardMembers = [System.Management.Automation.PSMemberInfo[]]$ddps
}
}
Process
{
foreach($Object in $InputObject)
{
switch ($PSBoundParameters.Keys)
{
'PropertyToAdd'
{
foreach($Key in $PropertyToAdd.Keys)
{
#Add some noteproperties. Slightly faster than Add-Member.
$Object.PSObject.Properties.Add( ( New-Object System.Management.Automation.PSNoteProperty($Key, $PropertyToAdd[$Key]) ) )
}
}
'TypeName'
{
#Add specified type
[void]$Object.PSObject.TypeNames.Insert(0,$TypeName)
}
'DefaultProperties'
{
# Attach default display property set
Add-Member -InputObject $Object -MemberType MemberSet -Name PSStandardMembers -Value $PSStandardMembers
}
}
if($Passthru)
{
$Object
}
}
}
}
function Show-Object-List
{
#############################################################################
##
## Show-Object
##
## From Windows PowerShell Cookbook (O'Reilly)
## by Lee Holmes (http://www.leeholmes.com/guide)
##
##############################################################################
<#
.SYNOPSIS
Spelunking with Show-Object
.DESCRIPTION
Spelunk [spi-luhngk], verb. To explore caves, especially as a hobby.
We must first recall that PowerShell pipelines are very different from, say, Linux pipelines. Rather than consisting of text, PowerShell objects are "three-dimensional" data structures that consist of properties (descriptive attributes), methods (actions the object can undertake), and events (actions that can be undertaken on the object). Collectively, these data elements are called object members.
For instance, take Get-Service. Unless you perform filtering, you receive an object collection as output. You probably know that Get-Member shows us the object's .NET Framework type name and its properties, methods, and events. Here's partial output from my Windows 8.1 administrative workstation running Windows Management Framework 5.0 Production Preview:
PS C:\> Get-Service | Get-Member
TypeName: System.ServiceProcess.ServiceController
Name MemberType Definition
—- ———- ———-
Name AliasProperty Name = ServiceName
RequiredServices AliasProperty RequiredServices…
Disposed Event System.EventHandler…
Close Method void Close()
Continue Method void Continue()
PowerShell objects are instances of underlying .NET classes, and by default those classes are self-discovering through a process known as reflection. If you want to see everything about the previous ServiceController objects, pipe the Get-Member output to Format-List like so:
Get-Service | Get-Member | Format-List *
What I've told you means that, practically speaking, we do an awful lot of get-membering and format-listing when we need to look up specific property, method, or event values. Is there (banish the thought!) an easier-on-the-eyes graphical solution?
.EXAMPLE
First we can locate the appropriate module:
Find-Module -Name *cookbook*
Cool. So Lee's module is named PowerShellCookbook, and it is stored on the PowerShell Gallery repository. Let's install it!
Install-Module -Name PowerShellCookbook -Force
As it happens, Show-Object is only one function among many that are contained in the PowerShellCookbook module. Run the following command to see them all:
Get-Command -Module PowerShellCookbook
Using the Show-Object Function
To use Show-Object, simply pipe your desired PowerShell object into the function like so:
Get-Service -Name Spooler | Show-Object
Take a look at the following Show-Object output, and I'll walk you through it.
The bottom pane (sadly unresizable) shows your ordinary Get-Member output. The upper pane allows you to quickly parse the object properties. For instance, we can expand each RequiredServices node to learn that the Print Spooler service in Windows 8.1 depends on a Remote Procedure Call (RPC) and HTTP services.
If you're of the mind to do so, you can inspect the Show-Object source code by visiting the book's website (see Program: Interactively View and Explore Objects) or by using PowerShell directly in your console:
(Get-Command -name Show-Object).Definition | Out-File 'C:\show-object-source.txt' | Notepad 'C:\show-object-source.txt'
Going further
One of the many things I love about the Windows PowerShell community is how friendly and helpful most people are. I don't want to draw comparisons to, say, the *NIX open-source community, but…well, let's just leave that alone.
That's all there is to it!
.FUNCTIONALITY
General Command
#>
param(
## The object to examine
[Parameter(ValueFromPipeline = $true)]
$InputObject
)
Set-StrictMode -Version 3
Add-Type -Assembly System.Windows.Forms
## Figure out the variable name to use when displaying the
## object navigation syntax. To do this, we look through all
## of the variables for the one with the same object identifier.
$rootVariableName = dir variable:\* -Exclude InputObject,Args |
Where-Object {
$_.Value -and
($_.Value.GetType() -eq $InputObject.GetType()) -and
($_.Value.GetHashCode() -eq $InputObject.GetHashCode())
}
## If we got multiple, pick the first
$rootVariableName = $rootVariableName| % Name | Select -First 1
## If we didn't find one, use a default name
if(-not $rootVariableName)
{
$rootVariableName = "InputObject"
}
## A function to add an object to the display tree
function PopulateNode($node, $object)
{
## If we've been asked to add a NULL object, just return
if(-not $object) { return }
## If the object is a collection, then we need to add multiple
## children to the node
if([System.Management.Automation.LanguagePrimitives]::GetEnumerator($object))
{
## Some very rare collections don't support indexing (i.e.: $foo[0]).
## In this situation, PowerShell returns the parent object back when you
## try to access the [0] property.
$isOnlyEnumerable = $object.GetHashCode() -eq $object[0].GetHashCode()
## Go through all the items
$count = 0
foreach($childObjectValue in $object)
{
## Create the new node to add, with the node text of the item and
## value, along with its type
$newChildNode = New-Object Windows.Forms.TreeNode
$newChildNode.Text = "$($node.Name)[$count] = $childObjectValue"
$newChildNode.ToolTipText = $childObjectValue.GetType()
## Use the node name to keep track of the actual property name
## and syntax to access that property.
## If we can't use the index operator to access children, add
## a special tag that we'll handle specially when displaying
## the node names.
if($isOnlyEnumerable)
{
$newChildNode.Name = "@"
}
$newChildNode.Name += "[$count]"
$null = $node.Nodes.Add($newChildNode)
## If this node has children or properties, add a placeholder
## node underneath so that the node shows a '+' sign to be
## expanded.
AddPlaceholderIfRequired $newChildNode $childObjectValue
$count++
}
}
else
{
## If the item was not a collection, then go through its
## properties
foreach($child in $object.PSObject.Properties)
{
## Figure out the value of the property, along with
## its type.
$childObject = $child.Value
$childObjectType = $null
if($childObject)
{
$childObjectType = $childObject.GetType()
}
## Create the new node to add, with the node text of the item and
## value, along with its type
$childNode = New-Object Windows.Forms.TreeNode
$childNode.Text = $child.Name + " = $childObject"
$childNode.ToolTipText = $childObjectType
if([System.Management.Automation.LanguagePrimitives]::GetEnumerator($childObject))
{
$childNode.ToolTipText += "[]"
}
$childNode.Name = $child.Name
$null = $node.Nodes.Add($childNode)
## If this node has children or properties, add a placeholder
## node underneath so that the node shows a '+' sign to be
## expanded.
AddPlaceholderIfRequired $childNode $childObject
}
}
}
## A function to add a placeholder if required to a node.
## If there are any properties or children for this object, make a temporary
## node with the text "..." so that the node shows a '+' sign to be
## expanded.
function AddPlaceholderIfRequired($node, $object)
{
if(-not $object) { return }
if([System.Management.Automation.LanguagePrimitives]::GetEnumerator($object) -or
@($object.PSObject.Properties))
{
$null = $node.Nodes.Add( (New-Object Windows.Forms.TreeNode "...") )
}
}
## A function invoked when a node is selected.
function OnAfterSelect
{
param($Sender, $TreeViewEventArgs)
## Determine the selected node
$nodeSelected = $Sender.SelectedNode
## Walk through its parents, creating the virtual
## PowerShell syntax to access this property.
$nodePath = GetPathForNode $nodeSelected
## Now, invoke that PowerShell syntax to retrieve
## the value of the property.
$resultObject = Invoke-Expression $nodePath
$outputPane.Text = $nodePath
## If we got some output, put the object's member
## information in the text box.
if($resultObject)
{
$members = Get-Member -InputObject $resultObject | Out-String
$outputPane.Text += "`n" + $members
}
}
## A function invoked when the user is about to expand a node
function OnBeforeExpand
{
param($Sender, $TreeViewCancelEventArgs)
## Determine the selected node
$selectedNode = $TreeViewCancelEventArgs.Node
## If it has a child node that is the placeholder, clear
## the placehoder node.
if($selectedNode.FirstNode -and
($selectedNode.FirstNode.Text -eq "..."))
{
$selectedNode.Nodes.Clear()
}
else
{
return
}
## Walk through its parents, creating the virtual
## PowerShell syntax to access this property.
$nodePath = GetPathForNode $selectedNode
## Now, invoke that PowerShell syntax to retrieve
## the value of the property.
Invoke-Expression "`$resultObject = $nodePath"
## And populate the node with the result object.
PopulateNode $selectedNode $resultObject
}
## A function to handle key presses on the tree view.
## In this case, we capture ^C to copy the path of
## the object property that we're currently viewing.
function OnTreeViewKeyPress
{
param($Sender, $KeyPressEventArgs)
## [Char] 3 = Control-C
if($KeyPressEventArgs.KeyChar -eq 3)
{
$KeyPressEventArgs.Handled = $true
## Get the object path, and set it on the clipboard
$node = $Sender.SelectedNode
$nodePath = GetPathForNode $node
[System.Windows.Forms.Clipboard]::SetText($nodePath)
$form.Close()
}
elseif([System.Windows.Forms.Control]::ModifierKeys -eq "Control")
{
if($KeyPressEventArgs.KeyChar -eq '+')
{
$SCRIPT:currentFontSize++
UpdateFonts $SCRIPT:currentFontSize
$KeyPressEventArgs.Handled = $true
}
elseif($KeyPressEventArgs.KeyChar -eq '-')
{
$SCRIPT:currentFontSize--
if($SCRIPT:currentFontSize -lt 1) { $SCRIPT:currentFontSize = 1 }
UpdateFonts $SCRIPT:currentFontSize
$KeyPressEventArgs.Handled = $true
}
}
}
## A function to handle key presses on the form.
## In this case, we handle Ctrl-Plus and Ctrl-Minus
## to adjust font size.
function OnKeyUp
{
param($Sender, $KeyUpEventArgs)
if([System.Windows.Forms.Control]::ModifierKeys -eq "Control")
{
if($KeyUpEventArgs.KeyCode -in 'Add','OemPlus')
{
$SCRIPT:currentFontSize++
UpdateFonts $SCRIPT:currentFontSize
$KeyUpEventArgs.Handled = $true
}
elseif($KeyUpEventArgs.KeyCode -in 'Subtract','OemMinus')
{
$SCRIPT:currentFontSize--
if($SCRIPT:currentFontSize -lt 1) { $SCRIPT:currentFontSize = 1 }
UpdateFonts $SCRIPT:currentFontSize
$KeyUpEventArgs.Handled = $true
}
elseif($KeyUpEventArgs.KeyCode -eq 'D0')
{
$SCRIPT:currentFontSize = 12
UpdateFonts $SCRIPT:currentFontSize
$KeyUpEventArgs.Handled = $true
}
}
}
## A function to handle mouse wheel scrolling.
## In this case, we translate Ctrl-Wheel to zoom.
function OnMouseWheel
{
param($Sender, $MouseEventArgs)
if(
([System.Windows.Forms.Control]::ModifierKeys -eq "Control") -and
($MouseEventArgs.Delta -ne 0))
{
$SCRIPT:currentFontSize += ($MouseEventArgs.Delta / 120)
if($SCRIPT:currentFontSize -lt 1) { $SCRIPT:currentFontSize = 1 }
UpdateFonts $SCRIPT:currentFontSize
$MouseEventArgs.Handled = $true
}
}
## A function to walk through the parents of a node,
## creating virtual PowerShell syntax to access this property.
function GetPathForNode
{
param($Node)
$nodeElements = @()
## Go through all the parents, adding them so that
## $nodeElements is in order.
while($Node)
{
$nodeElements = ,$Node + $nodeElements
$Node = $Node.Parent
}
## Now go through the node elements
$nodePath = ""
foreach($Node in $nodeElements)
{
$nodeName = $Node.Name
## If it was a node that PowerShell is able to enumerate
## (but not index), wrap it in the array cast operator.
if($nodeName.StartsWith('@'))
{
$nodeName = $nodeName.Substring(1)
$nodePath = "@(" + $nodePath + ")"
}
elseif($nodeName.StartsWith('['))
{
## If it's a child index, we don't need to
## add the dot for property access
}
elseif($nodePath)
{
## Otherwise, we're accessing a property. Add a dot.
$nodePath += "."
}
## Append the node name to the path
$tempNodePath = $nodePath + $nodeName
if($nodeName -notmatch '^[$\[\]a-zA-Z0-9]+$')
{
$nodePath += "'" + $nodeName + "'"
}
else
{
$nodePath = $tempNodePath
}
}
## And return the result
$nodePath
}
function UpdateFonts
{
param($fontSize)
$treeView.Font = New-Object System.Drawing.Font "Consolas",$fontSize
$outputPane.Font = New-Object System.Drawing.Font "Consolas",$fontSize
}
$SCRIPT:currentFontSize = 12
## Create the TreeView, which will hold our object navigation
## area.
$treeView = New-Object Windows.Forms.TreeView
$treeView.Dock = "Top"
$treeView.Height = 500
$treeView.PathSeparator = "."
$treeView.ShowNodeToolTips = $true
$treeView.Add_AfterSelect( { OnAfterSelect @args } )
$treeView.Add_BeforeExpand( { OnBeforeExpand @args } )
$treeView.Add_KeyPress( { OnTreeViewKeyPress @args } )
## Create the output pane, which will hold our object
## member information.
$outputPane = New-Object System.Windows.Forms.TextBox
$outputPane.Multiline = $true
$outputPane.WordWrap = $false
$outputPane.ScrollBars = "Both"
$outputPane.Dock = "Fill"
## Create the root node, which represents the object
## we are trying to show.
$root = New-Object Windows.Forms.TreeNode
$root.ToolTipText = $InputObject.GetType()
$root.Text = $InputObject
$root.Name = '$' + $rootVariableName
$root.Expand()
$null = $treeView.Nodes.Add($root)
UpdateFonts $currentFontSize
## And populate the initial information into the tree
## view.
PopulateNode $root $InputObject
## Finally, create the main form and show it.
$form = New-Object Windows.Forms.Form
$form.Text = "Browsing " + $root.Text
$form.Width = 1000
$form.Height = 800
$form.Controls.Add($outputPane)
$form.Controls.Add($treeView)
$form.Add_MouseWheel( { OnMouseWheel @args } )
$treeView.Add_KeyUp( { OnKeyUp @args } )
$treeView.Select()
$null = $form.ShowDialog()
$form.Dispose()
}
function Show-Object-Tree{
<#
.SYNOPSIS
Spelunking with Show-Object
.DESCRIPTION
Spelunk [spi-luhngk], verb. To explore caves, especially as a hobby.
We must first recall that PowerShell pipelines are very different from, say, Linux pipelines. Rather than consisting of text, PowerShell objects are "three-dimensional" data structures that consist of properties (descriptive attributes), methods (actions the object can undertake), and events (actions that can be undertaken on the object). Collectively, these data elements are called object members.
For instance, take Get-Service. Unless you perform filtering, you receive an object collection as output. You probably know that Get-Member shows us the object's .NET Framework type name and its properties, methods, and events. Here's partial output from my Windows 8.1 administrative workstation running Windows Management Framework 5.0 Production Preview:
PS C:\> Get-Service | Get-Member
TypeName: System.ServiceProcess.ServiceController
Name MemberType Definition
—- ———- ———-
Name AliasProperty Name = ServiceName
RequiredServices AliasProperty RequiredServices…
Disposed Event System.EventHandler…
Close Method void Close()
Continue Method void Continue()
PowerShell objects are instances of underlying .NET classes, and by default those classes are self-discovering through a process known as reflection. If you want to see everything about the previous ServiceController objects, pipe the Get-Member output to Format-List like so:
Get-Service | Get-Member | Format-List *
What I've told you means that, practically speaking, we do an awful lot of get-membering and format-listing when we need to look up specific property, method, or event values. Is there (banish the thought!) an easier-on-the-eyes graphical solution?
.EXAMPLE
First we can locate the appropriate module:
Find-Module -Name *cookbook*
Cool. So Lee's module is named PowerShellCookbook, and it is stored on the PowerShell Gallery repository. Let's install it!
Install-Module -Name PowerShellCookbook -Force
As it happens, Show-Object is only one function among many that are contained in the PowerShellCookbook module. Run the following command to see them all:
Get-Command -Module PowerShellCookbook
Using the Show-Object Function
To use Show-Object, simply pipe your desired PowerShell object into the function like so:
Get-Service -Name Spooler | Show-Object
Take a look at the following Show-Object output, and I'll walk you through it.
The bottom pane (sadly unresizable) shows your ordinary Get-Member output. The upper pane allows you to quickly parse the object properties. For instance, we can expand each RequiredServices node to learn that the Print Spooler service in Windows 8.1 depends on a Remote Procedure Call (RPC) and HTTP services.
If you're of the mind to do so, you can inspect the Show-Object source code by visiting the book's website (see Program: Interactively View and Explore Objects) or by using PowerShell directly in your console:
(Get-Command -name Show-Object).Definition | Out-File 'C:\show-object-source.txt' | Notepad 'C:\show-object-source.txt'
Going further
One of the many things I love about the Windows PowerShell community is how friendly and helpful most people are. I don't want to draw comparisons to, say, the *NIX open-source community, but…well, let's just leave that alone.
That's all there is to it!
.FUNCTIONALITY
General Command
#>
param(
## The object to examine
[Parameter(ValueFromPipeline = $true)]
$InputObject
)
#custom controls for treeview... found it on MSDN a while ago, lost link :-/
[void][System.Reflection.Assembly]::LoadWithPartialName('presentationframework')
add-type @"
using System;
using System.Windows.Controls;
using System.Windows;
using System.Windows.Data;
using System.Globalization;
namespace _treeListView
{
public class TreeListView : TreeView
{
protected override DependencyObject GetContainerForItemOverride()
{
return new TreeListViewItem();
}
protected override bool IsItemItsOwnContainerOverride(object item)
{
return item is TreeListViewItem;
}
}
public class TreeListViewItem : TreeViewItem
{
private int _level = -1;
public int Level
{
get
{
if (_level != -1) return _level;
var parent = ItemsControl.ItemsControlFromItemContainer(this) as TreeListViewItem;
_level = (parent != null) ? parent.Level + 1 : 0;
return _level;
}
}
public TreeListViewItem(object header)
{
Header = header;
}
public TreeListViewItem(){}
protected override DependencyObject GetContainerForItemOverride()
{
return new TreeListViewItem();
}
protected override bool IsItemItsOwnContainerOverride(object item)
{
return item is TreeListViewItem;
}
}
public class LevelToIndentConverter : IValueConverter
{
private const double c_IndentSize = 19.0;
public object Convert(object o, Type type, object parameter,CultureInfo culture)
{
return new Thickness((int)o * c_IndentSize, 0, 0, 0);
}
public object ConvertBack(object o, Type type, object parameter,CultureInfo culture)
{
throw new NotSupportedException();
}
}
}
"@ -ReferencedAssemblies presentationFramework,PresentationCore,WindowsBase,System.Xaml -ErrorAction SilentlyContinue
## form layout
[xml]$xaml = @"
<Window xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:s='clr-namespace:System;assembly=mscorlib'
xmlns:l='clr-namespace:_treeListView;assembly=$([_treeListView.LevelToIndentConverter].Assembly)'
Title="TreeListView" Width="640" Height="480">
<Window.Resources>
<Style x:Key="ExpandCollapseToggleStyle"
TargetType="{x:Type ToggleButton}">
<Setter Property="Focusable" Value="False"/>
<Setter Property="Width" Value="19"/>
<Setter Property="Height" Value="13"/>
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type ToggleButton}">
<Border Width="19" Height="13" Background="Transparent">
<Border Width="9" Height="9" BorderThickness="1" BorderBrush="#FF7898B5" CornerRadius="1" SnapsToDevicePixels="true">
<Border.Background>
<LinearGradientBrush StartPoint="0,0" EndPoint="1,1">
<LinearGradientBrush.GradientStops>
<GradientStop Color="White" Offset=".2"/>
<GradientStop Color="#FFC0B7A6" Offset="1"/>
</LinearGradientBrush.GradientStops>
</LinearGradientBrush>
</Border.Background>
<Path x:Name="ExpandPath" Margin="1,1,1,1" Fill="Black"
Data="M 0 2 L 0 3 L 2 3 L 2 5 L 3 5 L 3 3 L 5 3 L 5 2 L 3 2 L 3 0 L 2 0 L 2 2 Z"/>
</Border>
</Border>
<ControlTemplate.Triggers>
<Trigger Property="IsChecked" Value="True">
<Setter Property="Data" TargetName="ExpandPath" Value="M 0 2 L 0 3 L 5 3 L 5 2 Z"/>
</Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
<l:LevelToIndentConverter x:Key="LevelToIndentConverter"/>
<DataTemplate x:Key="CellTemplate_Name">
<DockPanel>
<ToggleButton x:Name="Expander"
Style="{StaticResource ExpandCollapseToggleStyle}"
Margin="{Binding Level, Converter={StaticResource LevelToIndentConverter},
RelativeSource={RelativeSource AncestorType={x:Type l:TreeListViewItem}}}"
IsChecked="{Binding Path=IsExpanded, RelativeSource=
{RelativeSource AncestorType={x:Type l:TreeListViewItem}}}"
ClickMode="Press"/>
<TextBlock Text="{Binding Name}"/>
</DockPanel>
<DataTemplate.Triggers>
<DataTrigger Binding="{Binding Path=HasItems,RelativeSource={RelativeSource AncestorType={x:Type l:TreeListViewItem}}}" Value="False">
<Setter TargetName="Expander" Property="Visibility" Value="Hidden"/>
</DataTrigger>
</DataTemplate.Triggers>
</DataTemplate>
<GridViewColumnCollection x:Key="gvcc">
<GridViewColumn Header="Name" CellTemplate="{StaticResource CellTemplate_Name}" />
<GridViewColumn Header="MemberType" DisplayMemberBinding="{Binding MemberType}" />
<GridViewColumn Header="Definition" DisplayMemberBinding="{Binding Definition}" />
<GridViewColumn Header="Value" DisplayMemberBinding="{Binding Value}" />
</GridViewColumnCollection>
<Style TargetType="{x:Type l:TreeListViewItem}">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type l:TreeListViewItem}">
<StackPanel>
<Border Name="Bd"
Background="{TemplateBinding Background}"
BorderBrush="{TemplateBinding BorderBrush}"
BorderThickness="{TemplateBinding BorderThickness}"
Padding="{TemplateBinding Padding}">
<GridViewRowPresenter x:Name="PART_Header"
Content="{TemplateBinding Header}"
Columns="{StaticResource gvcc}" />
</Border>
<ItemsPresenter x:Name="ItemsHost" />
</StackPanel>
<ControlTemplate.Triggers>
<Trigger Property="IsExpanded" Value="false">
<Setter TargetName="ItemsHost" Property="Visibility" Value="Collapsed"/>
</Trigger>
<MultiTrigger>
<MultiTrigger.Conditions>
<Condition Property="HasHeader" Value="false"/>
<Condition Property="Width" Value="Auto"/>
</MultiTrigger.Conditions>
<Setter TargetName="PART_Header" Property="MinWidth" Value="75"/>
</MultiTrigger>
<MultiTrigger>
<MultiTrigger.Conditions>
<Condition Property="HasHeader" Value="false"/>
<Condition Property="Height" Value="Auto"/>
</MultiTrigger.Conditions>
<Setter TargetName="PART_Header" Property="MinHeight" Value="19"/>
</MultiTrigger>
<Trigger Property="IsSelected" Value="true">
<Setter TargetName="Bd" Property="Background" Value="{DynamicResource {x:Static SystemColors.HighlightBrushKey}}"/>
<Setter Property="Foreground" Value="{DynamicResource {x:Static SystemColors.HighlightTextBrushKey}}"/>
</Trigger>
<MultiTrigger>
<MultiTrigger.Conditions>
<Condition Property="IsSelected" Value="true"/>
<Condition Property="IsSelectionActive" Value="false"/>
</MultiTrigger.Conditions>
<Setter TargetName="Bd" Property="Background" Value="{DynamicResource {x:Static SystemColors.ControlBrushKey}}"/>
<Setter Property="Foreground" Value="{DynamicResource {x:Static SystemColors.ControlTextBrushKey}}"/>
</MultiTrigger>
<Trigger Property="IsEnabled" Value="false">
<Setter Property="Foreground" Value="{DynamicResource {x:Static SystemColors.GrayTextBrushKey}}"/>
</Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
<Style TargetType="{x:Type l:TreeListView}">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type l:TreeListView}">
<Border BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="{TemplateBinding BorderThickness}">
<DockPanel>
<GridViewHeaderRowPresenter Columns="{StaticResource gvcc}" DockPanel.Dock="Top"/>
<ScrollViewer CanContentScroll="True">
<Grid>
<ItemsPresenter/>
</Grid>
</ScrollViewer>
</DockPanel>
</Border>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</Window.Resources>
<l:TreeListView x:Name="Tlv"/>
</Window>
"@
$rootVariableName = dir variable:\* -Exclude InputObject,Args |
Where-Object {
$_.Value -and
($_.Value.GetType() -eq $InputObject.GetType()) -and
($_.Value.GetHashCode() -eq $InputObject.GetHashCode())
}
## If we got multiple, pick the first
$rootVariableName = $rootVariableName| % Name | Select -First 1
## If we didn't find one, use a default name
if(-not $rootVariableName)
{
$rootVariableName = "InputObject"
}
## A function to add an object to the display tree
function PopulateNode($node, $object)
{
## If we've been asked to add a NULL object, just return
if(-not $object) { return }
## If the object is a collection, then we need to add multiple
## children to the node
if([System.Management.Automation.LanguagePrimitives]::GetEnumerator($object))
{
## Some very rare collections don't support indexing (i.e.: $foo[0]).
## In this situation, PowerShell returns the parent object back when you
## try to access the [0] property.
$isOnlyEnumerable = $object.GetHashCode() -eq $object[0].GetHashCode()
## Go through all the items
$count = 0
foreach($childObjectValue in $object)
{
## Create the new node to add, with the node text of the item and
## value, along with its type
$newChildNode = New-Object _treeListView.TreeListViewItem
#make sure the string version of it isnt more than a single line.
$showValue = if(($arr="$childObjectValue" -split "\n" | ?{$_}).count -gt 1)
{
"$($arr[0].trim()) ..."
}
else
{
"$childObjectValue"
}
$newChildNode.ToolTip = "$childObjectValue"
$newChildNode.Header = [pscustomobject] @{
Name=$childObjectValue.GetType().name
Value="$showValue"
Definition=$childObjectValue.gettype()
MemberType="Collection"
}
## Use the node name to keep track of the actual property name
## and syntax to access that property.
## If we can't use the index operator to access children, add
## a special tag that we'll handle specially when displaying
## the node names.
if($isOnlyEnumerable)
{
$newChildNode.Tag = "@"
}
$newChildNode.Tag += "[$count]"
$null = $node.Items.Add($newChildNode)
## If this node has children or properties, add a placeholder
## node underneath so that the node shows a '+' sign to be
## expanded.
AddPlaceholderIfRequired $newChildNode $childObjectValue
$count++
}
}
else
{
## If the item was not a collection, then go through its
## properties
$members = Get-Member -InputObject $object
foreach($member in $members)
{
$childNode = New-Object _treeListView.TreeListViewItem
$memberValue = if($member.MemberType -like "*Propert*")
{
$prop = $object.($member.Name)
if($prop)
{
$prop
$childnode.ToolTip = $prop
if($prop.gettype().fullname | ?{($_ -split '\.').count -gt 2})
{
AddPlaceholderIfRequired $childNode $prop
}
}
else { '$null' }
}
elseif($member.MemberType -eq "Method")
{
$childNode.ToolTip = ($object.($member.name) | Out-String).trim()
}
$showValue = if(($arr="$memberValue" -split "\n"|?{$_}).count -gt 1)
{
"$($arr[0].trim()) ..."
}
else
{
"$memberValue"
}
$childNode.Header = [pscustomobject] @{
Name=$member.name
Value=$showValue
Definition=$member.Definition
MemberType=$member.MemberType
}
$childNode.Tag = $member.Name
$null = $node.Items.Add($childNode)
}
}
}
## A function to add a placeholder if required to a node.
## If there are any properties or children for this object, make a temporary
## node with the text "..." so that the node shows a '+' sign to be
## expanded.
function AddPlaceholderIfRequired($node, $object)
{
if(-not $object) { return }
if([System.Management.Automation.LanguagePrimitives]::GetEnumerator($object) -or
@($object.PSObject.Properties))
{
$null = $node.Items.Add( (New-Object _treeListView.TreeListViewItem ([pscustomobject]@{Name="..."}) ) )
}
}
## A function invoked when a node is selected.
function OnSelect
{
param($Sender, $TreeViewEventArgs)
## Determine the selected node
$nodeSelected = $TreeViewEventArgs.source
## Walk through its parents, creating the virtual
## PowerShell syntax to access this property.
$nodePath = GetPathForNode $nodeSelected
## Now, invoke that PowerShell syntax to retrieve
## the value of the property.
$resultObject = Invoke-Expression $nodePath
#$outputPane.Text = $nodePath
## If we got some output, put the object's member
## information in the text box.
if($resultObject)
{
$members = Get-Member -InputObject $resultObject | Out-String
#$outputPane.Text += "`n" + $members
}
}
## A function invoked when the user is about to expand a node
function OnExpand
{
param($Sender, $TreeViewCancelEventArgs)
## Determine the selected node
$selectedNode = $TreeViewCancelEventArgs.Source
## If it has a child node that is the placeholder, clear
## the placeholder node.
if($selectedNode.items.Count -eq 1 -and
($selectedNode.Items[0].Header.Name-eq "..."))
{
$selectedNode.items.Clear()
}
else
{
return
}
## Walk through its parents, creating the virtual
## PowerShell syntax to access this property.
$nodePath = GetPathForNode $selectedNode
$global:nodepath= $nodePath
## Now, invoke that PowerShell syntax to retrieve
## the value of the property.
Invoke-Expression "`$resultObject = $nodePath"
## And populate the node with the result object.
PopulateNode $selectedNode $resultObject
}
## A function to handle keypresses on the form.
## In this case, we capture ^C to copy the path of
## the object property that we're currently viewing.
function OnKeyPress
{
param($Sender, $KeyPressEventArgs)
## [Char] 3 = Control-C
if($KeyPressEventArgs.KeyChar -eq 3)
{
$KeyPressEventArgs.Handled = $true
## Get the object path, and set it on the clipboard
$node = $Sender.SelectedNode
$nodePath = GetPathForNode $node
[System.Windows.Forms.Clipboard]::SetText($nodePath)
$form.Close()
}
}
## A function to walk through the parents of a node,
## creating virtual PowerShell syntax to access this property.
function GetPathForNode
{
param($Node)
$nodeElements = @()
## Go through all the parents, adding them so that
## $nodeElements is in order.
while($Node.Tag)
{
$nodeElements = ,$Node + $nodeElements
$Node = $Node.Parent
}
## Now go through the node elements
$nodePath = ""
foreach($Node in $nodeElements)
{
$nodeName = $Node.Tag
## If it was a node that PowerShell is able to enumerate
## (but not index), wrap it in the array cast operator.
if($nodeName.StartsWith('@'))
{
$nodeName = $nodeName.Substring(1)
$nodePath = "@(" + $nodePath + ")"
}
elseif($nodeName.StartsWith('['))
{
## If it's a child index, we don't need to
## add the dot for property access
}
elseif($nodePath)
{
## Otherwise, we're accessing a property. Add a dot.
$nodePath += "."
}
## Append the node name to the path
$nodePath += $nodeName
}
## And return the result
$nodePath
}
## Create the TreeView, which will hold our object navigation
## area.
$reader=(New-Object System.Xml.XmlNodeReader $xaml)
$Form=[Windows.Markup.XamlReader]::Load( $reader )
$tlv = $Form.FindName('Tlv')
[System.Windows.RoutedEventHandler]$Script:Select = { OnSelect @args }
[System.Windows.RoutedEventHandler]$Script:Expand = { OnExpand @args }
[System.Windows.RoutedEventHandler]$Script:KeyPress = { OnKeyPress @args }
$tlv.AddHandler([_treeListView.TreeListViewItem]::SelectedEvent, $Script:Select)
$tlv.AddHandler([_treeListView.TreeListViewItem]::ExpandedEvent, $Script:Expand)
$tlv.AddHandler([_treeListView.TreeListViewItem]::KeyUpEvent, $Script:KeyPress)
## Create the root node, which represents the object
## we are trying to show.
$root = New-Object _treeListView.TreeListViewItem ([pscustomobject]@{
Name=$InputObject.gettype().name
Value="$InputObject"
Definition=$InputObject.gettype().fullname})
#root.Header = "$InputObject : " + $InputObject.GetType()
$root.Tag = '$' + $rootVariableName
$root.ToolTip = "$InputObject"
$root.IsExpanded = $true
## And populate the initial information into the tree
## view.
PopulateNode $root $InputObject
$null = $tlv.Items.Add($root)
$null = $Form.ShowDialog()
}
|
PowerShellCorpus/PowerShellGallery/PSObjectInspector/0.0.1/temp/src/public/Out-Default-Capture.ps1
|
Out-Default-Capture.ps1
|
function Out-Default {
<#
.SYNOPSIS
Spelunking with Show-Object
.DESCRIPTION
Spelunk [spi-luhngk], verb. To explore caves, especially as a hobby.
We must first recall that PowerShell pipelines are very different from, say, Linux pipelines. Rather than consisting of text, PowerShell objects are "three-dimensional" data structures that consist of properties (descriptive attributes), methods (actions the object can undertake), and events (actions that can be undertaken on the object). Collectively, these data elements are called object members.
For instance, take Get-Service. Unless you perform filtering, you receive an object collection as output. You probably know that Get-Member shows us the object's .NET Framework type name and its properties, methods, and events. Here's partial output from my Windows 8.1 administrative workstation running Windows Management Framework 5.0 Production Preview:
PS C:\> Get-Service | Get-Member
TypeName: System.ServiceProcess.ServiceController
Name MemberType Definition
—- ———- ———-
Name AliasProperty Name = ServiceName
RequiredServices AliasProperty RequiredServices…
Disposed Event System.EventHandler…
Close Method void Close()
Continue Method void Continue()
PowerShell objects are instances of underlying .NET classes, and by default those classes are self-discovering through a process known as reflection. If you want to see everything about the previous ServiceController objects, pipe the Get-Member output to Format-List like so:
Get-Service | Get-Member | Format-List *
What I've told you means that, practically speaking, we do an awful lot of get-membering and format-listing when we need to look up specific property, method, or event values. Is there (banish the thought!) an easier-on-the-eyes graphical solution?
.EXAMPLE
First we can locate the appropriate module:
Find-Module -Name *cookbook*
Cool. So Lee's module is named PowerShellCookbook, and it is stored on the PowerShell Gallery repository. Let's install it!
Install-Module -Name PowerShellCookbook -Force
As it happens, Show-Object is only one function among many that are contained in the PowerShellCookbook module. Run the following command to see them all:
Get-Command -Module PowerShellCookbook
Using the Show-Object Function
To use Show-Object, simply pipe your desired PowerShell object into the function like so:
Get-Service -Name Spooler | Show-Object
Take a look at the following Show-Object output, and I'll walk you through it.
The bottom pane (sadly unresizable) shows your ordinary Get-Member output. The upper pane allows you to quickly parse the object properties. For instance, we can expand each RequiredServices node to learn that the Print Spooler service in Windows 8.1 depends on a Remote Procedure Call (RPC) and HTTP services.
If you're of the mind to do so, you can inspect the Show-Object source code by visiting the book's website (see Program: Interactively View and Explore Objects) or by using PowerShell directly in your console:
(Get-Command -name Show-Object).Definition | Out-File 'C:\show-object-source.txt' | Notepad 'C:\show-object-source.txt'
Going further
One of the many things I love about the Windows PowerShell community is how friendly and helpful most people are. I don't want to draw comparisons to, say, the *NIX open-source community, but…well, let's just leave that alone.
That's all there is to it!
.FUNCTIONALITY
General Command
#>
[CmdletBinding()]
param(
[Parameter(ValueFromPipeline=$true)]
[psobject]
$InputObject
)
begin {
$global:lastOutputCollection = New-Object Collections.ArrayList
try {
$outBuffer = $null
if ($PSBoundParameters.TryGetValue('OutBuffer', [ref]$outBuffer))
{
$PSBoundParameters['OutBuffer'] = 1
}
$wrappedCmd = $ExecutionContext.InvokeCommand.GetCommand('Out-Default', [System.Management.Automation.CommandTypes]::Cmdlet)
$scriptCmd = {& $wrappedCmd @PSBoundParameters }
$steppablePipeline = $scriptCmd.GetSteppablePipeline($myInvocation.CommandOrigin)
$steppablePipeline.Begin($true)
} catch {
throw
}
$invocation = Get-PSCallStack
}
process {
try {
$willProcess = $true
if ($_ -is [Management.Automation.ErrorRecord]) {
$e = $_
$i = $invocation
<#
$cs = Get-PSCallStack
$lastAction = Get-History -Count 1
if ($lastAction.CommandLine -like "*http*") {
if ($lastAction.CommandLine -like "`$*=*http*") {
$maybeUrl = $lastAction.CommandLine.Substring($lastAction.CommandLine.IndexOf("=") + 1).Trim()
$variableName = $lastAction.CommandLine.Substring(0, $lastAction.CommandLine.IndexOf("=") - 1).TrimStart('$')
if ($maybeUrl -like "http*") {
Set-Variable -Name $variableName -Value (
Get-Web -UseWebRequest $maybeUrl
) -Option AllScope
}
} else {
Start-Process -FilePath $lastAction.CommandLine
}
}
$null = $null
#>
}
$steppablePipeline.Process($_)
$null = $global:lastOutputCollection.Add($_)
$global:lastOutputItem = $_
} catch {
throw
}
}
end {
if ($global:lastOutputCollection.Count) {
$global:LastOutput = $global:lastOutputCollection
}
try {
$steppablePipeline.End()
} catch {
throw
}
}
}
|
PowerShellCorpus/PowerShellGallery/PSGit/2.0.4/PSGitPowerline.ps1
|
PSGitPowerline.ps1
|
function New-PowerLineBlock {
[CmdletBinding()]
param(
[Parameter(ValueFromPipelineByPropertyName=$true, Position=0)]
[Alias("Content","text")]
$Object,
[Parameter(ValueFromPipelineByPropertyName=$true)]
[Alias("fg","Foreground")]
$ForegroundColor,
[Parameter(ValueFromPipelineByPropertyName=$true)]
[Alias("bg","Background")]
$BackgroundColor
)
process {
$Parameters = @{} + $PSBoundParameters
$Null = $PSBoundParameters.GetEnumerator() | Where Value -eq $null | % { $Parameters.Remove($_.Key) }
Write-Debug ($Parameters | Out-String)
$Parameters
}
}
Set-Alias Get-StatusPowerLine Write-StatusPowerLine
function Write-StatusPowerLine {
[CmdletBinding()]
param (
$Status,
$Config
)
end {
if(!$Status) { $Status = Get-Status -WarningAction SilentlyContinue }
if(!$Config) { $Config = Import-Configuration }
if($Status -and $Config) {
$config.Branch | New-PowerLineBlock ("$($config.Branch.Object)" + $Status.Branch)
if($Status.AheadBy -gt 0) {
$config.AheadBy | New-PowerLineBlock ("$($config.AheadBy.Object)" + $Status.AheadBy)
}
if($Status.BehindBy -gt 0) {
$config.BehindBy | New-PowerLineBlock ("$($config.BehindBy.Object)" + $Status.BehindBy)
}
$StagedChanges = @($Status.Changes | Where { $_.Staged })
$UnStagedChanges = @($Status.Changes | Where { !$_.Staged })
if($StagedChanges.Length -gt 0 -or $UnStagedChanges.Length -gt 0) {
$config.BeforeChanges | New-PowerLineBlock
}
if(0 -ne $StagedChanges.Length) {
$config.StagedChanges | New-PowerLineBlock $($(
$count = @($StagedChanges | Where { $_.Change -eq "Added" }).Length
if(0 -lt $count -or !$config.HideZero) { "+$count" }
$count = @($StagedChanges | Where { $_.Change -eq "Modified" }).Length
if(0 -lt $count -or !$config.HideZero) { "~$count" }
$count = @($StagedChanges | Where { $_.Change -eq "Removed" }).Length
if(0 -lt $count -or !$config.HideZero) { "-$count" }
$count = @($StagedChanges | Where { $_.Change -eq "Renamed" }).Length
if(0 -lt $count -or !$config.HideZero) { "%$count" }
) -join " ")
}
if($StagedChanges.Length -gt 0 -and $UnStagedChanges.Length -gt 0) {
$config.Separator | New-PowerLineBlock
}
if(0 -ne $UnStagedChanges.Length) {
$config.UnStagedChanges | New-PowerLineBlock $($(
$count = @($UnStagedChanges | Where { $_.Change -eq "Added" }).Length
if(0 -lt $count -or !$config.HideZero) { "+$count" }
$count = @($UnStagedChanges | Where { $_.Change -eq "Modified" }).Length
if(0 -lt $count -or !$config.HideZero) { "~$count" }
$count = @($UnStagedChanges | Where { $_.Change -eq "Removed" }).Length
if(0 -lt $count -or !$config.HideZero) { "-$count" }
$count = @($UnStagedChanges | Where { $_.Change -eq "Renamed" }).Length
if(0 -lt $count -or !$config.HideZero) { "%$count" }
) -join " ")
}
}
}
}
|
PowerShellCorpus/PowerShellGallery/PSGit/2.0.4/PSGitPrompt.ps1
|
PSGitPrompt.ps1
|
function Set-PromptSettings {
[CmdletBinding()]
param(
[string]$AfterChangesText = "]:",
[ConsoleColor]$AfterChangesForeground,
[ConsoleColor]$AfterChangesBackground,
[string]$AfterNoChangesText = "]:",
[ConsoleColor]$AfterNoChangesForeground,
[ConsoleColor]$AfterNoChangesBackground,
[string]$AheadByText = '▲',
[ConsoleColor]$AheadByForeground,
[ConsoleColor]$AheadByBackground,
[string]$BehindByText = '▼',
[ConsoleColor]$BehindByForeground,
[ConsoleColor]$BehindByBackground,
[string]$BeforeText = "[",
[ConsoleColor]$BeforeForeground,
[ConsoleColor]$BeforeBackground,
[string]$BranchText = $([char]0x03BB),
[ConsoleColor]$BranchForeground,
[ConsoleColor]$BranchBackground,
[string]$BeforeChangesText = '',
[ConsoleColor]$BeforeChangesForeground,
[ConsoleColor]$BeforeChangesBackground,
[string]$SeparatorText = '|',
[ConsoleColor]$SeparatorForeground,
[ConsoleColor]$SeparatorBackground,
[ConsoleColor]$StagedChangesForeground,
[ConsoleColor]$StagedChangesBackground,
[ConsoleColor]$UnStagedChangesForeground,
[ConsoleColor]$UnStagedChangesBackground,
[Switch]$HideZero
)
$config = Import-Configuration
switch($PSBoundParameters.Keys) {
"AfterChangesText" { $config.AfterChanges.Object = $PSBoundParameters[$_] }
"AfterChangesBackground" { $config.AfterChanges.Background = $PSBoundParameters[$_] }
"AfterChangesForeground" { $config.AfterChanges.Foreground = $PSBoundParameters[$_] }
"AfterNoChangesText" { $config.AfterNoChanges.Object = $PSBoundParameters[$_] }
"AfterNoChangesBackground" { $config.AfterNoChanges.Background = $PSBoundParameters[$_] }
"AfterNoChangesForeground" { $config.AfterNoChanges.Foreground = $PSBoundParameters[$_] }
"AheadByText" { $config.AheadBy.Object = $PSBoundParameters[$_] }
"AheadByBackground" { $config.AheadBy.Background = $PSBoundParameters[$_] }
"AheadByForeground" { $config.AheadBy.Foreground = $PSBoundParameters[$_] }
"BeforeText" { $config.Before.Object = $PSBoundParameters[$_] }
"BeforeBackground" { $config.Before.Background = $PSBoundParameters[$_] }
"BeforeForeground" { $config.Before.Foreground = $PSBoundParameters[$_] }
"BeforeChangesText" { $config.BeforeChanges.Object = $PSBoundParameters[$_] }
"BeforeChangesBackground" { $config.BeforeChanges.Background = $PSBoundParameters[$_] }
"BeforeChangesForeground" { $config.BeforeChanges.Foreground = $PSBoundParameters[$_] }
"BehindByText" { $config.BehindBy.Object = $PSBoundParameters[$_] }
"BehindByBackground" { $config.BehindBy.Background = $PSBoundParameters[$_] }
"BehindByForeground" { $config.BehindBy.Foreground = $PSBoundParameters[$_] }
"BranchText" { $config.Branch.Object = $PSBoundParameters[$_] }
"BranchBackground" { $config.Branch.Background = $PSBoundParameters[$_] }
"BranchForeground" { $config.Branch.Foreground = $PSBoundParameters[$_] }
"SeparatorText" { $Config.Separator.Object = $PSBoundParameters[$_] }
"SeparatorBackground" { $Config.Separator.Background = $PSBoundParameters[$_] }
"SeparatorForeground" { $Config.Separator.Foreground = $PSBoundParameters[$_] }
"StagedChangesBackground" { $config.StagedChanges.Background = $PSBoundParameters[$_] }
"StagedChangesForeground" { $config.StagedChanges.Foreground = $PSBoundParameters[$_] }
"UnStagedChangesBackground" { $config.UnStagedChanges.Background = $PSBoundParameters[$_] }
"UnStagedChangesForeground" { $config.UnStagedChanges.Foreground = $PSBoundParameters[$_] }
"HideZero" { $Config.HideZero = [bool]$HideZero }
}
Export-Configuration $config
}
function Write-Text {
[CmdletBinding()]
param(
[Parameter(ValueFromPipelineByPropertyName=$true, Position=0)]
[Alias("Content","text")]
$Object,
[Parameter(ValueFromPipelineByPropertyName=$true)]
[Alias("fg","Foreground")]
$ForegroundColor,
[Parameter(ValueFromPipelineByPropertyName=$true)]
[Alias("bg","Background")]
$BackgroundColor
)
process {
$Parameters = @{} + $PSBoundParameters
$Null = $PSBoundParameters.GetEnumerator() | Where Value -eq $null | % { $Parameters.Remove($_.Key) }
Write-Debug ($Parameters | Out-String)
Write-Host -NoNewLine @Parameters
}
}
function Write-Status {
[CmdletBinding()]
param (
$Status,
$Config
)
end {
if(!$Status) { $Status = Get-Status -WarningAction SilentlyContinue}
if(!$Config) { $Config = Import-Configuration }
if($Status -and $Config) {
$config.Before | Write-Text
$config.Branch | Write-Text
$config.Branch | Write-Text ($Status.Branch + " ")
if($Status.AheadBy -gt 0) {
$config.AheadBy | Write-Text
$config.AheadBy | Write-Text ($Status.AheadBy + " ")
}
if($Status.BehindBy -gt 0) {
$config.BehindBy | Write-Text
$config.BehindBy | Write-Text ($Status.BehindBy + " ")
}
$StagedChanges = @($Status.Changes | Where { $_.Staged })
$UnStagedChanges = @($Status.Changes | Where { !$_.Staged })
if(($StagedChanges.Length -gt 0 -or $UnStagedChanges.Length -gt 0) -and $config.BeforeChanges.Object) {
$config.BeforeChanges | Write-Text
}
if(0 -ne $StagedChanges.Length) {
$count = @($StagedChanges | Where { $_.Change -eq "Added" }).Length
if(0 -lt $count -or !$config.HideZero) {
$config.StagedChanges | Write-Text "+$count "
}
$count = @($StagedChanges | Where { $_.Change -eq "Modified" }).Length
if(0 -lt $count -or !$config.HideZero) {
$config.StagedChanges | Write-Text "~$count "
}
$count = @($StagedChanges | Where { $_.Change -eq "Removed" }).Length
if(0 -lt $count -or !$config.HideZero) {
$config.StagedChanges | Write-Text "-$count "
}
$count = @($StagedChanges | Where { $_.Change -eq "Renamed" }).Length
if(0 -lt $count -or !$config.HideZero) {
$config.StagedChanges | Write-Text "%$count "
}
}
if(($StagedChanges.Length -gt 0 -and $UnStagedChanges.Length -gt 0) -and $config.Separator.Object) {
$config.Separator | Write-Text
}
if(0 -ne $UnStagedChanges.Length) {
$count = @($UnStagedChanges | Where { $_.Change -eq "Added" }).Length
if(0 -lt $count -or !$config.HideZero) {
$config.UnStagedChanges | Write-Text "+$count "
}
$count = @($UnStagedChanges | Where { $_.Change -eq "Modified" }).Length
if(0 -lt $count -or !$config.HideZero) {
$config.UnStagedChanges | Write-Text "~$count "
}
$count = @($UnStagedChanges | Where { $_.Change -eq "Removed" }).Length
if(0 -lt $count -or !$config.HideZero) {
$config.UnStagedChanges | Write-Text "-$count "
}
$count = @($UnStagedChanges | Where { $_.Change -eq "Renamed" }).Length
if(0 -lt $count -or !$config.HideZero) {
$config.UnStagedChanges | Write-Text "%$count "
}
}
if(($StagedChanges.Length -gt 0 -or $UnStagedChanges.Length -gt 0) -and $config.AfterChanges.Object) {
$config.AfterChanges | Write-Text
}
if(($StagedChanges.Length -eq 0 -and $UnStagedChanges.Length -eq 0) -and $config.AfterNoChanges.Object) {
$config.AfterNoChanges | Write-Text
}
} else {
$config.NoStatus | Write-Text
}
}
}
# This stuff leaks out on purpose
if(!(Test-Path Variable:Global:VcsPromptStatuses)) {
$Global:VcsPromptStatuses = @()
}
function Global:Write-VcsStatus { $Global:VcsPromptStatuses | foreach { & $_ } }
# Add scriptblock that will execute for Write-VcsStatus
$Global:VcsPromptStatuses = @($Global:VcsPromptStatuses) + @({
$WarningPreference, $WP = "SilentlyContinue", $WarningPreference
Write-Status
$WarningPreference = $WP
})
# but we don't want any duplicate hooks (if people import the module twice)
$Global:VcsPromptStatuses = @( $Global:VcsPromptStatuses | Select -Unique )
|
PowerShellCorpus/PowerShellGallery/AnsibleTower/0.1/AnsibleGroup.ps1
|
AnsibleGroup.ps1
|
function Get-AnsibleGroup
{
[CmdletBinding()]
Param (
[Parameter(ValueFromPipelineByPropertyName=$true)]
[int]$id,
[String]$Name
)
if ($id)
{
$Return = Invoke-GetAnsibleInternalJsonResult -ItemType "groups" -Id $id
}
Else
{
$Return = Invoke-GetAnsibleInternalJsonResult -ItemType "groups"
}
if (!($Return))
{
#Nothing returned from the call
Return
}
$returnobj = @()
foreach ($jsongroup in $return)
{
#Shift back to json and let newtonsoft parse it to a strongly named object instead
$jsongroupstring = $jsongroup | ConvertTo-Json
$group = $JsonParsers.ParseToGroup($jsongroupstring)
$returnobj += $group; $group = $null
}
if ($Name)
{
$returnobj = $returnobj | where {$_.Name -like $name}
}
#return the things
if ($returnobj)
{
$returnobj
}
}
|
PowerShellCorpus/PowerShellGallery/AnsibleTower/0.1/AnsibleInventory.ps1
|
AnsibleInventory.ps1
|
function Get-AnsibleInventory
{
[CmdletBinding()]
Param (
[Parameter(ValueFromPipelineByPropertyName=$true)]
[int]$id
)
if ($id)
{
$Return = Invoke-GetAnsibleInternalJsonResult -ItemType "inventory" -Id $id
}
Else
{
$Return = Invoke-GetAnsibleInternalJsonResult -ItemType "inventory"
}
if (!($Return))
{
#Nothing returned from the call
Return
}
$returnobj = @()
foreach ($jsonorg in $return)
{
#Shift back to json and let newtonsoft parse it to a strongly named object instead
$jsonorgstring = $jsonorg | ConvertTo-Json
$inventory = $JsonParsers.ParseToInventory($jsonorgstring)
$Groups = Invoke-GetAnsibleInternalJsonResult -ItemType "inventory" -Id $inventory.id -ItemSubItem "groups"
foreach ($group in $groups)
{
$GroupObj = Get-AnsibleGroup -id $group.id
if (!($thishost.groups))
{
$inventory.groups = $GroupObj
}
Else
{
$inventory.groups.add($GroupObj)
}
}
$returnobj += $inventory; $inventory = $null
}
#return the things
$returnobj
}
|
PowerShellCorpus/PowerShellGallery/AnsibleTower/0.1/testscripts.ps1
|
testscripts.ps1
|
$cred = Import-Clixml -Path "ansibletower.cred"
$cred = Get-Credential
Connect-AnsibleTower -Credential $cred -TowerUrl "https://f4t-dev.cloudapp.net" -DisableCertificateVerification
$AnsibleUrl = "https://192.168.1.33"
$AnsibleUrl = "https://f4t-dev.cloudapp.net"
$AnsibleCredential = $cred
$inventory = Get-AnsibleInventory
$group = Get-AnsibleGroup -Name "Food4Thought-Web-Dev"
if (!(get-ansiblehost -name "f4t-dev-web03.f4t-dev.local"))
{
New-AnsibleHost -Name "test3" -Inventory $inventory -Verbose -group $group -Description "Hello"
}
|
PowerShellCorpus/PowerShellGallery/AnsibleTower/0.1/AnsibleJob.ps1
|
AnsibleJob.ps1
|
function Get-AnsibleJob
{
[CmdletBinding()]
Param (
[Parameter(ValueFromPipelineByPropertyName=$true)]
[int]$id
)
if ($id)
{
$Return = Invoke-GetAnsibleInternalJsonResult -ItemType "jobs" -Id $id
}
Else
{
$Return = Invoke-GetAnsibleInternalJsonResult -ItemType "jobs"
}
if (!($Return))
{
#Nothing returned from the call
Return
}
$returnobj = @()
foreach ($jsonorg in $return)
{
#Shift back to json and let newtonsoft parse it to a strongly named object instead
$jsonorgstring = $jsonorg | ConvertTo-Json
$org = $JsonParsers.ParseToJob($jsonorgstring)
$returnobj += $org; $org = $null
}
#return the things
$returnobj
}
function Invoke-AnsibleJob
{
[CmdletBinding()]
Param (
[Parameter(ValueFromPipelineByPropertyName=$true,Mandatory=$true,ParameterSetName='ByObj')]
[AnsibleTower.JobTemplate]$JobTemplate,
[Parameter(ValueFromPipelineByPropertyName=$true,Mandatory=$true,ParameterSetName='ById')]
[int]$id
)
if ($JobTemplate)
{
$ThisJobTemplate = $JobTemplate
$id = $ThisJobTemplate.id
}
Else
{
$ThisJobTemplate = Get-AnsibleJobTemplate -id $id
}
if (!$ThisJobTemplate) {Write-Error "No Job template with id $id"; return}
Write-Verbose "Submitting job from template $id"
$result = Invoke-PostAnsibleInternalJsonResult -ItemType "job_templates" -itemId $id -ItemSubItem "jobs"
$JobId = $result.id
Write-Verbose "Starting job with jobid $jobid"
$result = Invoke-PostAnsibleInternalJsonResult -ItemType "jobs" -itemId $JobId -ItemSubItem "start"
$job = get-ansibleJob -id $JobId
$job
}
|
PowerShellCorpus/PowerShellGallery/AnsibleTower/0.1/AnsibleHost.ps1
|
AnsibleHost.ps1
|
function Get-AnsibleHost
{
[CmdletBinding()]
[OutputType([AnsibleTower.Host])]
Param (
[Parameter(ValueFromPipelineByPropertyName=$true)]
[int]$id,
[string]$Name
)
if ($id)
{
$Return = Invoke-GetAnsibleInternalJsonResult -ItemType "hosts" -Id $id
}
Else
{
$Return = Invoke-GetAnsibleInternalJsonResult -ItemType "hosts"
}
if (!($Return))
{
#Nothing returned from the call
Return
}
$returnobj = @()
foreach ($jsonhost in $return)
{
#Shift back to json and let newtonsoft parse it to a strongly named object instead
$jsonhoststring = $jsonhost | ConvertTo-Json
$thishost = $JsonParsers.ParseToHost($jsonhoststring)
Write-verbose "Found host id $($thishost.id)"
#Get the related groups
$Groups = Invoke-GetAnsibleInternalJsonResult -ItemType "hosts" -Id $thishost.id -ItemSubItem "groups"
foreach ($group in $groups)
{
$GroupObj = Get-AnsibleGroup -id $group.id
if (!($thishost.groups))
{
$thishost.groups = $GroupObj
}
Else
{
$thishost.groups.add($GroupObj)
}
}
$returnobj += $thishost; $thishost = $null
}
if ($name)
{
$returnobj = $Return | where {$_.Name -eq $name}
}
#return the things
if ($returnobj)
{
$returnobj
}
}
Function New-AnsibleHost
{
[CmdletBinding()]
Param (
[Parameter(Mandatory=$true)]
[string]$Name,
[Parameter(Mandatory=$false)]
[string]$Description,
[Parameter(Mandatory=$true)]
[AnsibleTower.Inventory]$Inventory,
[Parameter(Mandatory=$true)]
[AnsibleTower.Group]$group,
[String]$Variables = "---",
[bool]$Enabled = $true
)
$Group = Get-AnsibleGroup -id ($group.id)
if (!($group)) {
write-error "Could not find group $($group.name)"
return
}
$myobj = "" | Select name, description, inventory, variables, enabled
$myobj.Name = $Name
$myobj.Description = $Description
$myobj.Inventory = $Inventory.id
$myobj.variables = $Variables
$myobj.enabled = $Enabled
$result = Invoke-PostAnsibleInternalJsonResult -ItemType "groups" -InputObject $myobj -itemId ($group.id) -ItemSubItem "hosts"
}
|
PowerShellCorpus/PowerShellGallery/AnsibleTower/0.1/AnsibleUser.ps1
|
AnsibleUser.ps1
|
function Get-AnsibleUser
{
[CmdletBinding()]
Param (
[Parameter(ValueFromPipelineByPropertyName=$true)]
[int]$id
)
if ($id)
{
$Return = Invoke-GetAnsibleInternalJsonResult -ItemType "users" -Id $id
}
Else
{
$Return = Invoke-GetAnsibleInternalJsonResult -ItemType "users"
}
if (!($Return))
{
#Nothing returned from the call
Return
}
$returnobj = @()
foreach ($jsonorg in $return)
{
#Shift back to json and let newtonsoft parse it to a strongly named object instead
$jsonorgstring = $jsonorg | ConvertTo-Json
$org = $JsonParsers.ParseToUser($jsonorgstring)
$returnobj += $org; $org = $null
}
#return the things
$returnobj
}
Function New-AnsibleUser
{
[CmdletBinding()]
Param (
[Parameter(Mandatory=$true)]
$UserName,
[Parameter(Mandatory=$true)]
$FirstName,
[Parameter(Mandatory=$true)]
$LastName,
[Parameter(Mandatory=$true)]
$Email,
[Parameter(Mandatory=$true)]
[bool]$SuperUser,
[Parameter(Mandatory=$true)]
$Password
)
$myobj = "" | Select username, first_name, last_name, email, is_superuser, password
$myobj.username = $UserName
if ($FirstName){$myobj.first_name = $FirstName}
if ($LastName){$myobj.last_name = $LastName}
if ($Email){$myobj.email = $Email}
if ($SuperUser) {$myobj.is_superuser = $SuperUser}
if ($Password) {$myobj.password = $Password}
$result = Invoke-PostAnsibleInternalJsonResult -ItemType "users" -InputObject $myobj
if ($result)
{
$resultString = $result | ConvertTo-Json
$resultobj = $JsonParsers.ParseToUser($resultString)
$resultobj
}
}
Function Set-AnsibleUser
{
[CmdletBinding()]
Param (
[Parameter(ValueFromPipelineByPropertyName=$true,Mandatory=$true)]
$id,
#[Parameter(Mandatory=$true)]
$UserName,
#[Parameter(Mandatory=$true)]
$FirstName,
#[Parameter(Mandatory=$true)]
$LastName,
#[Parameter(Mandatory=$true)]
$Email,
#[Parameter(Mandatory=$true)]
[bool]$SuperUser,
#[Parameter(Mandatory=$true)]
$Password
)
$thisuser = Get-AnsibleUser -id $id
if ($username) {$thisuser.username = $UserName}
if ($FirstName){$thisuser.first_name = $FirstName}
if ($LastName){$thisuser.last_name = $LastName}
if ($Email){$thisuser.email = $Email}
if ($SuperUser) {$thisuser.is_superuser = $SuperUser}
if ($Password) {$thisuser.password = $Password}
$result = Invoke-PutAnsibleInternalJsonResult -ItemType "users" -InputObject $thisuser
if ($result)
{
$resultString = $result | ConvertTo-Json
$resultobj = $JsonParsers.ParseToUser($resultString)
$resultobj
}
}
|
PowerShellCorpus/PowerShellGallery/AnsibleTower/0.1/AnsibleOrganization.ps1
|
AnsibleOrganization.ps1
|
function Get-AnsibleOrganization
{
[CmdletBinding()]
Param (
[String]$Name,
[Parameter(ValueFromPipelineByPropertyName=$true)]
[int]$id
)
if ($id)
{
$Return = Invoke-GetAnsibleInternalJsonResult -ItemType "organizations" -Id $id
}
Else
{
$Return = Invoke-GetAnsibleInternalJsonResult -ItemType "organizations"
}
if (!($Return))
{
#Nothing returned from the call
Return
}
$returnobj = @()
foreach ($jsonorg in $return)
{
#Shift back to json and let newtonsoft parse it to a strongly named object instead
$jsonorgstring = $jsonorg | ConvertTo-Json
$org = $JsonParsers.ParseToOrganization($jsonorgstring)
$returnobj += $org; $org = $null
}
#return the things
$returnobj
}
Function New-AnsibleOrganization
{
[CmdletBinding()]
Param ($Name, $Description)
$myobj = "" | Select name, description
$myobj.name = $Name
if ($Description)
{
$myobj.description = $Description
}
$result = Invoke-PostAnsibleInternalJsonResult -ItemType "organizations" -InputObject $myobj
if ($result)
{
$resultString = $result | ConvertTo-Json
$resultobj = $JsonParsers.ParseToOrganization($resultString)
$resultobj
}
}
|
PowerShellCorpus/PowerShellGallery/AnsibleTower/0.1/AnsibleJobTemplate.ps1
|
AnsibleJobTemplate.ps1
|
function Get-AnsibleJobTemplate
{
<#
.SYNOPSIS
Gets one or multiple Job Templates
#>
[CmdletBinding()]
Param (
[Parameter(ValueFromPipelineByPropertyName=$true)]
[int]$id
)
if ($id)
{
$Return = Invoke-GetAnsibleInternalJsonResult -ItemType "job_templates" -Id $id
}
Else
{
$Return = Invoke-GetAnsibleInternalJsonResult -ItemType "job_templates"
}
if (!($Return))
{
#Nothing returned from the call
Return
}
$returnobj = @()
foreach ($jsonorg in $return)
{
#Shift back to json and let newtonsoft parse it to a strongly named object instead
$jsonorgstring = $jsonorg | ConvertTo-Json
$org = $JsonParsers.ParseToJobTemplate($jsonorgstring)
$returnobj += $org; $org = $null
}
#return the things
$returnobj
}
function Invoke-AnsibleJobTemplate
{
<#
.SYNOPSIS
Invokes an Ansible Job Template
.EXAMPLE
Connect-AnsibleTower -Credential (get-credential) -TowerUrl "https://mytower" -DisableCertificateVerification
$jobtemplate = get-ansibleJobTemplate -id 5
$jobtemplate | Invoke-AnsibleJobTemplate
#>
[CmdletBinding()]
Param (
[Parameter(ValueFromPipelineByPropertyName=$true,Mandatory=$true)]
[int]$id
)
$ThisJobTemplate = Get-AnsibleJobTemplate -id $id
if (!$ThisJobTemplate) {Write-Error "No Job template with id $id"; return}
$result = Invoke-PostAnsibleInternalJsonResult -ItemType "job_templates" -itemId $id -ItemSubItem "jobs"
$JobId = $result.id
$job = get-ansibleJob -id $JobId
$job
}
|
PowerShellCorpus/PowerShellGallery/AnsibleTower/0.1/AnsibleTowerClasses/AnsibleTower/packages/Newtonsoft.Json.6.0.5/tools/install.ps1
|
install.ps1
|
param($installPath, $toolsPath, $package, $project)
# open json.net splash page on package install
# don't open if json.net is installed as a dependency
try
{
$url = "http://james.newtonking.com/json"
$dte2 = Get-Interface $dte ([EnvDTE80.DTE2])
if ($dte2.ActiveWindow.Caption -eq "Package Manager Console")
{
# user is installing from VS NuGet console
# get reference to the window, the console host and the input history
# show webpage if "install-package newtonsoft.json" was last input
$consoleWindow = $(Get-VSComponentModel).GetService([NuGetConsole.IPowerConsoleWindow])
$props = $consoleWindow.GetType().GetProperties([System.Reflection.BindingFlags]::Instance -bor `
[System.Reflection.BindingFlags]::NonPublic)
$prop = $props | ? { $_.Name -eq "ActiveHostInfo" } | select -first 1
if ($prop -eq $null) { return }
$hostInfo = $prop.GetValue($consoleWindow)
if ($hostInfo -eq $null) { return }
$history = $hostInfo.WpfConsole.InputHistory.History
$lastCommand = $history | select -last 1
if ($lastCommand)
{
$lastCommand = $lastCommand.Trim().ToLower()
if ($lastCommand.StartsWith("install-package") -and $lastCommand.Contains("newtonsoft.json"))
{
$dte2.ItemOperations.Navigate($url) | Out-Null
}
}
}
else
{
# user is installing from VS NuGet dialog
# get reference to the window, then smart output console provider
# show webpage if messages in buffered console contains "installing...newtonsoft.json" in last operation
$instanceField = [NuGet.Dialog.PackageManagerWindow].GetField("CurrentInstance", [System.Reflection.BindingFlags]::Static -bor `
[System.Reflection.BindingFlags]::NonPublic)
$consoleField = [NuGet.Dialog.PackageManagerWindow].GetField("_smartOutputConsoleProvider", [System.Reflection.BindingFlags]::Instance -bor `
[System.Reflection.BindingFlags]::NonPublic)
if ($instanceField -eq $null -or $consoleField -eq $null) { return }
$instance = $instanceField.GetValue($null)
if ($instance -eq $null) { return }
$consoleProvider = $consoleField.GetValue($instance)
if ($consoleProvider -eq $null) { return }
$console = $consoleProvider.CreateOutputConsole($false)
$messagesField = $console.GetType().GetField("_messages", [System.Reflection.BindingFlags]::Instance -bor `
[System.Reflection.BindingFlags]::NonPublic)
if ($messagesField -eq $null) { return }
$messages = $messagesField.GetValue($console)
if ($messages -eq $null) { return }
$operations = $messages -split "=============================="
$lastOperation = $operations | select -last 1
if ($lastOperation)
{
$lastOperation = $lastOperation.ToLower()
$lines = $lastOperation -split "`r`n"
$installMatch = $lines | ? { $_.StartsWith("------- installing...newtonsoft.json ") } | select -first 1
if ($installMatch)
{
$dte2.ItemOperations.Navigate($url) | Out-Null
}
}
}
}
catch
{
# stop potential errors from bubbling up
# worst case the splash page won't open
}
# yolo
|
PowerShellCorpus/PowerShellGallery/SPClient/0.9/helpers/Convert-SPClientMemberAccessExpression.ps1
|
Convert-SPClientMemberAccessExpression.ps1
|
#Requires -Version 3.0
# Convert-SPClientMemberAccessExpression.ps1
#
# Copyright (c) 2017 karamem0
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
function Convert-SPClientMemberAccessExpression {
[CmdletBinding()]
param (
[Parameter(Mandatory = $true)]
[string]
$InputString,
[Parameter(Mandatory = $true)]
[System.Linq.Expressions.Expression]
$Expression
)
process {
$Expr = $Expression
$Type = $Expression.Type
if ($InputString -ne '*') {
$Splits = Split-SPClientExpressionString -InputString $InputString -Separator '.'
$Splits | ForEach-Object {
if (Test-GenericSubclassOf -InputType $Type -TestType 'Microsoft.SharePoint.Client.ClientObjectCollection`1') {
$Expr = Convert-SPClientIncludeExpression -InputString $_ -Expression $Expr
} else {
$Prop = $Type.GetProperty($_)
if ($Prop -eq $null) {
throw "Cannot convert expression because '$($Type)' has no member named '$($_)'."
}
$Expr = [System.Linq.Expressions.Expression]::Property($Expr, $Prop)
$Type = $Prop.PropertyType
}
}
}
Write-Output $Expr
}
}
|
PowerShellCorpus/PowerShellGallery/SPClient/0.9/helpers/Split-SPClientExpressionString.ps1
|
Split-SPClientExpressionString.ps1
|
#Requires -Version 3.0
# Split-SPClientExpressionString.ps1
#
# Copyright (c) 2017 karamem0
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
function Split-SPClientExpressionString {
[CmdletBinding()]
param (
[Parameter(Mandatory = $true)]
[string]
$InputString,
[Parameter(Mandatory = $true)]
[string]
$Separator
)
process {
$Buffer = ''
$Depth = 0
for ($Index = 0; $Index -lt $InputString.Length; $Index += 1) {
if ($InputString[$Index] -eq $Separator) {
if ($Depth -eq 0) {
Write-Output $Buffer.Trim()
$Buffer = ''
continue
}
}
if ($InputString[$Index] -eq '(') {
$Depth += 1
}
if ($InputString[$Index] -eq ')') {
$Depth -= 1
}
$Buffer += $InputString[$Index]
}
if ($Depth -ne 0) {
throw 'Cannot convert expression because braces is not closed.'
}
Write-Output $Buffer.Trim()
}
}
|
PowerShellCorpus/PowerShellGallery/SPClient/0.9/helpers/Invoke-SPClientLoadQuery.ps1
|
Invoke-SPClientLoadQuery.ps1
|
#Requires -Version 3.0
# Invoke-SPClientLoadQuery.ps1
#
# Copyright (c) 2017 karamem0
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
function Invoke-SPClientLoadQuery {
[CmdletBinding()]
param (
[Parameter(Mandatory = $true)]
[Microsoft.SharePoint.Client.ClientContext]
$ClientContext = $SPClient.ClientContext,
[Parameter(Mandatory = $true)]
[Microsoft.SharePoint.Client.ClientObject]
$ClientObject,
[Parameter(Mandatory = $false)]
[string]
$Retrievals
)
process {
$ObjType = $ClientObject.GetType()
$FuncType = [type]'System.Func`2' | &{ process { $_.MakeGenericType($ObjType, [object]) } }
$ExprType = [type]'System.Linq.Expressions.Expression`1' | &{ process { $_.MakeGenericType($FuncType) } }
$ListType = [type]'System.Collections.Generic.List`1' | &{ process{ $_.MakeGenericType($ExprType) } }
$LambdaExprList = New-Object $ListType
if (-not [string]::IsNullOrEmpty($Retrievals)) {
if (Test-GenericSubclassOf -InputType $ObjType -TestType 'Microsoft.SharePoint.Client.ClientObjectCollection`1') {
if (-not ($Retrievals.StartsWith('Include(') -and $Retrievals.EndsWith(')'))) {
$Retrievals = 'Include(' + $Retrievals + ')'
}
$ParamExpr = [System.Linq.Expressions.Expression]::Parameter($ObjType, $ObjType.Name)
$PropExpr = Convert-SPClientIncludeExpression -InputString $Retrievals -Expression $ParamExpr
$LambdaExpr = [System.Linq.Expressions.Expression]::Lambda($FuncType, $PropExpr, $ParamExpr)
$LambdaExprList.Add($LambdaExpr)
} else {
if ($Retrievals.StartsWith('Include(') -and $Retrievals.EndsWith(')')) {
$Retrievals = $Retrievals.Substring(8, $Retrievals.Length - 9)
}
$ParamExpr = [System.Linq.Expressions.Expression]::Parameter($ObjType, $ObjType.Name)
$Splits = Split-SPClientExpressionString -InputString $Retrievals -Separator ','
$Splits | ForEach-Object {
$PropExpr = Convert-SPClientMemberAccessExpression -InputString $_ -Expression $ParamExpr
$CastExpr = [System.Linq.Expressions.Expression]::Convert($PropExpr, [object])
$LambdaExpr = [System.Linq.Expressions.Expression]::Lambda($FuncType, $CastExpr, $ParamExpr)
$LambdaExprList.Add($LambdaExpr)
}
}
}
$LoadMethod = $ClientContext.GetType().GetMethod('Load').MakeGenericMethod($ObjType)
$LoadMethod.Invoke($ClientContext, @($ClientObject, $LambdaExprList.ToArray())) | Out-Null
$ClientContext.ExecuteQuery()
}
}
|
PowerShellCorpus/PowerShellGallery/SPClient/0.9/helpers/Test-GenericSubclassOf.ps1
|
Test-GenericSubclassOf.ps1
|
#Requires -Version 3.0
# Test-GenericSubclassOf.ps1
#
# Copyright (c) 2017 karamem0
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
function Test-GenericSubclassOf {
[CmdletBinding()]
param (
[Parameter(Mandatory = $true)]
[type]
$InputType,
[Parameter(Mandatory = $true)]
[type]
$TestType
)
process {
while ($InputType -ne $null -and $InputType -ne [object]) {
$Type = $InputType
if ($Type.IsGenericType) {
$Type = $Type.GetGenericTypeDefinition()
}
if ($Type -eq $TestType) {
Write-Output $true
return
}
$InputType = $InputType.BaseType
}
Write-Output $false
}
}
|
PowerShellCorpus/PowerShellGallery/SPClient/0.9/helpers/Convert-SPClientIncludeExpression.ps1
|
Convert-SPClientIncludeExpression.ps1
|
#Requires -Version 3.0
# Convert-SPClientIncludeExpression.ps1
#
# Copyright (c) 2017 karamem0
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
function Convert-SPClientIncludeExpression {
[CmdletBinding()]
param (
[Parameter(Mandatory = $true)]
[string]
$InputString,
[Parameter(Mandatory = $true)]
[System.Linq.Expressions.Expression]
$Expression
)
process {
if (-not $InputString.StartsWith('Include(')) {
throw "Cannot convert expression because 'InputString' parameter does not start with 'Include('."
}
if (-not $InputString.EndsWith(')')) {
throw "Cannot convert expression because 'InputString' parameter does not end with ')'."
}
$InputString = $InputString.Substring(8, $InputString.Length - 9)
$ItemType = $Expression.Type.BaseType.GenericTypeArguments[0]
$FuncType = [type]'System.Func`2' | &{ process { $_.MakeGenericType($ItemType, [object]) } }
$ExprType = [type]'System.Linq.Expressions.Expression`1' | &{ process { $_.MakeGenericType($FuncType) } }
$ListType = [type]'System.Collections.Generic.List`1' | &{ process { $_.MakeGenericType($ExprType) } }
$ParamExpr = [System.Linq.Expressions.Expression]::Parameter($ItemType, $ItemType.Name)
$LambdaExprList = New-Object $ListType
$Splits = Split-SPClientExpressionString -InputString $InputString -Separator ','
$Splits | ForEach-Object {
if ($Splits -ne '*') {
$PropExpr = Convert-SPClientMemberAccessExpression -InputString $_ -Expression $ParamExpr
$CastExpr = [System.Linq.Expressions.Expression]::Convert($PropExpr, [object])
$LambdaExpr = [System.Linq.Expressions.Expression]::Lambda($FuncType, $CastExpr, $ParamExpr)
$LambdaExprList.Add($LambdaExpr)
}
}
$ExtType = [Microsoft.SharePoint.Client.ClientObjectQueryableExtension]
$ArrayExpr = [System.Linq.Expressions.Expression]::NewArrayInit($ExprType, $LambdaExprList.ToArray())
if ($Splits -contains '*') {
$IncludeExpr = [System.Linq.Expressions.Expression]::Call( `
$ExtType.GetMethod('IncludeWithDefaultProperties').MakeGenericMethod($ItemType), `
[System.Linq.Expressions.Expression[]]@($Expression, $ArrayExpr)
)
Write-Output $IncludeExpr
} else {
$IncludeExpr = [System.Linq.Expressions.Expression]::Call( `
$ExtType.GetMethod('Include').MakeGenericMethod($ItemType), `
[System.Linq.Expressions.Expression[]]@($Expression, $ArrayExpr)
)
Write-Output $IncludeExpr
}
}
}
|
PowerShellCorpus/PowerShellGallery/SPClient/0.9/functions/SPClientFolder/ConvertTo-SPClientFolder.ps1
|
ConvertTo-SPClientFolder.ps1
|
#Requires -Version 3.0
# ConvertTo-SPClientFolder.ps1
#
# Copyright (c) 2017 karamem0
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
function ConvertTo-SPClientFolder {
<#
.SYNOPSIS
Converts list item to folder.
.PARAMETER ClientContext
Indicates the client context.
If not specified, uses default context.
.PARAMETER ListItem
Indicates the list item.
.PARAMETER Retrievals
Indicates the data retrieval expression.
#>
[CmdletBinding()]
param (
[Parameter(Mandatory = $false)]
[Microsoft.SharePoint.Client.ClientContext]
$ClientContext = $SPClient.ClientContext,
[Parameter(Mandatory = $true, ValueFromPipeline = $true, ParameterSetName = 'ListItem')]
[Microsoft.SharePoint.Client.ListItem]
$ListItem,
[Parameter(Mandatory = $false)]
[string]
$Retrievals
)
process {
if ($ClientContext -eq $null) {
throw "Cannot bind argument to parameter 'ClientContext' because it is null."
}
$ClientObject = $ListItem.Folder
Invoke-SPClientLoadQuery `
-ClientContext $ClientContext `
-ClientObject $ClientObject `
-Retrievals $Retrievals
Write-Host $($ClientObject.GetType())
if ($ClientObject.ServerObjectIsNull) {
throw 'Cannot convert list item to folder because it is not a folder.'
}
Write-Output $ClientObject
}
}
|
PowerShellCorpus/PowerShellGallery/SPClient/0.9/functions/SPClientFolder/Get-SPClientFolder.ps1
|
Get-SPClientFolder.ps1
|
#Requires -Version 3.0
# Get-SPClientFolder.ps1
#
# Copyright (c) 2017 karamem0
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
<#
.SYNOPSIS
Lists all folders or retrieve the specified folder.
.DESCRIPTION
If not specified filterable parameter, returns all sub folders in the folder.
Otherwise, returns a folder which matches the parameter.
.PARAMETER ClientContext
Indicates the client context.
If not specified, uses default context.
.PARAMETER ParentFolder
Indicates the folder which the folders are contained.
.PARAMETER ParentWeb
Indicates the web which the folders are contained.
.PARAMETER Identity
Indicates the folder GUID.
.PARAMETER Name
Indicates the folder name.
.PARAMETER Url
Indicates the folder url.
.PARAMETER Retrievals
Indicates the data retrieval expression.
#>
function Get-SPClientFolder {
[CmdletBinding(DefaultParameterSetName = 'All')]
param (
[Parameter(Mandatory = $false, ParameterSetName = 'All')]
[Parameter(Mandatory = $false, ParameterSetName = 'Identity')]
[Parameter(Mandatory = $false, ParameterSetName = 'Name')]
[Parameter(Mandatory = $false, ParameterSetName = 'Url')]
[Microsoft.SharePoint.Client.ClientContext]
$ClientContext = $SPClient.ClientContext,
[Parameter(Mandatory = $true, ValueFromPipeline = $true, ParameterSetName = 'All')]
[Parameter(Mandatory = $true, ValueFromPipeline = $true, ParameterSetName = 'Name')]
[Microsoft.SharePoint.Client.Folder]
$ParentFolder,
[Parameter(Mandatory = $true, ValueFromPipeline = $true, ParameterSetName = 'Identity')]
[Parameter(Mandatory = $true, ValueFromPipeline = $true, ParameterSetName = 'Url')]
[Microsoft.SharePoint.Client.Web]
$ParentWeb,
[Parameter(Mandatory = $true, ParameterSetName = 'Identity')]
[Alias('Id')]
[guid]
$Identity,
[Parameter(Mandatory = $true, ParameterSetName = 'Name')]
[string]
$Name,
[Parameter(Mandatory = $true, ParameterSetName = 'Url')]
[string]
$Url,
[Parameter(Mandatory = $false)]
[string]
$Retrievals
)
process {
if ($ClientContext -eq $null) {
throw "Cannot bind argument to parameter 'ClientContext' because it is null."
}
if ($PSCmdlet.ParameterSetName -eq 'All') {
$ClientObjectCollection = $ParentFolder.Folders
Invoke-SPClientLoadQuery `
-ClientContext $ClientContext `
-ClientObject $ClientObjectCollection `
-Retrievals $Retrievals
Write-Output @(, $ClientObjectCollection)
}
if ($PSCmdlet.ParameterSetName -eq 'Identity') {
$PathMethod = New-Object Microsoft.SharePoint.Client.ObjectPathMethod( `
$ClientContext, `
$ParentWeb.Path, `
'GetFolderById', `
[object[]]$Identity)
$ClientObject = New-Object Microsoft.SharePoint.Client.Folder($ClientContext, $PathMethod)
Invoke-SPClientLoadQuery `
-ClientContext $ClientContext `
-ClientObject $ClientObject `
-Retrievals $Retrievals
Write-Output $ClientObject
trap {
throw 'The specified folder could not be found.'
}
}
if ($PSCmdlet.ParameterSetName -eq 'Name') {
$ClientObjectCollection = $ParentFolder.Folders
$PathMethod = New-Object Microsoft.SharePoint.Client.ObjectPathMethod( `
$ClientContext, `
$ClientObjectCollection.Path, `
'GetByUrl', `
[object[]]$Name)
$ClientObject = New-Object Microsoft.SharePoint.Client.Folder($ClientContext, $PathMethod)
Invoke-SPClientLoadQuery `
-ClientContext $ClientContext `
-ClientObject $ClientObject `
-Retrievals $Retrievals
Write-Output $ClientObject
trap {
throw 'The specified folder could not be found.'
}
}
if ($PSCmdlet.ParameterSetName -eq 'Url') {
$PathMethod = New-Object Microsoft.SharePoint.Client.ObjectPathMethod( `
$ClientContext, `
$ParentWeb.Path, `
'GetFolderByServerRelativeUrl', `
[object[]]$Url)
$ClientObject = New-Object Microsoft.SharePoint.Client.Folder($ClientContext, $PathMethod)
Invoke-SPClientLoadQuery `
-ClientContext $ClientContext `
-ClientObject $ClientObject `
-Retrievals $Retrievals
Write-Output $ClientObject
trap {
throw 'The specified folder could not be found.'
}
}
}
}
|
PowerShellCorpus/PowerShellGallery/SPClient/0.9/functions/SPClientFolder/New-SPClientFolder.ps1
|
New-SPClientFolder.ps1
|
#Requires -Version 3.0
# New-SPClientFolder.ps1
#
# Copyright (c) 2017 karamem0
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
function New-SPClientFolder {
<#
.SYNOPSIS
Creates a new folder.
.PARAMETER ClientContext
Indicates the client context.
If not specified, uses default context.
.PARAMETER ParentFolder
Indicates the folder which a folder to be created.
.PARAMETER Name
Indicates the folder name.
.PARAMETER Retrievals
Indicates the data retrieval expression.
#>
[CmdletBinding()]
param (
[Parameter(Mandatory = $false)]
[Microsoft.SharePoint.Client.ClientContext]
$ClientContext = $SPClient.ClientContext,
[Parameter(Mandatory = $true, ValueFromPipeline = $true)]
[Microsoft.SharePoint.Client.Folder]
$ParentFolder,
[Parameter(Mandatory = $true)]
[string]
$Name,
[Parameter(Mandatory = $false)]
[string]
$Retrievals
)
process {
if ($ClientContext -eq $null) {
throw "Cannot bind argument to parameter 'ClientContext' because it is null."
}
$ClientObject = $ParentFolder.Folders.Add($Name)
Invoke-SPClientLoadQuery `
-ClientContext $ClientContext `
-ClientObject $ClientObject `
-Retrievals $Retrievals
Write-Output $ClientObject
}
}
|
PowerShellCorpus/PowerShellGallery/SPClient/0.9/functions/SPClientFolder/Remove-SPClientFolder.ps1
|
Remove-SPClientFolder.ps1
|
#Requires -Version 3.0
# Remove-SPClientFolder.ps1
#
# Copyright (c) 2017 karamem0
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
function Remove-SPClientFolder {
<#
.SYNOPSIS
Deletes a folder.
.PARAMETER ClientContext
Indicates the client context.
If not specified, uses default context.
.PARAMETER ClientObject
Indicates the folder to delete.
.PARAMETER ParentFolder
Indicates the folder which the folders are contained.
.PARAMETER ParentWeb
Indicates the web which the folders are contained.
.PARAMETER Identity
Indicates the folder GUID.
.PARAMETER Name
Indicates the folder name.
.PARAMETER Url
Indicates the folder url.
#>
[CmdletBinding(DefaultParameterSetName = 'ClientObject')]
param (
[Parameter(Mandatory = $false)]
[Microsoft.SharePoint.Client.ClientContext]
$ClientContext = $SPClient.ClientContext,
[Parameter(Mandatory = $true, ValueFromPipeline = $true, ParameterSetName = 'ClientObject')]
[Microsoft.SharePoint.Client.Folder]
$ClientObject,
[Parameter(Mandatory = $true, ValueFromPipeline = $true, ParameterSetName = 'All')]
[Parameter(Mandatory = $true, ValueFromPipeline = $true, ParameterSetName = 'Name')]
[Microsoft.SharePoint.Client.Folder]
$ParentFolder,
[Parameter(Mandatory = $true, ValueFromPipeline = $true, ParameterSetName = 'Identity')]
[Parameter(Mandatory = $true, ValueFromPipeline = $true, ParameterSetName = 'Url')]
[Microsoft.SharePoint.Client.Web]
$ParentWeb,
[Parameter(Mandatory = $true, ParameterSetName = 'Identity')]
[Alias('Id')]
[guid]
$Identity,
[Parameter(Mandatory = $true, ParameterSetName = 'Name')]
[Alias('Title')]
[string]
$Name,
[Parameter(Mandatory = $true, ParameterSetName = 'Url')]
[string]
$Url
)
process {
if ($ClientContext -eq $null) {
throw "Cannot bind argument to parameter 'ClientContext' because it is null."
}
if ($PSCmdlet.ParameterSetName -eq 'ClientObject') {
if (-not $ClientObject.IsPropertyAvailable('ServerRelativeUrl')) {
Write-Host $ClientObject.ServerRelativeUrl
Invoke-SPClientLoadQuery `
-ClientContext $ClientContext `
-ClientObject $ClientObject `
-Retrievals 'UniqueId,ServerRelativeUrl'
}
} else {
if ($PSCmdlet.ParameterSetName -eq 'Identity') {
$PathMethod = New-Object Microsoft.SharePoint.Client.ObjectPathMethod( `
$ClientContext, `
$ParentWeb.Path, `
'GetFolderById', `
[object[]]$Identity)
$ClientObject = New-Object Microsoft.SharePoint.Client.Folder($ClientContext, $PathMethod)
Invoke-SPClientLoadQuery `
-ClientContext $ClientContext `
-ClientObject $ClientObject `
-Retrievals 'UniqueId,ServerRelativeUrl'
trap {
throw 'The specified folder could not be found.'
}
}
if ($PSCmdlet.ParameterSetName -eq 'Name') {
$ClientObjectCollection = $ParentFolder.Folders
$PathMethod = New-Object Microsoft.SharePoint.Client.ObjectPathMethod( `
$ClientContext, `
$ClientObjectCollection.Path, `
'GetByUrl', `
[object[]]$Name)
$ClientObject = New-Object Microsoft.SharePoint.Client.Folder($ClientContext, $PathMethod)
Invoke-SPClientLoadQuery `
-ClientContext $ClientContext `
-ClientObject $ClientObject `
-Retrievals 'UniqueId,ServerRelativeUrl'
trap {
throw 'The specified folder could not be found.'
}
}
if ($PSCmdlet.ParameterSetName -eq 'Url') {
$PathMethod = New-Object Microsoft.SharePoint.Client.ObjectPathMethod( `
$ClientContext, `
$ParentWeb.Path, `
'GetFolderByServerRelativeUrl', `
[object[]]$Url)
$ClientObject = New-Object Microsoft.SharePoint.Client.Folder($ClientContext, $PathMethod)
Invoke-SPClientLoadQuery `
-ClientContext $ClientContext `
-ClientObject $ClientObject `
-Retrievals 'UniqueId,ServerRelativeUrl'
trap {
throw 'The specified folder could not be found.'
}
}
}
$ClientObject.DeleteObject()
$ClientContext.ExecuteQuery()
}
}
|
PowerShellCorpus/PowerShellGallery/SPClient/0.9/functions/SPClientPermission/Clear-SPClientPermission.ps1
|
Clear-SPClientPermission.ps1
|
#Requires -Version 3.0
# Clear-SPClientPermission.ps1
#
# Copyright (c) 2017 karamem0
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
function Clear-SPClientPermission {
<#
.SYNOPSIS
Clears all role assignments from the specified object.
.PARAMETER ClientContext
Indicates the client context.
If not specified, uses default context.
.PARAMETER ClientObject
Indicates the web, list or item.
#>
[CmdletBinding()]
param (
[Parameter(Mandatory = $false)]
[Microsoft.SharePoint.Client.ClientContext]
$ClientContext = $SPClient.ClientContext,
[Parameter(Mandatory = $true, ValueFromPipeline = $true)]
[Microsoft.SharePoint.Client.SecurableObject]
$ClientObject
)
process {
if ($ClientContext -eq $null) {
throw "Cannot bind argument to parameter 'ClientContext' because it is null."
}
Invoke-SPClientLoadQuery `
-ClientContext $ClientContext `
-ClientObject $ClientObject `
-Retrievals 'RoleAssignments'
while ($ClientObject.RoleAssignments.Count -gt 0) {
$ClientObject.RoleAssignments[0].DeleteObject()
}
Invoke-SPClientLoadQuery `
-ClientContext $ClientContext `
-ClientObject $ClientObject `
-Retrievals 'RoleAssignments.Include(Member,RoleDefinitionBindings)'
Write-Output $ClientObject
}
}
|
PowerShellCorpus/PowerShellGallery/SPClient/0.9/functions/SPClientPermission/Grant-SPClientPermission.ps1
|
Grant-SPClientPermission.ps1
|
#Requires -Version 3.0
# Grant-SPClientPermission.ps1
#
# Copyright (c) 2017 karamem0
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
function Grant-SPClientPermission {
<#
.SYNOPSIS
Grants permission to the specified object.
.PARAMETER ClientContext
Indicates the client context.
If not specified, uses default context.
.PARAMETER ClientObject
Indicates the web, list or item.
.PARAMETER Member
Indicates the user or group to be granted permission.
.PARAMETER Roles
Indicates the roles to be added.
#>
[CmdletBinding()]
param (
[Parameter(Mandatory = $false)]
[Microsoft.SharePoint.Client.ClientContext]
$ClientContext = $SPClient.ClientContext,
[Parameter(Mandatory = $true, ValueFromPipeline = $true)]
[Microsoft.SharePoint.Client.SecurableObject]
$ClientObject,
[Parameter(Mandatory = $true)]
[Microsoft.SharePoint.Client.Principal]
$Member,
[Parameter(Mandatory = $true)]
[object[]]
$Roles
)
process {
if ($ClientContext -eq $null) {
throw "Cannot bind argument to parameter 'ClientContext' because it is null."
}
$RoleDefinitionBindings = New-Object Microsoft.SharePoint.Client.RoleDefinitionBindingCollection($ClientContext)
$RoleDefinitionCollection = $ClientContext.Site.RootWeb.RoleDefinitions
foreach ($Role in $Roles) {
if ($Role -is 'Microsoft.SharePoint.Client.RoleType') {
$RoleDefinition = $RoleDefinitionCollection.GetByType($Role)
$RoleDefinitionBindings.Add($RoleDefinition)
} else {
$RoleDefinition = $RoleDefinitionCollection.GetByName($Role.ToString())
$RoleDefinitionBindings.Add($RoleDefinition)
}
}
$ClientObject.RoleAssignments.Add($Member, $RoleDefinitionBindings) | Out-Null
Invoke-SPClientLoadQuery `
-ClientContext $ClientContext `
-ClientObject $ClientObject `
-Retrievals 'RoleAssignments.Include(Member,RoleDefinitionBindings)'
Write-Output $ClientObject
}
}
|
PowerShellCorpus/PowerShellGallery/SPClient/0.9/functions/SPClientPermission/Revoke-SPClientPermission.ps1
|
Revoke-SPClientPermission.ps1
|
#Requires -Version 3.0
# Revoke-SPClientPermission.ps1
#
# Copyright (c) 2017 karamem0
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
function Revoke-SPClientPermission {
<#
.SYNOPSIS
Revokes permission from the specified object.
.PARAMETER ClientContext
Indicates the client context.
If not specified, uses default context.
.PARAMETER ClientObject
Indicates the web, list or item.
.PARAMETER Member
Indicates the user or group to be revoked permission.
.PARAMETER Roles
Indicates the roles to be removed.
#>
[CmdletBinding(DefaultParameterSetName = 'All')]
param (
[Parameter(Mandatory = $false, ParameterSetName = 'All')]
[Parameter(Mandatory = $false, ParameterSetName = 'Roles')]
[Microsoft.SharePoint.Client.ClientContext]
$ClientContext = $SPClient.ClientContext,
[Parameter(Mandatory = $true, ValueFromPipeline = $true)]
[Microsoft.SharePoint.Client.SecurableObject]
$ClientObject,
[Parameter(Mandatory = $true)]
[Microsoft.SharePoint.Client.Principal]
$Member,
[Parameter(Mandatory = $true, ParameterSetName = 'All')]
[switch]
$All,
[Parameter(Mandatory = $true, ParameterSetName = 'Roles')]
[object[]]
$Roles
)
process {
if ($ClientContext -eq $null) {
throw "Cannot bind argument to parameter 'ClientContext' because it is null."
}
$RoleAssignment = $ClientObject.RoleAssignments.GetByPrincipal($Member)
if ($PSCmdlet.ParameterSetName -eq 'All') {
$RoleAssignment.DeleteObject()
}
if ($PSCmdlet.ParameterSetName -eq 'Roles') {
$RoleDefinitionBindings = $RoleAssignment.RoleDefinitionBindings
$RoleDefinitionCollection = $ClientContext.Site.RootWeb.RoleDefinitions
foreach ($Role in $Roles) {
if ($Role -is 'Microsoft.SharePoint.Client.RoleType') {
$RoleDefinition = $RoleDefinitionCollection.GetByType($Role)
$RoleDefinitionBindings.Remove($RoleDefinition)
} else {
$RoleDefinition = $RoleDefinitionCollection.GetByName($Role.ToString())
$RoleDefinitionBindings.Remove($RoleDefinition)
}
}
$RoleAssignment.Update()
}
Invoke-SPClientLoadQuery `
-ClientContext $ClientContext `
-ClientObject $ClientObject `
-Retrievals 'RoleAssignments.Include(Member,RoleDefinitionBindings)'
Write-Output $ClientObject
}
}
|
PowerShellCorpus/PowerShellGallery/SPClient/0.9/functions/SPClientContentType/New-SPClientContentType.ps1
|
New-SPClientContentType.ps1
|
#Requires -Version 3.0
# New-SPClientContentType.ps1
#
# Copyright (c) 2017 karamem0
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
function New-SPClientContentType {
<#
.SYNOPSIS
Creates a new content type.
.PARAMETER ClientContext
Indicates the client context.
If not specified, uses default context.
.PARAMETER ParentWeb
Indicates the web which a content type to be created.
.PARAMETER Name
Indicates the internal name.
.PARAMETER Description
Indicates the description.
.PARAMETER Group
Indicates the group name.
.PARAMETER ParentContentType
Indicates the parent content type.
.PARAMETER Retrievals
Indicates the data retrieval expression.
#>
[CmdletBinding()]
param (
[Parameter(Mandatory = $false)]
[Microsoft.SharePoint.Client.ClientContext]
$ClientContext = $SPClient.ClientContext,
[Parameter(Mandatory = $true, ValueFromPipeline = $true)]
[Microsoft.SharePoint.Client.Web]
$ParentWeb,
[Parameter(Mandatory = $true)]
[string]
$Name,
[Parameter(Mandatory = $false)]
[string]
$Description,
[Parameter(Mandatory = $false)]
[string]
$Group,
[Parameter(Mandatory = $false)]
[Microsoft.SharePoint.Client.ContentType]
$ParentContentType,
[Parameter(Mandatory = $false)]
[string]
$Retrievals
)
process {
if ($ClientContext -eq $null) {
throw "Cannot bind argument to parameter 'ClientContext' because it is null."
}
$Creation = New-Object Microsoft.SharePoint.Client.ContentTypeCreationInformation
$Creation.Name = $Name
if ($MyInvocation.BoundParameters.ContainsKey('Group')) {
$Creation.Group = $Group
}
if ($MyInvocation.BoundParameters.ContainsKey('ParentContentType')) {
if (-not $ParentContentType.IsPropertyAvailable('Id')) {
Invoke-SPClientLoadQuery `
-ClientContext $ClientContext `
-ClientObject $ParentContentType `
-Retrievals 'Id'
}
$Creation.ParentContentType = $ParentContentType
}
$ClientObject = $ParentWeb.ContentTypes.Add($Creation)
$ClientObject.Description = $Description
$ClientObject.Update($true)
Invoke-SPClientLoadQuery `
-ClientContext $ClientContext `
-ClientObject $ClientObject `
-Retrievals $Retrievals
Write-Output $ClientObject
}
}
|
PowerShellCorpus/PowerShellGallery/SPClient/0.9/functions/SPClientContentType/Get-SPClientContentType.ps1
|
Get-SPClientContentType.ps1
|
#Requires -Version 3.0
# Get-SPClientContentType.ps1
#
# Copyright (c) 2017 karamem0
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
function Get-SPClientContentType {
<#
.SYNOPSIS
Lists all content types or retrieve the specified content type.
.DESCRIPTION
If not specified filterable parameter, returns all content types of the web.
Otherwise, returns a content type which matches the parameter.
.PARAMETER ClientContext
Indicates the client context.
.PARAMETER ParentWeb
Indicates the web which the content types are contained.
.PARAMETER Identity
Indicates the content type ID.
.PARAMETER Name
Indicates the content type name.
.PARAMETER Retrievals
Indicates the data retrieval expression.
#>
[CmdletBinding(DefaultParameterSetName = 'All')]
param (
[Parameter(Mandatory = $false, ParameterSetName = 'All')]
[Parameter(Mandatory = $false, ParameterSetName = 'Identity')]
[Parameter(Mandatory = $false, ParameterSetName = 'Name')]
[Microsoft.SharePoint.Client.ClientContext]
$ClientContext = $SPClient.ClientContext,
[Parameter(Mandatory = $true, ValueFromPipeline = $true)]
[Microsoft.SharePoint.Client.Web]
$ParentWeb,
[Parameter(Mandatory = $true, ParameterSetName = 'Identity')]
[Alias('Id')]
[string]
$Identity,
[Parameter(Mandatory = $true, ParameterSetName = 'Name')]
[string]
$Name,
[Parameter(Mandatory = $false)]
[string]
$Retrievals
)
process {
if ($ClientContext -eq $null) {
throw "Cannot bind argument to parameter 'ClientContext' because it is null."
}
$ClientObjectCollection = $ParentWeb.ContentTypes
if ($PSCmdlet.ParameterSetName -eq 'All') {
Invoke-SPClientLoadQuery `
-ClientContext $ClientContext `
-ClientObject $ClientObjectCollection `
-Retrievals $Retrievals
Write-Output @(, $ClientObjectCollection)
}
if ($PSCmdlet.ParameterSetName -eq 'Identity') {
$PathMethod = New-Object Microsoft.SharePoint.Client.ObjectPathMethod( `
$ClientContext, `
$ClientObjectCollection.Path, `
'GetById', `
[object[]]$Identity)
$ClientObject = New-Object Microsoft.SharePoint.Client.ContentType($ClientContext, $PathMethod)
Invoke-SPClientLoadQuery `
-ClientContext $ClientContext `
-ClientObject $ClientObject `
-Retrievals $Retrievals
if ($ClientObject.Id -eq $null) {
throw 'The specified content type could not be found.'
}
Write-Output $ClientObject
}
if ($PSCmdlet.ParameterSetName -eq 'Name') {
Invoke-SPClientLoadQuery `
-ClientContext $ClientContext `
-ClientObject $ClientObjectCollection `
-Retrievals 'Include(Name)'
$ClientObject = $ClientObjectCollection | Where-Object { $_.Name -eq $Name }
if ($ClientObject -eq $null) {
throw 'The specified content type could not be found.'
}
Invoke-SPClientLoadQuery `
-ClientContext $ClientContext `
-ClientObject $ClientObject `
-Retrievals $Retrievals
Write-Output $ClientObject
}
}
}
|
PowerShellCorpus/PowerShellGallery/SPClient/0.9/functions/SPClientContentType/Remove-SPClientContentType.ps1
|
Remove-SPClientContentType.ps1
|
#Requires -Version 3.0
# Remove-SPClientContentType.ps1
#
# Copyright (c) 2017 karamem0
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
function Remove-SPClientContentType {
<#
.SYNOPSIS
Deletes a content type.
.PARAMETER ClientContext
Indicates the client context.
If not specified, uses default context.
.PARAMETER ClientObject
Indicates the content type to delete.
.PARAMETER ParentWeb
Indicates the web which the content type is contained.
.PARAMETER Identity
Indicates the content type ID.
.PARAMETER Name
Indicates the content type name.
#>
[CmdletBinding(DefaultParameterSetName = 'ClientObject')]
param (
[Parameter(Mandatory = $false)]
[Microsoft.SharePoint.Client.ClientContext]
$ClientContext = $SPClient.ClientContext,
[Parameter(Mandatory = $true, ValueFromPipeline = $true, ParameterSetName = 'ClientObject')]
[Microsoft.SharePoint.Client.ContentType]
$ClientObject,
[Parameter(Mandatory = $true, ValueFromPipeline = $true, ParameterSetName = 'Identity')]
[Parameter(Mandatory = $true, ValueFromPipeline = $true, ParameterSetName = 'Name')]
[Microsoft.SharePoint.Client.Web]
$ParentWeb,
[Parameter(Mandatory = $true, ParameterSetName = 'Identity')]
[Alias('Id')]
[string]
$Identity,
[Parameter(Mandatory = $true, ParameterSetName = 'Name')]
[string]
$Name
)
process {
if ($ClientContext -eq $null) {
throw "Cannot bind argument to parameter 'ClientContext' because it is null."
}
if ($PSCmdlet.ParameterSetName -eq 'ClientObject') {
if (-not $ClientObject.IsPropertyAvailable('Id')) {
Invoke-SPClientLoadQuery `
-ClientContext $ClientContext `
-ClientObject $ClientObject `
-Retrievals 'Id'
}
} else {
$ClientObjectCollection = $ParentWeb.ContentTypes
if ($PSCmdlet.ParameterSetName -eq 'Identity') {
$PathMethod = New-Object Microsoft.SharePoint.Client.ObjectPathMethod( `
$ClientContext, `
$ClientObjectCollection.Path, `
'GetById', `
[object[]]$Identity)
$ClientObject = New-Object Microsoft.SharePoint.Client.ContentType($ClientContext, $PathMethod)
Invoke-SPClientLoadQuery `
-ClientContext $ClientContext `
-ClientObject $ClientObject `
-Retrievals 'Id'
if ($ClientObject.Id -eq $null) {
throw 'The specified content type could not be found.'
}
}
if ($PSCmdlet.ParameterSetName -eq 'Name') {
Invoke-SPClientLoadQuery `
-ClientContext $ClientContext `
-ClientObject $ClientObjectCollection `
-Retrievals 'Include(Id,Name)'
$ClientObject = $ClientObjectCollection | Where-Object { $_.Name -eq $Name }
if ($ClientObject -eq $null) {
throw 'The specified content type could not be found.'
}
}
}
$ClientObject.DeleteObject()
$ClientContext.ExecuteQuery()
}
}
|
PowerShellCorpus/PowerShellGallery/SPClient/0.9/functions/SPClientListItemAttachment/New-SPClientListItemAttachment.ps1
|
New-SPClientListItemAttachment.ps1
|
#Requires -Version 3.0
# New-SPClientListItemAttachment.ps1
#
# Copyright (c) 2017 karamem0
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
function New-SPClientListItemAttachment {
<#
.SYNOPSIS
Creates a new attachment.
.PARAMETER ClientContext
Indicates the client context.
If not specified, uses default context.
.PARAMETER ParentListItem
Indicates the list item which a attachment to be created.
.PARAMETER ContentPath
Indicates the content file path.
.PARAMETER ContentStream
Indicates the content stream.
.PARAMETER FileName
Indicates the file name.
.PARAMETER Retrievals
Indicates the data retrieval expression.
#>
[CmdletBinding(DefaultParameterSetName = 'ContentStream')]
param (
[Parameter(Mandatory = $false)]
[Microsoft.SharePoint.Client.ClientContext]
$ClientContext = $SPClient.ClientContext,
[Parameter(Mandatory = $true, ValueFromPipeline = $true)]
[Microsoft.SharePoint.Client.ListItem]
$ParentListItem,
[Parameter(Mandatory = $true, ParameterSetName = 'ContentStream')]
[System.IO.Stream]
$ContentStream,
[Parameter(Mandatory = $true, ParameterSetName = 'ContentPath')]
[string]
$ContentPath,
[Parameter(Mandatory = $true, ParameterSetName = 'ContentStream')]
[Parameter(Mandatory = $false, ParameterSetName = 'ContentPath')]
[string]
$Name,
[Parameter(Mandatory = $false)]
[string]
$Retrievals
)
process {
if ($ClientContext -eq $null) {
throw "Cannot bind argument to parameter 'ClientContext' because it is null."
}
$Creation = New-Object Microsoft.SharePoint.Client.AttachmentCreationInformation
if ($PSCmdlet.ParameterSetName -eq 'ContentStream') {
$Creation.ContentStream = $ContentStream
$Creation.FileName = $Name
}
if ($PSCmdlet.ParameterSetName -eq 'ContentPath') {
if (-not (Test-Path -Path $ContentPath)) {
throw "Cannot find file '$($ContentPath)'."
}
$Creation.ContentStream = [System.IO.File]::OpenRead($ContentPath)
if ($MyInvocation.BoundParameters.ContainsKey('Name')) {
$Creation.FileName = $Name
} else {
$Creation.FileName = [System.IO.Path]::GetFileName($ContentPath)
}
}
$ClientObject = $ParentListItem.AttachmentFiles.Add($Creation)
Invoke-SPClientLoadQuery `
-ClientContext $ClientContext `
-ClientObject $ClientObject `
-Retrievals $Retrievals
Write-Output $ClientObject
}
}
|
PowerShellCorpus/PowerShellGallery/SPClient/0.9/functions/SPClientListItemAttachment/Remove-SPClientListItemAttachment.ps1
|
Remove-SPClientListItemAttachment.ps1
|
#Requires -Version 3.0
# Remove-SPClientListItemAttachment.ps1
#
# Copyright (c) 2017 karamem0
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
function Remove-SPClientListItemAttachment {
<#
.SYNOPSIS
Deletes a attachment.
.PARAMETER ClientContext
Indicates the client context.
If not specified, uses default context.
.PARAMETER ClientObject
Indicates the attachment to delete.
.PARAMETER ParentListItem
Indicates the list item which the attachment is contained.
.PARAMETER FileName
Indicates the attachment file name.
#>
[CmdletBinding(DefaultParameterSetName = 'ClientObject')]
param (
[Parameter(Mandatory = $false)]
[Microsoft.SharePoint.Client.ClientContext]
$ClientContext = $SPClient.ClientContext,
[Parameter(Mandatory = $true, ValueFromPipeline = $true, ParameterSetName = 'ClientObject')]
[Microsoft.SharePoint.Client.Attachment]
$ClientObject,
[Parameter(Mandatory = $true, ValueFromPipeline = $true, ParameterSetName = 'FileName')]
[Microsoft.SharePoint.Client.ListItem]
$ParentListItem,
[Parameter(Mandatory = $true, ParameterSetName = 'FileName')]
[string]
$FileName
)
process {
if ($ClientContext -eq $null) {
throw "Cannot bind argument to parameter 'ClientContext' because it is null."
}
if ($PSCmdlet.ParameterSetName -eq 'ClientObject') {
if (-not $ClientObject.IsPropertyAvailable('FileName')) {
Invoke-SPClientLoadQuery `
-ClientContext $ClientContext `
-ClientObject $ClientObject `
-Retrievals 'FileName'
}
} else {
$ClientObjectCollection = $ParentListItem.AttachmentFiles
if ($PSCmdlet.ParameterSetName -eq 'FileName') {
$PathMethod = New-Object Microsoft.SharePoint.Client.ObjectPathMethod( `
$ClientContext, `
$ClientObjectCollection.Path, `
'GetByFileName', `
[object[]]$FileName)
$ClientObject = New-Object Microsoft.SharePoint.Client.Attachment($ClientContext, $PathMethod)
Invoke-SPClientLoadQuery `
-ClientContext $ClientContext `
-ClientObject $ClientObject `
-Retrievals 'FileName'
trap {
throw 'The specified attachment could not be found.'
}
}
}
$ClientObject.DeleteObject()
$ClientContext.ExecuteQuery()
}
}
|
PowerShellCorpus/PowerShellGallery/SPClient/0.9/functions/SPClientListItemAttachment/Get-SPClientListItemAttachment.ps1
|
Get-SPClientListItemAttachment.ps1
|
#Requires -Version 3.0
# Get-SPClientListItemAttachment.ps1
#
# Copyright (c) 2017 karamem0
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
function Get-SPClientListItemAttachment {
<#
.SYNOPSIS
Lists all attachments or retrieve the specified attachment.
.DESCRIPTION
If not specified filterable parameter, returns all attachments of the list
item. Otherwise, returns a attachment which matches the parameter.
.PARAMETER ClientContext
Indicates the client context.
If not specified, uses default context.
.PARAMETER ParentListItem
Indicates the list item which the attachments are contained.
.PARAMETER FileName
Indicates the attachment file name.
.PARAMETER Retrievals
Indicates the data retrieval expression.
#>
[CmdletBinding(DefaultParameterSetName = 'All')]
param (
[Parameter(Mandatory = $false, ParameterSetName = 'All')]
[Parameter(Mandatory = $false, ParameterSetName = 'Name')]
[Microsoft.SharePoint.Client.ClientContext]
$ClientContext = $SPClient.ClientContext,
[Parameter(Mandatory = $true, ValueFromPipeline = $true)]
[Microsoft.SharePoint.Client.ListItem]
$ParentListItem,
[Parameter(Mandatory = $true, ParameterSetName = 'Name')]
[string]
$Name,
[Parameter(Mandatory = $false)]
[string]
$Retrievals
)
process {
if ($ClientContext -eq $null) {
throw "Cannot bind argument to parameter 'ClientContext' because it is null."
}
$ClientObjectCollection = $ParentListItem.AttachmentFiles
if ($PSCmdlet.ParameterSetName -eq 'All') {
Invoke-SPClientLoadQuery `
-ClientContext $ClientContext `
-ClientObject $ClientObjectCollection `
-Retrievals $Retrievals
Write-Output @(, $ClientObjectCollection)
}
if ($PSCmdlet.ParameterSetName -eq 'Name') {
$PathMethod = New-Object Microsoft.SharePoint.Client.ObjectPathMethod( `
$ClientContext, `
$ClientObjectCollection.Path, `
'GetByFileName', `
[object[]]$Name)
$ClientObject = New-Object Microsoft.SharePoint.Client.Attachment($ClientContext, $PathMethod)
Invoke-SPClientLoadQuery `
-ClientContext $ClientContext `
-ClientObject $ClientObject `
-Retrievals $Retrievals
Write-Output $ClientObject
trap {
throw 'The specified attachment could not be found.'
}
}
}
}
|
PowerShellCorpus/PowerShellGallery/SPClient/0.9/functions/SPClientContext/Disconnect-SPClientContext.ps1
|
Disconnect-SPClientContext.ps1
|
#Requires -Version 3.0
# Disconnect-SPClientContext.ps1
#
# Copyright (c) 2017 karamem0
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
function Disconnect-SPClientContext {
<#
.SYNOPSIS
Disconnects from SharePoint site.
.PARAMETER ClientContext
Indicates the client context.
#>
[CmdletBinding()]
param (
[Parameter(Mandatory = $false)]
[Microsoft.SharePoint.Client.ClientContext]
$ClientContext = $SPClient.ClientContext
)
process {
if ($ClientContext -eq $null) {
throw "Cannot bind argument to parameter 'ClientContext' because it is null."
}
$ClientContext.Dispose()
$ClientContext = $null
}
}
|
PowerShellCorpus/PowerShellGallery/SPClient/0.9/functions/SPClientContext/Connect-SPClientContext.ps1
|
Connect-SPClientContext.ps1
|
#Requires -Version 3.0
# Connect-SPClientContext.ps1
#
# Copyright (c) 2017 karamem0
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
function Connect-SPClientContext {
<#
.SYNOPSIS
Connects to SharePoint site.
.PARAMETER Network
If specified, connects to SharePoint Server (On-premise).
.PARAMETER Online
If specified, connects to SharePoint Online.
.PARAMETER Url
Indicates the site url.
.PARAMETER UserName
Indicates the user name.
.PARAMETER Password
Indicates the password.
.PARAMETER Domain
Indicates the domain.
.PARAMETER Credential
Indicates the credential.
.PARAMETER PassThru
If specified, returns a client context.
#>
[CmdletBinding()]
param (
[Parameter(Mandatory = $true, ParameterSetName = 'NetworkPassword')]
[Parameter(Mandatory = $true, ParameterSetName = 'NetworkCredential')]
[switch]
$Network,
[Parameter(Mandatory = $true, ParameterSetName = 'OnlinePassword')]
[Parameter(Mandatory = $true, ParameterSetName = 'OnlineCredential')]
[switch]
$Online,
[Parameter(Mandatory = $true)]
[string]
$Url,
[Parameter(Mandatory = $true, ParameterSetName = 'NetworkPassword')]
[Parameter(Mandatory = $true, ParameterSetName = 'OnlinePassword')]
[string]
$UserName,
[Parameter(Mandatory = $true, ParameterSetName = 'NetworkPassword')]
[Parameter(Mandatory = $true, ParameterSetName = 'OnlinePassword')]
[securestring]
$Password,
[Parameter(Mandatory = $true, ParameterSetName = 'NetworkPassword')]
[string]
$Domain,
[Parameter(Mandatory = $true, ValueFromPipeline = $true, ParameterSetName = 'NetworkCredential')]
[Parameter(Mandatory = $true, ValueFromPipeline = $true, ParameterSetName = 'OnlineCredential')]
[PSCredential]
$Credential,
[Parameter(Mandatory = $false)]
[switch]
$PassThru
)
process {
$ClientContext = New-Object Microsoft.SharePoint.Client.ClientContext($Url)
if ($PSCmdlet.ParameterSetName -eq 'NetworkPassword') {
$ClientContext.Credentials = New-Object System.Net.NetworkCredential($UserName, $Password, $Domain)
}
if ($PSCmdlet.ParameterSetName -eq 'NetworkCredential') {
$ClientContext.Credentials = $Credential.GetNetworkCredential()
}
if ($PSCmdlet.ParameterSetName -eq 'OnlinePassword') {
$ClientContext.Credentials =
New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($UserName, $Password)
}
if ($PSCmdlet.ParameterSetName -eq 'OnlineCredential') {
$UserName = $Credential.UserName
$Password = $Credential.Password
$ClientContext.Credentials =
New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($UserName, $Password)
}
$SPClient.ClientContext = $ClientContext
if ($PassThru) {
Write-Output $ClientContext
}
}
}
|
PowerShellCorpus/PowerShellGallery/SPClient/0.9/functions/SPClientFile/Remove-SPClientFile.ps1
|
Remove-SPClientFile.ps1
|
#Requires -Version 3.0
# Remove-SPClientFile.ps1
#
# Copyright (c) 2017 karamem0
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
function Remove-SPClientFile {
<#
.SYNOPSIS
Deletes a file.
.PARAMETER ClientContext
Indicates the client context.
If not specified, uses default context.
.PARAMETER ClientObject
Indicates the file to delete.
.PARAMETER ParentFolder
Indicates the folder which the files are contained.
.PARAMETER ParentWeb
Indicates the web which the files are contained.
.PARAMETER Identity
Indicates the file GUID.
.PARAMETER Name
Indicates the file name including the extension.
.PARAMETER Url
Indicates the file url.
#>
[CmdletBinding(DefaultParameterSetName = 'ClientObject')]
param (
[Parameter(Mandatory = $false)]
[Microsoft.SharePoint.Client.ClientContext]
$ClientContext = $SPClient.ClientContext,
[Parameter(Mandatory = $true, ValueFromPipeline = $true, ParameterSetName = 'ClientObject')]
[Microsoft.SharePoint.Client.File]
$ClientObject,
[Parameter(Mandatory = $true, ValueFromPipeline = $true, ParameterSetName = 'All')]
[Parameter(Mandatory = $true, ValueFromPipeline = $true, ParameterSetName = 'Name')]
[Microsoft.SharePoint.Client.Folder]
$ParentFolder,
[Parameter(Mandatory = $true, ValueFromPipeline = $true, ParameterSetName = 'Identity')]
[Parameter(Mandatory = $true, ValueFromPipeline = $true, ParameterSetName = 'Url')]
[Microsoft.SharePoint.Client.Web]
$ParentWeb,
[Parameter(Mandatory = $true, ParameterSetName = 'Identity')]
[Alias('Id')]
[guid]
$Identity,
[Parameter(Mandatory = $true, ParameterSetName = 'Name')]
[Alias('Title')]
[string]
$Name,
[Parameter(Mandatory = $true, ParameterSetName = 'Url')]
[string]
$Url
)
process {
if ($ClientContext -eq $null) {
throw "Cannot bind argument to parameter 'ClientContext' because it is null."
}
if ($PSCmdlet.ParameterSetName -eq 'ClientObject') {
if (-not $ClientObject.IsPropertyAvailable('ServerRelativeUrl')) {
Invoke-SPClientLoadQuery `
-ClientContext $ClientContext `
-ClientObject $ClientObject `
-Retrievals 'UniqueId,ServerRelativeUrl'
}
} else {
if ($PSCmdlet.ParameterSetName -eq 'Identity') {
$PathMethod = New-Object Microsoft.SharePoint.Client.ObjectPathMethod( `
$ClientContext, `
$ParentWeb.Path, `
'GetFileById', `
[object[]]$Identity)
$ClientObject = New-Object Microsoft.SharePoint.Client.File($ClientContext, $PathMethod)
Invoke-SPClientLoadQuery `
-ClientContext $ClientContext `
-ClientObject $ClientObject `
-Retrievals 'UniqueId,ServerRelativeUrl'
trap {
throw 'The specified file could not be found.'
}
}
if ($PSCmdlet.ParameterSetName -eq 'Name') {
$ClientObjectCollection = $ParentFolder.Files
$PathMethod = New-Object Microsoft.SharePoint.Client.ObjectPathMethod( `
$ClientContext, `
$ClientObjectCollection.Path, `
'GetByUrl', `
[object[]]$Name)
$ClientObject = New-Object Microsoft.SharePoint.Client.File($ClientContext, $PathMethod)
Invoke-SPClientLoadQuery `
-ClientContext $ClientContext `
-ClientObject $ClientObject `
-Retrievals 'UniqueId,ServerRelativeUrl'
trap {
throw 'The specified file could not be found.'
}
}
if ($PSCmdlet.ParameterSetName -eq 'Url') {
$PathMethod = New-Object Microsoft.SharePoint.Client.ObjectPathMethod( `
$ClientContext, `
$ParentWeb.Path, `
'GetFileByServerRelativeUrl', `
[object[]]$Url)
$ClientObject = New-Object Microsoft.SharePoint.Client.File($ClientContext, $PathMethod)
Invoke-SPClientLoadQuery `
-ClientContext $ClientContext `
-ClientObject $ClientObject `
-Retrievals 'UniqueId,ServerRelativeUrl'
trap {
throw 'The specified file could not be found.'
}
}
}
$ClientObject.DeleteObject()
$ClientContext.ExecuteQuery()
}
}
|
PowerShellCorpus/PowerShellGallery/SPClient/0.9/functions/SPClientFile/New-SPClientFile.ps1
|
New-SPClientFile.ps1
|
#Requires -Version 3.0
# New-SPClientFile.ps1
#
# Copyright (c) 2017 karamem0
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
function New-SPClientFile {
<#
.SYNOPSIS
Creates a new file.
.PARAMETER ClientContext
Indicates the client context.
If not specified, uses default context.
.PARAMETER ParentFolder
Indicates the folder which a file to be created.
.PARAMETER ContentPath
Indicates the content file path.
.PARAMETER ContentStream
Indicates the content stream.
.PARAMETER Name
Indicates the file name.
.PARAMETER Retrievals
Indicates the data retrieval expression.
#>
[CmdletBinding(DefaultParameterSetName = 'ContentStream')]
param (
[Parameter(Mandatory = $false)]
[Microsoft.SharePoint.Client.ClientContext]
$ClientContext = $SPClient.ClientContext,
[Parameter(Mandatory = $true, ValueFromPipeline = $true)]
[Microsoft.SharePoint.Client.Folder]
$ParentFolder,
[Parameter(Mandatory = $true, ParameterSetName = 'ContentStream')]
[System.IO.Stream]
$ContentStream,
[Parameter(Mandatory = $true, ParameterSetName = 'ContentPath')]
[string]
$ContentPath,
[Parameter(Mandatory = $true, ParameterSetName = 'ContentStream')]
[Parameter(Mandatory = $false, ParameterSetName = 'ContentPath')]
[string]
$Name,
[Parameter(Mandatory = $false)]
[string]
$Retrievals
)
process {
if ($ClientContext -eq $null) {
throw "Cannot bind argument to parameter 'ClientContext' because it is null."
}
$Creation = New-Object Microsoft.SharePoint.Client.FileCreationInformation
if ($PSCmdlet.ParameterSetName -eq 'ContentStream') {
$Creation.ContentStream = $ContentStream
$Creation.Url = $Name
}
if ($PSCmdlet.ParameterSetName -eq 'ContentPath') {
if (-not (Test-Path -Path $ContentPath)) {
throw "Cannot find file '$($ContentPath)'."
}
$Creation.ContentStream = [System.IO.File]::OpenRead($ContentPath)
if ($MyInvocation.BoundParameters.ContainsKey('Name')) {
$Creation.Url = $Name
} else {
$Creation.Url = [System.IO.Path]::GetFileName($ContentPath)
}
}
$ClientObject = $ParentFolder.Files.Add($Creation)
Invoke-SPClientLoadQuery `
-ClientContext $ClientContext `
-ClientObject $ClientObject `
-Retrievals $Retrievals
Write-Output $ClientObject
}
}
|
PowerShellCorpus/PowerShellGallery/SPClient/0.9/functions/SPClientFile/ConvertTo-SPClientFile.ps1
|
ConvertTo-SPClientFile.ps1
|
#Requires -Version 3.0
# ConvertTo-SPClientFile.ps1
#
# Copyright (c) 2017 karamem0
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
function ConvertTo-SPClientFile {
<#
.SYNOPSIS
Converts list item to file.
.PARAMETER ClientContext
Indicates the client context.
If not specified, uses default context.
.PARAMETER ListItem
Indicates the list item.
.PARAMETER Retrievals
Indicates the data retrieval expression.
#>
[CmdletBinding()]
param (
[Parameter(Mandatory = $false)]
[Microsoft.SharePoint.Client.ClientContext]
$ClientContext = $SPClient.ClientContext,
[Parameter(Mandatory = $true, ValueFromPipeline = $true, ParameterSetName = 'ListItem')]
[Microsoft.SharePoint.Client.ListItem]
$ListItem,
[Parameter(Mandatory = $false)]
[string]
$Retrievals
)
process {
if ($ClientContext -eq $null) {
throw "Cannot bind argument to parameter 'ClientContext' because it is null."
}
$ClientObject = $ListItem.File
Invoke-SPClientLoadQuery `
-ClientContext $ClientContext `
-ClientObject $ClientObject `
-Retrievals $Retrievals
if ($ClientObject.ServerObjectIsNull) {
throw 'Cannot convert list item to file because it is a folder or it is located in a document library.'
}
Write-Output $ClientObject
}
}
|
PowerShellCorpus/PowerShellGallery/SPClient/0.9/functions/SPClientFile/Get-SPClientFile.ps1
|
Get-SPClientFile.ps1
|
#Requires -Version 3.0
# Get-SPClientFile.ps1
#
# Copyright (c) 2017 karamem0
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
<#
.SYNOPSIS
Lists all files or retrieve the specified file.
.DESCRIPTION
If not specified filterable parameter, returns all files in the folder.
Otherwise, returns a file which matches the parameter.
.PARAMETER ClientContext
Indicates the client context.
If not specified, uses default context.
.PARAMETER ParentFolder
Indicates the folder which the files are contained.
.PARAMETER ParentWeb
Indicates the web which the files are contained.
.PARAMETER Identity
Indicates the file GUID.
.PARAMETER Name
Indicates the file name including the extension.
.PARAMETER Url
Indicates the file url.
.PARAMETER Retrievals
Indicates the data retrieval expression.
#>
function Get-SPClientFile {
[CmdletBinding(DefaultParameterSetName = 'All')]
param (
[Parameter(Mandatory = $false, ParameterSetName = 'All')]
[Parameter(Mandatory = $false, ParameterSetName = 'Identity')]
[Parameter(Mandatory = $false, ParameterSetName = 'Name')]
[Parameter(Mandatory = $false, ParameterSetName = 'Url')]
[Microsoft.SharePoint.Client.ClientContext]
$ClientContext = $SPClient.ClientContext,
[Parameter(Mandatory = $true, ValueFromPipeline = $true, ParameterSetName = 'All')]
[Parameter(Mandatory = $true, ValueFromPipeline = $true, ParameterSetName = 'Name')]
[Microsoft.SharePoint.Client.Folder]
$ParentFolder,
[Parameter(Mandatory = $true, ValueFromPipeline = $true, ParameterSetName = 'Identity')]
[Parameter(Mandatory = $true, ValueFromPipeline = $true, ParameterSetName = 'Url')]
[Microsoft.SharePoint.Client.Web]
$ParentWeb,
[Parameter(Mandatory = $true, ParameterSetName = 'Identity')]
[Alias('Id')]
[guid]
$Identity,
[Parameter(Mandatory = $true, ParameterSetName = 'Name')]
[string]
$Name,
[Parameter(Mandatory = $true, ParameterSetName = 'Url')]
[string]
$Url,
[Parameter(Mandatory = $false)]
[string]
$Retrievals
)
process {
if ($ClientContext -eq $null) {
throw "Cannot bind argument to parameter 'ClientContext' because it is null."
}
if ($PSCmdlet.ParameterSetName -eq 'All') {
$ClientObjectCollection = $ParentFolder.Files
Invoke-SPClientLoadQuery `
-ClientContext $ClientContext `
-ClientObject $ClientObjectCollection `
-Retrievals $Retrievals
Write-Output @(, $ClientObjectCollection)
}
if ($PSCmdlet.ParameterSetName -eq 'Identity') {
$PathMethod = New-Object Microsoft.SharePoint.Client.ObjectPathMethod( `
$ClientContext, `
$ParentWeb.Path, `
'GetFileById', `
[object[]]$Identity)
$ClientObject = New-Object Microsoft.SharePoint.Client.File($ClientContext, $PathMethod)
Invoke-SPClientLoadQuery `
-ClientContext $ClientContext `
-ClientObject $ClientObject `
-Retrievals $Retrievals
Write-Output $ClientObject
trap {
throw 'The specified file could not be found.'
}
}
if ($PSCmdlet.ParameterSetName -eq 'Name') {
$ClientObjectCollection = $ParentFolder.Files
$PathMethod = New-Object Microsoft.SharePoint.Client.ObjectPathMethod( `
$ClientContext, `
$ClientObjectCollection.Path, `
'GetByUrl', `
[object[]]$Name)
$ClientObject = New-Object Microsoft.SharePoint.Client.File($ClientContext, $PathMethod)
Invoke-SPClientLoadQuery `
-ClientContext $ClientContext `
-ClientObject $ClientObject `
-Retrievals $Retrievals
Write-Output $ClientObject
trap {
throw 'The specified file could not be found.'
}
}
if ($PSCmdlet.ParameterSetName -eq 'Url') {
$PathMethod = New-Object Microsoft.SharePoint.Client.ObjectPathMethod( `
$ClientContext, `
$ParentWeb.Path, `
'GetFileByServerRelativeUrl', `
[object[]]$Url)
$ClientObject = New-Object Microsoft.SharePoint.Client.File($ClientContext, $PathMethod)
Invoke-SPClientLoadQuery `
-ClientContext $ClientContext `
-ClientObject $ClientObject `
-Retrievals $Retrievals
Write-Output $ClientObject
trap {
throw 'The specified file could not be found.'
}
}
}
}
|
PowerShellCorpus/PowerShellGallery/SPClient/0.9/functions/SPClientView/Get-SPClientView.ps1
|
Get-SPClientView.ps1
|
#Requires -Version 3.0
# Get-SPClientView.ps1
#
# Copyright (c) 2017 karamem0
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
function Get-SPClientView {
<#
.SYNOPSIS
Lists all views or retrieve the specified view.
.DESCRIPTION
If not specified filterable parameter, returns all views of the list.
Otherwise, returns a view which matches the parameter.
.PARAMETER ClientContext
Indicates the client context.
If not specified, uses default context.
.PARAMETER ParentList
Indicates the list which the views are contained.
.PARAMETER Identity
Indicates the view GUID.
.PARAMETER Url
Indicates the view url.
.PARAMETER Title
Indicates the view title.
.PARAMETER Default
If specified, returns the default view.
.PARAMETER Retrievals
Indicates the data retrieval expression.
#>
[CmdletBinding(DefaultParameterSetName = 'All')]
param (
[Parameter(Mandatory = $false, ParameterSetName = 'All')]
[Parameter(Mandatory = $false, ParameterSetName = 'Identity')]
[Parameter(Mandatory = $false, ParameterSetName = 'Url')]
[Parameter(Mandatory = $false, ParameterSetName = 'Title')]
[Parameter(Mandatory = $false, ParameterSetName = 'Default')]
[Microsoft.SharePoint.Client.ClientContext]
$ClientContext = $SPClient.ClientContext,
[Parameter(Mandatory = $true, ValueFromPipeline = $true)]
[Microsoft.SharePoint.Client.List]
$ParentList,
[Parameter(Mandatory = $true, ParameterSetName = 'Identity')]
[Alias('Id')]
[guid]
$Identity,
[Parameter(Mandatory = $true, ParameterSetName = 'Url')]
[string]
$Url,
[Parameter(Mandatory = $true, ParameterSetName = 'Title')]
[string]
$Title,
[Parameter(Mandatory = $true, ParameterSetName = 'Default')]
[switch]
$Default,
[Parameter(Mandatory = $false)]
[string]
$Retrievals
)
process {
if ($ClientContext -eq $null) {
throw "Cannot bind argument to parameter 'ClientContext' because it is null."
}
$ClientObjectCollection = $ParentList.Views
if ($PSCmdlet.ParameterSetName -eq 'All') {
Invoke-SPClientLoadQuery `
-ClientContext $ClientContext `
-ClientObject $ClientObjectCollection `
-Retrievals $Retrievals
Write-Output @(, $ClientObjectCollection)
}
if ($PSCmdlet.ParameterSetName -eq 'Identity') {
$PathMethod = New-Object Microsoft.SharePoint.Client.ObjectPathMethod( `
$ClientContext, `
$ClientObjectCollection.Path, `
'GetById', `
[object[]]$Identity)
$ClientObject = New-Object Microsoft.SharePoint.Client.View($ClientContext, $PathMethod)
Invoke-SPClientLoadQuery `
-ClientContext $ClientContext `
-ClientObject $ClientObject `
-Retrievals $Retrievals
Write-Output $ClientObject
trap {
throw 'The specified view could not be found.'
}
}
if ($PSCmdlet.ParameterSetName -eq 'Url') {
Invoke-SPClientLoadQuery `
-ClientContext $ClientContext `
-ClientObject $ClientObjectCollection `
-Retrievals 'ServerRelativeUrl'
$ClientObject = $ClientObjectCollection | Where-Object { $_.ServerRelativeUrl -eq $Url }
if ($ClientObject -eq $null) {
throw 'The specified view could not be found.'
}
Invoke-SPClientLoadQuery `
-ClientContext $ClientContext `
-ClientObject $ClientObject `
-Retrievals $Retrievals
Write-Output $ClientObject
}
if ($PSCmdlet.ParameterSetName -eq 'Title') {
$PathMethod = New-Object Microsoft.SharePoint.Client.ObjectPathMethod( `
$ClientContext, `
$ClientObjectCollection.Path, `
'GetByTitle', `
[object[]]$Title)
$ClientObject = New-Object Microsoft.SharePoint.Client.View($ClientContext, $PathMethod)
Invoke-SPClientLoadQuery `
-ClientContext $ClientContext `
-ClientObject $ClientObject `
-Retrievals $Retrievals
Write-Output $ClientObject
trap {
throw 'The specified view could not be found.'
}
}
if ($PSCmdlet.ParameterSetName -eq 'Default') {
$ClientObject = $ParentList.DefaultView
Invoke-SPClientLoadQuery `
-ClientContext $ClientContext `
-ClientObject $ClientObject `
-Retrievals $Retrievals
Write-Output $ClientObject
}
}
}
|
PowerShellCorpus/PowerShellGallery/SPClient/0.9/functions/SPClientView/Remove-SPClientView.ps1
|
Remove-SPClientView.ps1
|
#Requires -Version 3.0
# Remove-SPClientView.ps1
#
# Copyright (c) 2017 karamem0
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
function Remove-SPClientView {
<#
.SYNOPSIS
Deletes a view.
.PARAMETER ClientContext
Indicates the client context.
If not specified, uses default context.
.PARAMETER ClientObject
Indicates the view to delete.
.PARAMETER ParentList
Indicates the list which the view is contained.
.PARAMETER Identity
Indicates the view GUID.
.PARAMETER Url
Indicates the view url.
.PARAMETER Title
Indicates the view title.
#>
[CmdletBinding(DefaultParameterSetName = 'ClientObject')]
param (
[Parameter(Mandatory = $false)]
[Microsoft.SharePoint.Client.ClientContext]
$ClientContext = $SPClient.ClientContext,
[Parameter(Mandatory = $true, ValueFromPipeline = $true, ParameterSetName = 'ClientObject')]
[Microsoft.SharePoint.Client.View]
$ClientObject,
[Parameter(Mandatory = $true, ValueFromPipeline = $true, ParameterSetName = 'Identity')]
[Parameter(Mandatory = $true, ValueFromPipeline = $true, ParameterSetName = 'Url')]
[Parameter(Mandatory = $true, ValueFromPipeline = $true, ParameterSetName = 'Title')]
[Microsoft.SharePoint.Client.List]
$ParentList,
[Parameter(Mandatory = $true, ParameterSetName = 'Identity')]
[Alias('Id')]
[guid]
$Identity,
[Parameter(Mandatory = $true, ParameterSetName = 'Url')]
[string]
$Url,
[Parameter(Mandatory = $true, ParameterSetName = 'Title')]
[string]
$Title
)
process {
if ($ClientContext -eq $null) {
throw "Cannot bind argument to parameter 'ClientContext' because it is null."
}
if ($PSCmdlet.ParameterSetName -eq 'ClientObject') {
if (-not $ClientObject.IsPropertyAvailable('Id')) {
Invoke-SPClientLoadQuery `
-ClientContext $ClientContext `
-ClientObject $ClientObject `
-Retrievals 'Id'
}
} else {
$ClientObjectCollection = $ParentList.Views
if ($PSCmdlet.ParameterSetName -eq 'Identity') {
$PathMethod = New-Object Microsoft.SharePoint.Client.ObjectPathMethod( `
$ClientContext, `
$ClientObjectCollection.Path, `
'GetById', `
[object[]]$Identity)
$ClientObject = New-Object Microsoft.SharePoint.Client.View($ClientContext, $PathMethod)
Invoke-SPClientLoadQuery `
-ClientContext $ClientContext `
-ClientObject $ClientObject `
-Retrievals 'Id'
trap {
throw 'The specified view could not be found.'
}
}
if ($PSCmdlet.ParameterSetName -eq 'Url') {
Invoke-SPClientLoadQuery `
-ClientContext $ClientContext `
-ClientObject $ClientObjectCollection `
-Retrievals 'Include(Id,ServerRelativeUrl)'
$ClientObject = $ClientObjectCollection | Where-Object { $_.ServerRelativeUrl -eq $Url }
if ($ClientObject -eq $null) {
throw 'The specified view could not be found.'
}
}
if ($PSCmdlet.ParameterSetName -eq 'Title') {
$PathMethod = New-Object Microsoft.SharePoint.Client.ObjectPathMethod( `
$ClientContext, `
$ClientObjectCollection.Path, `
'GetByTitle', `
[object[]]$Title)
$ClientObject = New-Object Microsoft.SharePoint.Client.View($ClientContext, $PathMethod)
Invoke-SPClientLoadQuery `
-ClientContext $ClientContext `
-ClientObject $ClientObject `
-Retrievals 'Id'
trap {
throw 'The specified view could not be found.'
}
}
}
$ClientObject.DeleteObject()
$ClientContext.ExecuteQuery()
}
}
|
PowerShellCorpus/PowerShellGallery/SPClient/0.9/functions/SPClientView/New-SPClientView.ps1
|
New-SPClientView.ps1
|
#Requires -Version 3.0
# New-SPClientView.ps1
#
# Copyright (c) 2017 karamem0
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
function New-SPClientView {
<#
.SYNOPSIS
Creates a new view.
.PARAMETER ClientContext
Indicates the client context.
If not specified, uses default context.
.PARAMETER ParentList
Indicates the list which a view to be created.
.PARAMETER Name
Indicates the internal name.
.PARAMETER Title
Indicates the title.
If not specified, uses the internal name.
.PARAMETER ViewFields
Indicates the collection of view fields.
.PARAMETER Query
Indicates the XML representation of the query.
.PARAMETER RowLimit
Indicates the number of items.
.PARAMETER Paged
Indicates a value whether the view is a paged view.
.PARAMETER SetAsDefaultView
Indicates a value whether the view is the default view.
.PARAMETER ViewTypeKind
Indicates the type of the view.
.PARAMETER PersonalView
Indicates a value whether the view is a personal view.
.PARAMETER Retrievals
Indicates the data retrieval expression.
#>
[CmdletBinding()]
param (
[Parameter(Mandatory = $false)]
[Microsoft.SharePoint.Client.ClientContext]
$ClientContext = $SPClient.ClientContext,
[Parameter(Mandatory = $true, ValueFromPipeline = $true)]
[Microsoft.SharePoint.Client.List]
$ParentList,
[Parameter(Mandatory = $true)]
[string]
$Name,
[Parameter(Mandatory = $false)]
[string]
$Title = $Name,
[Parameter(Mandatory = $false)]
[string[]]
$ViewFields,
[Parameter(Mandatory = $false)]
[string]
$Query,
[Parameter(Mandatory = $false)]
[int]
$RowLimit,
[Parameter(Mandatory = $false)]
[bool]
$Paged,
[Parameter(Mandatory = $false)]
[bool]
$SetAsDefaultView,
[Parameter(Mandatory = $false)]
[ValidateSet('Html', 'Grid', 'Calendar', 'Recurrence', 'Chart', 'Gantt')]
[string]
$ViewType = 'Html',
[Parameter(Mandatory = $false)]
[bool]
$PersonalView,
[Parameter(Mandatory = $false)]
[string]
$Retrievals
)
process {
if ($ClientContext -eq $null) {
throw "Cannot bind argument to parameter 'ClientContext' because it is null."
}
$Creation = New-Object Microsoft.SharePoint.Client.ViewCreationInformation
$Creation.Title = $Name
$Creation.ViewFields = $ViewFields
if ($MyInvocation.BoundParameters.ContainsKey('Query')) {
$XmlDocument = New-Object System.Xml.XmlDocument
$QueryElement = $XmlDocument.AppendChild($XmlDocument.CreateElement('Query'))
$QueryElement.InnerXml = $Query
if ($QueryElement.FirstChild.Name -eq 'Query') {
$QueryElement = $QueryElement.FirstChild
}
$Query = $QueryElement.InnerXml
$Creation.Query = $Query
}
$Creation.RowLimit = $RowLimit
$Creation.Paged = $Paged
$Creation.SetAsDefaultView = $SetAsDefaultView
$Creation.ViewTypeKind = $ViewType
$Creation.PersonalView = $PersonalView
$ClientObject = $ParentList.Views.Add($Creation)
$ClientObject.Title = $Title
$ClientObject.Update()
Invoke-SPClientLoadQuery `
-ClientContext $ClientContext `
-ClientObject $ClientObject `
-Retrievals $Retrievals
Write-Output $ClientObject
}
}
|
PowerShellCorpus/PowerShellGallery/SPClient/0.9/functions/SPClientUser/Get-SPClientUser.ps1
|
Get-SPClientUser.ps1
|
#Requires -Version 3.0
# Get-SPClientUser.ps1
#
# Copyright (c) 2017 karamem0
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
function Get-SPClientUser {
<#
.SYNOPSIS
Lists all site users or retrieve the specified site user.
.DESCRIPTION
If not specified filterable parameter, returns site all users. Otherwise,
returns a user which matches the parameter.
.PARAMETER ClientContext
Indicates the client context.
If not specified, uses default context.
.PARAMETER Identity
Indicates the user id.
.PARAMETER Name
Indicates the user login name.
.PARAMETER Email
Indicates the user email.
.PARAMETER Current
If specified, returns current user.
.PARAMETER Retrievals
Indicates the data retrieval expression.
#>
[CmdletBinding(DefaultParameterSetName = 'All')]
param (
[Parameter(Mandatory = $false, ParameterSetName = 'All')]
[Parameter(Mandatory = $false, ParameterSetName = 'Identity')]
[Parameter(Mandatory = $false, ParameterSetName = 'Name')]
[Parameter(Mandatory = $false, ParameterSetName = 'Email')]
[Parameter(Mandatory = $false, ParameterSetName = 'Current')]
[Microsoft.SharePoint.Client.ClientContext]
$ClientContext = $SPClient.ClientContext,
[Parameter(Mandatory = $true, ParameterSetName = 'Identity')]
[int]
$Identity,
[Parameter(Mandatory = $true, ParameterSetName = 'Name')]
[Alias('LoginName')]
[string]
$Name,
[Parameter(Mandatory = $true, ParameterSetName = 'Email')]
[string]
$Email,
[Parameter(Mandatory = $true, ParameterSetName = 'Current')]
[switch]
$Current,
[Parameter(Mandatory = $false)]
[string]
$Retrievals
)
process {
if ($ClientContext -eq $null) {
throw "Cannot bind argument to parameter 'ClientContext' because it is null."
}
$ClientObjectCollection = $ClientContext.Site.RootWeb.SiteUsers
if ($PSCmdlet.ParameterSetName -eq 'All') {
Invoke-SPClientLoadQuery `
-ClientContext $ClientContext `
-ClientObject $ClientObjectCollection `
-Retrievals $Retrievals
Write-Output @(, $ClientObjectCollection)
}
if ($PSCmdlet.ParameterSetName -eq 'Identity') {
$PathMethod = New-Object Microsoft.SharePoint.Client.ObjectPathMethod( `
$ClientContext, `
$ClientObjectCollection.Path, `
'GetById', `
[object[]]$Identity)
$ClientObject = New-Object Microsoft.SharePoint.Client.User($ClientContext, $PathMethod)
Invoke-SPClientLoadQuery `
-ClientContext $ClientContext `
-ClientObject $ClientObject `
-Retrievals $Retrievals
Write-Output $ClientObject
trap {
throw 'The specified user could not be found.'
}
}
if ($PSCmdlet.ParameterSetName -eq 'Name') {
$PathMethod = New-Object Microsoft.SharePoint.Client.ObjectPathMethod( `
$ClientContext, `
$ClientObjectCollection.Path, `
'GetByLoginName', `
[object[]]$Name)
$ClientObject = New-Object Microsoft.SharePoint.Client.User($ClientContext, $PathMethod)
Invoke-SPClientLoadQuery `
-ClientContext $ClientContext `
-ClientObject $ClientObject `
-Retrievals $Retrievals
Write-Output $ClientObject
trap {
throw 'The specified user could not be found.'
}
}
if ($PSCmdlet.ParameterSetName -eq 'Email') {
$PathMethod = New-Object Microsoft.SharePoint.Client.ObjectPathMethod( `
$ClientContext, `
$ClientObjectCollection.Path, `
'GetByEmail', `
[object[]]$Email)
$ClientObject = New-Object Microsoft.SharePoint.Client.User($ClientContext, $PathMethod)
Invoke-SPClientLoadQuery `
-ClientContext $ClientContext `
-ClientObject $ClientObject `
-Retrievals $Retrievals
Write-Output $ClientObject
trap {
throw 'The specified user could not be found.'
}
}
if ($PSCmdlet.ParameterSetName -eq 'Current') {
$ClientObject = $ClientContext.Site.RootWeb.CurrentUser
Invoke-SPClientLoadQuery `
-ClientContext $ClientContext `
-ClientObject $ClientObject `
-Retrievals $Retrievals
Write-Output $ClientObject
trap {
throw 'The specified user could not be found.'
}
}
}
}
|
PowerShellCorpus/PowerShellGallery/SPClient/0.9/functions/SPClientUser/Remove-SPClientUser.ps1
|
Remove-SPClientUser.ps1
|
#Requires -Version 3.0
# Remove-SPClientUser.ps1
#
# Copyright (c) 2017 karamem0
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
function Remove-SPClientUser {
<#
.SYNOPSIS
Deletes a user.
.PARAMETER ClientContext
Indicates the client context.
If not specified, uses default context.
.PARAMETER ClientObject
Indicates the user to delete.
.PARAMETER Identity
Indicates the user id.
.PARAMETER Name
Indicates the user login name.
.PARAMETER Email
Indicates the user email.
#>
[CmdletBinding(DefaultParameterSetName = 'ClientObject')]
param (
[Parameter(Mandatory = $false)]
[Microsoft.SharePoint.Client.ClientContext]
$ClientContext = $SPClient.ClientContext,
[Parameter(Mandatory = $true, ValueFromPipeline = $true, ParameterSetName = 'ClientObject')]
[Microsoft.SharePoint.Client.User]
$ClientObject,
[Parameter(Mandatory = $true, ParameterSetName = 'Identity')]
[Alias('Id')]
[int]
$Identity,
[Parameter(Mandatory = $true, ParameterSetName = 'Name')]
[Alias('LoginName')]
[string]
$Name,
[Parameter(Mandatory = $true, ParameterSetName = 'Email')]
[string]
$Email
)
process {
if ($ClientContext -eq $null) {
throw "Cannot bind argument to parameter 'ClientContext' because it is null."
}
$ClientObjectCollection = $ClientContext.Site.RootWeb.SiteUsers
if ($PSCmdlet.ParameterSetName -eq 'ClientObject') {
if (-not $ClientObject.IsPropertyAvailable('Id')) {
Invoke-SPClientLoadQuery `
-ClientContext $ClientContext `
-ClientObject $ClientObject `
-Retrievals 'Id'
}
} else {
if ($PSCmdlet.ParameterSetName -eq 'Identity') {
$PathMethod = New-Object Microsoft.SharePoint.Client.ObjectPathMethod( `
$ClientContext, `
$ClientObjectCollection.Path, `
'GetById', `
[object[]]$Identity)
$ClientObject = New-Object Microsoft.SharePoint.Client.User($ClientContext, $PathMethod)
Invoke-SPClientLoadQuery `
-ClientContext $ClientContext `
-ClientObject $ClientObject `
-Retrievals 'Id'
trap {
throw 'The specified user could not be found.'
}
}
if ($PSCmdlet.ParameterSetName -eq 'Name') {
$PathMethod = New-Object Microsoft.SharePoint.Client.ObjectPathMethod( `
$ClientContext, `
$ClientObjectCollection.Path, `
'GetByLoginName', `
[object[]]$Name)
$ClientObject = New-Object Microsoft.SharePoint.Client.User($ClientContext, $PathMethod)
Invoke-SPClientLoadQuery `
-ClientContext $ClientContext `
-ClientObject $ClientObject `
-Retrievals 'Id'
trap {
throw 'The specified user could not be found.'
}
}
if ($PSCmdlet.ParameterSetName -eq 'Email') {
$PathMethod = New-Object Microsoft.SharePoint.Client.ObjectPathMethod( `
$ClientContext, `
$ClientObjectCollection.Path, `
'GetByEmail', `
[object[]]$Email)
$ClientObject = New-Object Microsoft.SharePoint.Client.User($ClientContext, $PathMethod)
Invoke-SPClientLoadQuery `
-ClientContext $ClientContext `
-ClientObject $ClientObject `
-Retrievals 'Id'
trap {
throw 'The specified user could not be found.'
}
}
}
$ClientObjectCollection.Remove($ClientObject)
$ClientContext.ExecuteQuery()
}
}
|
PowerShellCorpus/PowerShellGallery/SPClient/0.9/functions/SPClientUser/Resolve-SPClientUser.ps1
|
Resolve-SPClientUser.ps1
|
#Requires -Version 3.0
# Resolve-SPClientUser.ps1
#
# Copyright (c) 2017 karamem0
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
function Resolve-SPClientUser {
<#
.SYNOPSIS
Checks whether the specified login name belongs to a valid user.
.PARAMETER ClientContext
Indicates the client context.
If not specified, uses default context.
.PARAMETER Name
Indicates login name or e-mail address.
#>
[CmdletBinding()]
param (
[Parameter(Mandatory = $false)]
[Microsoft.SharePoint.Client.ClientContext]
$ClientContext = $SPClient.ClientContext,
[Parameter(Mandatory = $true)]
[string]
$Name
)
process {
if ($ClientContext -eq $null) {
throw "Cannot bind argument to parameter 'ClientContext' because it is null."
}
$ClientObject = $ClientContext.Site.RootWeb.EnsureUser($Name)
Invoke-SPClientLoadQuery `
-ClientContext $ClientContext `
-ClientObject $ClientObject `
-Retrievals $Retrievals
Write-Output $ClientObject
trap {
throw 'The specified user could not be found.'
}
}
}
|
PowerShellCorpus/PowerShellGallery/SPClient/0.9/functions/SPClientUser/New-SPClientUser.ps1
|
New-SPClientUser.ps1
|
#Requires -Version 3.0
# New-SPClientUser.ps1
#
# Copyright (c) 2017 karamem0
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
function New-SPClientUser {
<#
.SYNOPSIS
Creates a new view.
.PARAMETER ClientContext
Indicates the client context.
If not specified, uses default context.
.PARAMETER Name
Indicates the login name.
.PARAMETER Title
Indicates the display name.
.PARAMETER Email
Indicates the email.
.PARAMETER IsSiteAdmin
Indicates a value whether the user is a site collection administrator.
.PARAMETER Retrievals
Indicates the data retrieval expression.
#>
[CmdletBinding()]
param (
[Parameter(Mandatory = $false)]
[Microsoft.SharePoint.Client.ClientContext]
$ClientContext = $SPClient.ClientContext,
[Parameter(Mandatory = $true)]
[Alias('LoginName')]
[string]
$Name,
[Parameter(Mandatory = $false)]
[string]
$Title,
[Parameter(Mandatory = $false)]
[string]
$Email,
[Parameter(Mandatory = $false)]
[bool]
$IsSiteAdmin,
[Parameter(Mandatory = $false)]
[string]
$Retrievals
)
process {
if ($ClientContext -eq $null) {
throw "Cannot bind argument to parameter 'ClientContext' because it is null."
}
$Creation = New-Object Microsoft.SharePoint.Client.UserCreationInformation
$Creation.LoginName = $Name
$Creation.Email = $Email
$Creation.Title = $Title
$ClientObject = $ClientContext.Site.RootWeb.SiteUsers.Add($Creation)
if ($MyInvocation.BoundParameters.ContainsKey('IsSiteAdmin')) {
$ClientObject.IsSiteAdmin = $IsSiteAdmin
}
$ClientObject.Update()
Invoke-SPClientLoadQuery `
-ClientContext $ClientContext `
-ClientObject $ClientObject `
-Retrievals $Retrievals
Write-Output $ClientObject
}
}
|
PowerShellCorpus/PowerShellGallery/SPClient/0.9/functions/SPClientList/Get-SPClientList.ps1
|
Get-SPClientList.ps1
|
#Requires -Version 3.0
# Get-SPClientList.ps1
#
# Copyright (c) 2017 karamem0
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
function Get-SPClientList {
<#
.SYNOPSIS
Lists all lists or retrieve the specified list.
.DESCRIPTION
If not specified filterable parameter, returns all lists of the web.
Otherwise, returns a list which matches the parameter.
.PARAMETER ClientContext
Indicates the client context.
.PARAMETER ParentWeb
Indicates the web which the lists are contained.
.PARAMETER Identity
Indicates the list GUID.
.PARAMETER Url
Indicates the list url.
.PARAMETER Name
Indicates the list title or internal name.
.PARAMETER Retrievals
Indicates the data retrieval expression.
#>
[CmdletBinding(DefaultParameterSetName = 'All')]
param (
[Parameter(Mandatory = $false, ParameterSetName = 'All')]
[Parameter(Mandatory = $false, ParameterSetName = 'Identity')]
[Parameter(Mandatory = $false, ParameterSetName = 'Url')]
[Parameter(Mandatory = $false, ParameterSetName = 'Name')]
[Microsoft.SharePoint.Client.ClientContext]
$ClientContext = $SPClient.ClientContext,
[Parameter(Mandatory = $true, ValueFromPipeline = $true)]
[Microsoft.SharePoint.Client.Web]
$ParentWeb,
[Parameter(Mandatory = $true, ParameterSetName = 'Identity')]
[Alias('Id')]
[guid]
$Identity,
[Parameter(Mandatory = $true, ParameterSetName = 'Url')]
[string]
$Url,
[Parameter(Mandatory = $true, ParameterSetName = 'Name')]
[Alias('Title')]
[string]
$Name,
[Parameter(Mandatory = $false)]
[string]
$Retrievals
)
process {
if ($ClientContext -eq $null) {
throw "Cannot bind argument to parameter 'ClientContext' because it is null."
}
$ClientObjectCollection = $ParentWeb.Lists
if ($PSCmdlet.ParameterSetName -eq 'All') {
Invoke-SPClientLoadQuery `
-ClientContext $ClientContext `
-ClientObject $ClientObjectCollection `
-Retrievals $Retrievals
Write-Output @(, $ClientObjectCollection)
}
if ($PSCmdlet.ParameterSetName -eq 'Identity') {
$PathMethod = New-Object Microsoft.SharePoint.Client.ObjectPathMethod( `
$ClientContext, `
$ClientObjectCollection.Path, `
'GetById', `
[object[]]$Identity)
$ClientObject = New-Object Microsoft.SharePoint.Client.List($ClientContext, $PathMethod)
Invoke-SPClientLoadQuery `
-ClientContext $ClientContext `
-ClientObject $ClientObject `
-Retrievals $Retrievals
Write-Output $ClientObject
trap {
throw 'The specified list could not be found.'
}
}
if ($PSCmdlet.ParameterSetName -eq 'Url') {
$PathMethod = New-Object Microsoft.SharePoint.Client.ObjectPathMethod( `
$ClientContext, `
$ParentWeb.Path, `
'GetList', `
[object[]]$Url)
$ClientObject = New-Object Microsoft.SharePoint.Client.List($ClientContext, $PathMethod)
Invoke-SPClientLoadQuery `
-ClientContext $ClientContext `
-ClientObject $ClientObject `
-Retrievals $Retrievals
Write-Output $ClientObject
trap {
throw 'The specified list could not be found.'
}
}
if ($PSCmdlet.ParameterSetName -eq 'Name') {
try {
$PathMethod = New-Object Microsoft.SharePoint.Client.ObjectPathMethod( `
$ClientContext, `
$ClientObjectCollection.Path, `
'GetByTitle', `
[object[]]$Name)
$ClientObject = New-Object Microsoft.SharePoint.Client.List($ClientContext, $PathMethod)
Invoke-SPClientLoadQuery `
-ClientContext $ClientContext `
-ClientObject $ClientObject `
-Retrievals $Retrievals
} catch {
Invoke-SPClientLoadQuery `
-ClientContext $ClientContext `
-ClientObject $ClientObjectCollection `
-Retrievals 'Include(RootFolder.Name)'
$ClientObject = $ClientObjectCollection | Where-Object { $_.RootFolder.Name -eq $Name }
if ($ClientObject -eq $null) {
throw 'The specified list could not be found.'
}
Invoke-SPClientLoadQuery `
-ClientContext $ClientContext `
-ClientObject $ClientObject `
-Retrievals $Retrievals
}
Write-Output $ClientObject
}
}
}
|
PowerShellCorpus/PowerShellGallery/SPClient/0.9/functions/SPClientList/New-SPClientList.ps1
|
New-SPClientList.ps1
|
#Requires -Version 3.0
# New-SPClientList.ps1
#
# Copyright (c) 2017 karamem0
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
function New-SPClientList {
<#
.SYNOPSIS
Creates a new list.
.PARAMETER ClientContext
Indicates the client context.
If not specified, uses default context.
.PARAMETER ParentWeb
Indicates the web which a list to be created.
.PARAMETER Name
Indicates the internal name.
.PARAMETER Title
Indicates the title.
If not specified, uses the internal name.
.PARAMETER Description
Indicates the description.
.PARAMETER Template
Indicates the template ID.
If not specified, uses 100 (Generic List).
.PARAMETER EnableAttachments
Indicates a value whether attachments are enabled.
.PARAMETER EnableFolderCreation
Indicates a value whether new folders can be added.
.PARAMETER EnableVersioning
Indicates a value whether historical versions can be created.
.PARAMETER NoCrawl
Indicates a value whether crawler must not crawl.
.PARAMETER OnQuickLaunch
Indicates a value whether the list is displayed on the quick launch.
.PARAMETER Retrievals
Indicates the data retrieval expression.
#>
[CmdletBinding()]
param (
[Parameter(Mandatory = $false)]
[Microsoft.SharePoint.Client.ClientContext]
$ClientContext = $SPClient.ClientContext,
[Parameter(Mandatory = $true, ValueFromPipeline = $true)]
[Microsoft.SharePoint.Client.Web]
$ParentWeb,
[Parameter(Mandatory = $true)]
[string]
$Name,
[Parameter(Mandatory = $false)]
[string]
$Title = $Name,
[Parameter(Mandatory = $false)]
[string]
$Description,
[Parameter(Mandatory = $false)]
[int]
$Template = 100,
[Parameter(Mandatory = $false)]
[bool]
$EnableAttachments,
[Parameter(Mandatory = $false)]
[bool]
$EnableFolderCreation,
[Parameter(Mandatory = $false)]
[bool]
$EnableVersioning,
[Parameter(Mandatory = $false)]
[bool]
$NoCrawl,
[Parameter(Mandatory = $false)]
[bool]
$OnQuickLaunch,
[Parameter(Mandatory = $false)]
[string]
$Retrievals
)
process {
if ($ClientContext -eq $null) {
throw "Cannot bind argument to parameter 'ClientContext' because it is null."
}
$Creation = New-Object Microsoft.SharePoint.Client.ListCreationInformation
$Creation.Title = $Name
$Creation.Description = $Description
$Creation.TemplateType = $Template
$ClientObject = $ParentWeb.Lists.Add($Creation)
$ClientObject.Title = $Title
$ClientObject.EnableAttachments = $EnableAttachments
$ClientObject.EnableFolderCreation = $EnableFolderCreation
$ClientObject.EnableVersioning = $EnableVersioning
$ClientObject.NoCrawl = $NoCrawl
$ClientObject.OnQuickLaunch = $OnQuickLaunch
$ClientObject.Update()
Invoke-SPClientLoadQuery `
-ClientContext $ClientContext `
-ClientObject $ClientObject `
-Retrievals $Retrievals
Write-Output $ClientObject
}
}
|
PowerShellCorpus/PowerShellGallery/SPClient/0.9/functions/SPClientList/Remove-SPClientList.ps1
|
Remove-SPClientList.ps1
|
#Requires -Version 3.0
# Remove-SPClientList.ps1
#
# Copyright (c) 2017 karamem0
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
function Remove-SPClientList {
<#
.SYNOPSIS
Deletes a list.
.PARAMETER ClientContext
Indicates the client context.
If not specified, uses default context.
.PARAMETER ClientObject
Indicates the list to delete.
.PARAMETER ParentWeb
Indicates the web which the list is contained.
.PARAMETER Identity
Indicates the list GUID.
.PARAMETER Url
Indicates the list relative url.
.PARAMETER Name
Indicates the list title or internal name.
#>
[CmdletBinding(DefaultParameterSetName = 'ClientObject')]
param (
[Parameter(Mandatory = $false)]
[Microsoft.SharePoint.Client.ClientContext]
$ClientContext = $SPClient.ClientContext,
[Parameter(Mandatory = $true, ValueFromPipeline = $true, ParameterSetName = 'ClientObject')]
[Microsoft.SharePoint.Client.List]
$ClientObject,
[Parameter(Mandatory = $true, ValueFromPipeline = $true, ParameterSetName = 'Identity')]
[Parameter(Mandatory = $true, ValueFromPipeline = $true, ParameterSetName = 'Url')]
[Parameter(Mandatory = $true, ValueFromPipeline = $true, ParameterSetName = 'Name')]
[Microsoft.SharePoint.Client.Web]
$ParentWeb,
[Parameter(Mandatory = $true, ParameterSetName = 'Identity')]
[Alias('Id')]
[guid]
$Identity,
[Parameter(Mandatory = $true, ParameterSetName = 'Url')]
[string]
$Url,
[Parameter(Mandatory = $true, ParameterSetName = 'Name')]
[Alias('Title')]
[string]
$Name
)
process {
if ($ClientContext -eq $null) {
throw "Cannot bind argument to parameter 'ClientContext' because it is null."
}
if ($PSCmdlet.ParameterSetName -eq 'ClientObject') {
if (-not $ClientObject.IsPropertyAvailable('Id')) {
Invoke-SPClientLoadQuery `
-ClientContext $ClientContext `
-ClientObject $ClientObject `
-Retrievals 'Id'
}
} else {
$ClientObjectCollection = $ParentWeb.Lists
if ($PSCmdlet.ParameterSetName -eq 'Identity') {
$PathMethod = New-Object Microsoft.SharePoint.Client.ObjectPathMethod( `
$ClientContext, `
$ClientObjectCollection.Path, `
'GetById', `
[object[]]$Identity)
$ClientObject = New-Object Microsoft.SharePoint.Client.List($ClientContext, $PathMethod)
Invoke-SPClientLoadQuery `
-ClientContext $ClientContext `
-ClientObject $ClientObject `
-Retrievals 'Id'
trap {
throw 'The specified list could not be found.'
}
}
if ($PSCmdlet.ParameterSetName -eq 'Url') {
$PathMethod = New-Object Microsoft.SharePoint.Client.ObjectPathMethod( `
$ClientContext, `
$ParentWeb.Path, `
'GetList', `
[object[]]$Url)
$ClientObject = New-Object Microsoft.SharePoint.Client.List($ClientContext, $PathMethod)
Invoke-SPClientLoadQuery `
-ClientContext $ClientContext `
-ClientObject $ClientObject `
-Retrievals 'Id'
trap {
throw 'The specified list could not be found.'
}
}
if ($PSCmdlet.ParameterSetName -eq 'Name') {
try {
$PathMethod = New-Object Microsoft.SharePoint.Client.ObjectPathMethod( `
$ClientContext, `
$ClientObjectCollection.Path, `
'GetByTitle', `
[object[]]$Name)
$ClientObject = New-Object Microsoft.SharePoint.Client.List($ClientContext, $PathMethod)
Invoke-SPClientLoadQuery `
-ClientContext $ClientContext `
-ClientObject $ClientObject `
-Retrievals 'Id'
} catch {
Invoke-SPClientLoadQuery `
-ClientContext $ClientContext `
-ClientObject $ClientObjectCollection `
-Retrievals 'Include(RootFolder.Name)'
$ClientObject = $ClientObjectCollection | Where-Object { $_.RootFolder.Name -eq $Name }
if ($ClientObject -eq $null) {
throw 'The specified list could not be found.'
}
}
}
}
$ClientObject.DeleteObject()
$ClientContext.ExecuteQuery()
}
}
|
PowerShellCorpus/PowerShellGallery/SPClient/0.9/functions/SPClientUniquePermission/Disable-SPClientUniquePermission.ps1
|
Disable-SPClientUniquePermission.ps1
|
#Requires -Version 3.0
# Disable-SPClientUniquePermission.ps1
#
# Copyright (c) 2017 karamem0
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
function Disable-SPClientUniquePermission {
<#
.SYNOPSIS
Disables unique permission to the specified object.
.PARAMETER ClientContext
Indicates the client context.
If not specified, uses default context.
.PARAMETER ClientObject
Indicates the web, list or item.
#>
[CmdletBinding()]
param (
[Parameter(Mandatory = $false)]
[Microsoft.SharePoint.Client.ClientContext]
$ClientContext = $SPClient.ClientContext,
[Parameter(Mandatory = $true, ValueFromPipeline = $true)]
[Microsoft.SharePoint.Client.SecurableObject]
$ClientObject
)
process {
if ($ClientContext -eq $null) {
throw "Cannot bind argument to parameter 'ClientContext' because it is null."
}
$ClientObject.ResetRoleInheritance()
Invoke-SPClientLoadQuery `
-ClientContext $ClientContext `
-ClientObject $ClientObject `
-Retrievals 'HasUniqueRoleAssignments'
}
}
|
PowerShellCorpus/PowerShellGallery/SPClient/0.9/functions/SPClientUniquePermission/Enable-SPClientUniquePermission.ps1
|
Enable-SPClientUniquePermission.ps1
|
#Requires -Version 3.0
# Enable-SPClientUniquePermission.ps1
#
# Copyright (c) 2017 karamem0
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
function Enable-SPClientUniquePermission {
<#
.SYNOPSIS
Enables unique permission to the specified object.
.PARAMETER ClientContext
Indicates the client context.
If not specified, uses default context.
.PARAMETER ClientObject
Indicates the web, list or item.
.PARAMETER CopyRoleAssignments
If specified, copies role assignments from the parent object.
.PARAMETER ClearSubscopes
If specified, resets role assignments of child objects.
#>
[CmdletBinding()]
param (
[Parameter(Mandatory = $false)]
[Microsoft.SharePoint.Client.ClientContext]
$ClientContext = $SPClient.ClientContext,
[Parameter(Mandatory = $true, ValueFromPipeline = $true)]
[Microsoft.SharePoint.Client.SecurableObject]
$ClientObject,
[Parameter(Mandatory = $false)]
[switch]
$CopyRoleAssignments,
[Parameter(Mandatory = $false)]
[switch]
$ClearSubscopes
)
process {
if ($ClientContext -eq $null) {
throw "Cannot bind argument to parameter 'ClientContext' because it is null."
}
$ClientObject.BreakRoleInheritance($CopyRoleAssignments, $ClearSubscopes)
Invoke-SPClientLoadQuery `
-ClientContext $ClientContext `
-ClientObject $ClientObject `
-Retrievals 'HasUniqueRoleAssignments'
}
}
|
PowerShellCorpus/PowerShellGallery/SPClient/0.9/functions/SPClientListItem/ConvertTo-SPClientListItem.ps1
|
ConvertTo-SPClientListItem.ps1
|
#Requires -Version 3.0
# ConvertTo-SPClientListItem.ps1
#
# Copyright (c) 2017 karamem0
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
function ConvertTo-SPClientListItem {
<#
.SYNOPSIS
Converts file or folder to list item.
.PARAMETER ClientContext
Indicates the client context.
If not specified, uses default context.
.PARAMETER File
Indicates the file.
.PARAMETER Folder
Indicates the folder.
.PARAMETER Retrievals
Indicates the data retrieval expression.
#>
[CmdletBinding()]
param (
[Parameter(Mandatory = $false)]
[Microsoft.SharePoint.Client.ClientContext]
$ClientContext = $SPClient.ClientContext,
[Parameter(Mandatory = $true, ValueFromPipeline = $true, ParameterSetName = 'File')]
[Microsoft.SharePoint.Client.File]
$File,
[Parameter(Mandatory = $true, ValueFromPipeline = $true, ParameterSetName = 'Folder')]
[Microsoft.SharePoint.Client.Folder]
$Folder,
[Parameter(Mandatory = $false)]
[string]
$Retrievals
)
process {
if ($ClientContext -eq $null) {
throw "Cannot bind argument to parameter 'ClientContext' because it is null."
}
if ($PSCmdlet.ParameterSetName -eq 'File') {
$ClientObject = $File.ListItemAllFields
Invoke-SPClientLoadQuery `
-ClientContext $ClientContext `
-ClientObject $ClientObject `
-Retrievals $Retrievals
Write-Output $ClientObject
}
if ($PSCmdlet.ParameterSetName -eq 'Folder') {
$ClientObject = $Folder.ListItemAllFields
Invoke-SPClientLoadQuery `
-ClientContext $ClientContext `
-ClientObject $ClientObject `
-Retrievals $Retrievals
Write-Output $ClientObject
}
}
}
|
PowerShellCorpus/PowerShellGallery/SPClient/0.9/functions/SPClientListItem/Get-SPClientListItem.ps1
|
Get-SPClientListItem.ps1
|
#Requires -Version 3.0
# Get-SPClientLisItem.ps1
#
# Copyright (c) 2017 karamem0
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
function Get-SPClientListItem {
<#
.SYNOPSIS
Retrieve list items using CAML query.
.PARAMETER ClientContext
Indicates the client context.
If not specified, uses default context.
.PARAMETER ParentList
Indicates the list which the list items are contained.
.PARAMETER FolderUrl
Indicates the folder relative url.
.PARAMETER Scope
Indicates the scope of retrievals.
- FilesOnly: Only the files of a specific folder.
- Recursive: All files of all folders.
- RecursiveAll: All files and all subfolders of all folders.
If not specified, only the files and subfolders of a specific folder.
.PARAMETER ViewFields
Indicates the collection of view fields.
.PARAMETER Query
Indicates the XML representation of query.
.PARAMETER RowLimit
Indicates the number of items.
This parameter is used for item pagination.
.PARAMETER Position
Indicates the starting position.
This parameter is used for item pagination.
.PARAMETER Identity
Indicates the list item ID.
.PARAMETER IdentityGuid
Indicates the list item GUID.
.PARAMETER Retrievals
Indicates the data retrieval expression.
#>
[CmdletBinding(DefaultParameterSetName = 'All')]
param (
[Parameter(Mandatory = $false, ParameterSetName = 'All')]
[Parameter(Mandatory = $false, ParameterSetName = 'Identity')]
[Parameter(Mandatory = $false, ParameterSetName = 'IdentityGuid')]
[Microsoft.SharePoint.Client.ClientContext]
$ClientContext = $SPClient.ClientContext,
[Parameter(Mandatory = $true, ValueFromPipeline = $true)]
[Microsoft.SharePoint.Client.List]
$ParentList,
[Parameter(Mandatory = $false, ParameterSetName = 'All')]
[string]
$FolderUrl,
[Parameter(Mandatory = $false, ParameterSetName = 'All')]
[ValidateSet('FilesOnly', 'Recursive', 'RecursiveAll')]
[string]
$Scope,
[Parameter(Mandatory = $false, ParameterSetName = 'All')]
[string[]]
$ViewFields,
[Parameter(Mandatory = $false, ParameterSetName = 'All')]
[string]
$Query,
[Parameter(Mandatory = $false, ParameterSetName = 'All')]
[int]
$RowLimit,
[Parameter(Mandatory = $false, ParameterSetName = 'All')]
[Microsoft.SharePoint.Client.ListItemCollectionPosition]
$Position,
[Parameter(Mandatory = $true, ParameterSetName = 'Identity')]
[Alias('Id')]
[int]
$Identity,
[Parameter(Mandatory = $true, ParameterSetName = 'IdentityGuid')]
[Alias('UniqueId')]
[guid]
$IdentityGuid,
[Parameter(Mandatory = $false)]
[string]
$Retrievals
)
process {
if ($ClientContext -eq $null) {
throw "Cannot bind argument to parameter 'ClientContext' because it is null."
}
if ($PSCmdlet.ParameterSetName -eq 'All') {
$Caml = New-object Microsoft.SharePoint.Client.CamlQuery
if ($MyInvocation.BoundParameters.ContainsKey('FolderUrl')) {
$Caml.FolderServerRelativeUrl = $FolderUrl
}
$XmlDocument = New-Object System.Xml.XmlDocument
$ViewElement = $XmlDocument.AppendChild($XmlDocument.CreateElement('View'))
if ($MyInvocation.BoundParameters.ContainsKey('Scope')) {
$ViewElement.SetAttribute('Scope', $Scope)
}
if ($MyInvocation.BoundParameters.ContainsKey('ViewFields')) {
$ViewFieldsElement = $ViewElement.AppendChild($XmlDocument.CreateElement('ViewFields'))
foreach ($ViewField in $ViewFields) {
$FieldRefElement = $ViewFieldsElement.AppendChild($XmlDocument.CreateElement('FieldRef'))
$FieldRefElement.SetAttribute('Name', $ViewField)
}
}
if ($MyInvocation.BoundParameters.ContainsKey('Query')) {
$QueryElement = $ViewElement.AppendChild($XmlDocument.CreateElement('Query'))
$QueryElement.InnerXml = $Query
if ($QueryElement.FirstChild.Name -eq 'Query') {
$QueryElement = $QueryElement.FirstChild
}
}
if ($MyInvocation.BoundParameters.ContainsKey('RowLimit')) {
$RowLimitElement = $ViewElement.AppendChild($XmlDocument.CreateElement('RowLimit'))
$RowLimitElement.InnerText = $RowLimit
}
if ($MyInvocation.BoundParameters.ContainsKey('Position')) {
$Caml.ListItemCollectionPosition = $Position
}
$Caml.ViewXml = $XmlDocument.InnerXml
$ClientObjectCollection = $ParentList.GetItems($Caml)
Invoke-SPClientLoadQuery `
-ClientContext $ClientContext `
-ClientObject $ClientObjectCollection `
-Retrievals $Retrievals
Write-Output @(, $ClientObjectCollection)
}
if ($PSCmdlet.ParameterSetName -eq 'Identity') {
$PathMethod = New-Object Microsoft.SharePoint.Client.ObjectPathMethod( `
$ClientContext, `
$ParentList.Path, `
'GetItemById', `
[object[]]$Identity)
$ClientObject = New-Object Microsoft.SharePoint.Client.ListItem($ClientContext, $PathMethod)
Invoke-SPClientLoadQuery `
-ClientContext $ClientContext `
-ClientObject $ClientObject `
-Retrievals $Retrievals
Write-Output $ClientObject
trap {
throw 'The specified list item could not be found.'
}
}
if ($PSCmdlet.ParameterSetName -eq 'IdentityGuid') {
$Caml = New-object Microsoft.SharePoint.Client.CamlQuery
$Caml.ViewXml = `
'<View Scope="RecursiveAll">' + `
'<RowLimit>1</RowLimit>' + `
'<Query>' + `
'<Where>' + `
'<Eq>' + `
'<FieldRef Name="UniqueId"/>' + `
'<Value Type="Guid">' + $IdentityGuid + '</Value>' + `
'</Eq>' + `
'</Where>' + `
'</Query>' + `
'</View>'
$ClientObjectCollection = $ParentList.GetItems($Caml)
Invoke-SPClientLoadQuery `
-ClientContext $ClientContext `
-ClientObject $ClientObjectCollection `
-Retrievals $Retrievals
if ($ClientObjectCollection.Count -eq 0) {
throw 'The specified list item could not be found.'
}
Write-Output $ClientObjectCollection[0]
}
}
}
|
PowerShellCorpus/PowerShellGallery/SPClient/0.9/functions/SPClientListItem/Remove-SPClientListItem.ps1
|
Remove-SPClientListItem.ps1
|
#Requires -Version 3.0
# Remove-SPClientListItem.ps1
#
# Copyright (c) 2017 karamem0
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
function Remove-SPClientListItem {
<#
.SYNOPSIS
Deletes a list item.
.PARAMETER ClientContext
Indicates the client context.
If not specified, uses default context.
.PARAMETER ClientObject
Indicates the list item to delete.
.PARAMETER ParentList
Indicates the list which the list item is contained.
.PARAMETER Identity
Indicates the list item ID.
#>
[CmdletBinding(DefaultParameterSetName = 'ClientObject')]
param (
[Parameter(Mandatory = $false)]
[Microsoft.SharePoint.Client.ClientContext]
$ClientContext = $SPClient.ClientContext,
[Parameter(Mandatory = $true, ValueFromPipeline = $true, ParameterSetName = 'ClientObject')]
[Microsoft.SharePoint.Client.ListItem]
$ClientObject,
[Parameter(Mandatory = $true, ValueFromPipeline = $true, ParameterSetName = 'Identity')]
[Microsoft.SharePoint.Client.List]
$ParentList,
[Parameter(Mandatory = $true, ParameterSetName = 'Identity')]
[Alias('Id')]
[int]
$Identity
)
process {
if ($ClientContext -eq $null) {
throw "Cannot bind argument to parameter 'ClientContext' because it is null."
}
if ($PSCmdlet.ParameterSetName -eq 'ClientObject') {
if (-not $ClientObject.IsPropertyAvailable('Id')) {
Invoke-SPClientLoadQuery `
-ClientContext $ClientContext `
-ClientObject $ClientObject `
-Retrievals 'Id'
}
} else {
if ($PSCmdlet.ParameterSetName -eq 'Identity') {
$PathMethod = New-Object Microsoft.SharePoint.Client.ObjectPathMethod( `
$ClientContext, `
$ParentList.Path, `
'GetItemById', `
[object[]]$Identity)
$ClientObject = New-Object Microsoft.SharePoint.Client.ListItem($ClientContext, $PathMethod)
Invoke-SPClientLoadQuery `
-ClientContext $ClientContext `
-ClientObject $ClientObject `
-Retrievals 'Id'
trap {
throw 'The specified list item could not be found.'
}
}
}
$ClientObject.DeleteObject()
$ClientContext.ExecuteQuery()
}
}
|
PowerShellCorpus/PowerShellGallery/SPClient/0.9/functions/SPClientListItem/New-SPClientListItem.ps1
|
New-SPClientListItem.ps1
|
#Requires -Version 3.0
# New-SPClientListItem.ps1
#
# Copyright (c) 2017 karamem0
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
function New-SPClientListItem {
<#
.SYNOPSIS
Creates a new list item.
.PARAMETER ClientContext
Indicates the client context.
If not specified, uses default context.
.PARAMETER ParentList
Indicates the list which a list item to be created.
.PARAMETER FieldValues
Indicates the field key/value collection.
.PARAMETER Retrievals
Indicates the data retrieval expression.
#>
[CmdletBinding()]
param (
[Parameter(Mandatory = $false)]
[Microsoft.SharePoint.Client.ClientContext]
$ClientContext = $SPClient.ClientContext,
[Parameter(Mandatory = $true, ValueFromPipeline = $true)]
[Microsoft.SharePoint.Client.List]
$ParentList,
[Parameter(Mandatory = $false)]
[hashtable]
$FieldValues,
[Parameter(Mandatory = $false)]
[string]
$Retrievals
)
process {
if ($ClientContext -eq $null) {
throw "Cannot bind argument to parameter 'ClientContext' because it is null."
}
$Creation = New-Object Microsoft.SharePoint.Client.ListItemCreationInformation
$ClientObject = $ParentList.AddItem($Creation)
if ($MyInvocation.BoundParameters.ContainsKey('FieldValues')) {
$FieldValues.GetEnumerator() | ForEach-Object {
$ClientObject[$_.Name] = $_.Value
}
}
$ClientObject.Update()
Invoke-SPClientLoadQuery `
-ClientContext $ClientContext `
-ClientObject $ClientObject `
-Retrievals $Retrievals
Write-Output $ClientObject
}
}
|
PowerShellCorpus/PowerShellGallery/SPClient/0.9/functions/SPClientField/New-SPClientFieldCalculated.ps1
|
New-SPClientFieldCalculated.ps1
|
#Requires -Version 3.0
# New-SPClientFieldCalculated.ps1
#
# Copyright (c) 2017 karamem0
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
function New-SPClientFieldCalculated {
<#
.SYNOPSIS
Creates a new field whose value is calculated based on other columns.
.PARAMETER ClientContext
Indicates the client context.
If not specified, uses default context.
.PARAMETER ParentList
Indicates the list which a field to be created.
.PARAMETER Name
Indicates the internal name.
.PARAMETER Title
Indicates the title.
.PARAMETER Identity
Indicates the field GUID.
.PARAMETER Description
Indicates the description.
.PARAMETER Fomula
Indicates the formula.
.PARAMETER FieldRefs
Indicates the collection of fields which used in formula.
.PARAMETER OutputType
Indicates the data type of the return value.
- Text
- Number
- Currency
- DateTime
- Boolean
.PARAMETER Decimals
Indicates the number of decimals.
This parameter is used when OutputType is 'Number' or 'Currency'.
.PARAMETER Percentage
Indicates a value whether the field shows as percentage.
This parameter is used when OutputType is 'Number'.
.PARAMETER LocaleId
Indicates the language code identifier (LCID).
This parameter is used when OutputType is 'Currency'.
.PARAMETER DateFormat
Indicates the datetime display format.
This parameter is used when OutputType is 'DateTime'.
.PARAMETER AddToDefaultView
If true, the field is add to default view.
.PARAMETER Retrievals
Indicates the data retrieval expression.
#>
[CmdletBinding()]
param (
[Parameter(Mandatory = $false)]
[Microsoft.SharePoint.Client.ClientContext]
$ClientContext = $SPClient.ClientContext,
[Parameter(Mandatory = $false, ValueFromPipeline = $true)]
[Microsoft.SharePoint.Client.List]
$ParentList,
[Parameter(Mandatory = $true)]
[string]
$Name,
[Parameter(Mandatory = $false)]
[string]
$Title = $Name,
[Parameter(Mandatory = $false)]
[guid]
$Identity,
[Parameter(Mandatory = $false)]
[string]
$Description,
[Parameter(Mandatory = $true)]
[string]
$Formula,
[Parameter(Mandatory = $true)]
[string[]]
$FieldRefs,
[Parameter(Mandatory = $true)]
[ValidateSet('Text', 'Number', 'Currency', 'DateTime', 'Boolean')]
[string]
$OutputType,
[Parameter(Mandatory = $false)]
[int]
$Decimals,
[Parameter(Mandatory = $false)]
[bool]
$Percentage,
[Parameter(Mandatory = $false)]
[int]
$LocaleId,
[Parameter(Mandatory = $false)]
[ValidateSet('DateOnly', 'DateTime')]
[string]
$DateFormat,
[Parameter(Mandatory = $false)]
[bool]
$AddToDefaultView,
[Parameter(Mandatory = $false)]
[string]
$Retrievals
)
process {
if ($ClientContext -eq $null) {
throw "Cannot bind argument to parameter 'ClientContext' because it is null."
}
$XmlDocument = New-Object System.Xml.XmlDocument
$FieldElement = $XmlDocument.AppendChild($XmlDocument.CreateElement('Field'))
$FieldElement.SetAttribute('Type', 'Calculated')
$FieldElement.SetAttribute('ReadOnly', 'TRUE')
$FieldElement.SetAttribute('Name', $Name)
$FieldElement.SetAttribute('DisplayName', $Title)
if ($MyInvocation.BoundParameters.ContainsKey('Identity')) {
$FieldElement.SetAttribute('ID', $Identity)
}
if ($MyInvocation.BoundParameters.ContainsKey('Description')) {
$FieldElement.SetAttribute('Description', $Description)
}
if ($MyInvocation.BoundParameters.ContainsKey('Formula')) {
$FormulaElement = $FieldElement.AppendChild($XmlDocument.CreateElement('Formula'))
$FormulaElement.InnerText = $Formula
}
if ($MyInvocation.BoundParameters.ContainsKey('FieldRefs')) {
$FieldRefsElement = $FieldElement.AppendChild($XmlDocument.CreateElement('FieldRefs'))
foreach ($FieldRef in $FieldRefs) {
$FieldRefElement = $FieldRefsElement.AppendChild($XmlDocument.CreateElement('FieldRef'))
$FieldRefElement.SetAttribute('Name', $FieldRef)
}
}
if ($MyInvocation.BoundParameters.ContainsKey('OutputType')) {
$FieldElement.SetAttribute('ResultType', $OutputType)
}
if ($MyInvocation.BoundParameters.ContainsKey('Decimals')) {
$FieldElement.SetAttribute('Decimals', $Decimals)
}
if ($MyInvocation.BoundParameters.ContainsKey('Percentage')) {
$FieldElement.SetAttribute('Percentage', $Percentage.ToString().ToUpper())
}
if ($MyInvocation.BoundParameters.ContainsKey('LocaleId')) {
$FieldElement.SetAttribute('LCID', $LocaleId)
}
if ($MyInvocation.BoundParameters.ContainsKey('DateFormat')) {
$FieldElement.SetAttribute('Format', $DateFormat)
}
$AddFieldOptions = [Microsoft.SharePoint.Client.AddFieldOptions]::AddFieldInternalNameHint
$ClientObject = $ParentList.Fields.AddFieldAsXml($XmlDocument.InnerXml, $AddToDefaultView, $AddFieldOptions)
Invoke-SPClientLoadQuery `
-ClientContext $ClientContext `
-ClientObject $ClientObject `
-Retrievals $Retrievals
$ClientObject = Convert-SPClientField `
-ClientContext $ClientContext `
-ClientObject $ClientObject
Write-Output $ClientObject
}
}
|
PowerShellCorpus/PowerShellGallery/SPClient/0.9/functions/SPClientField/New-SPClientFieldDateTime.ps1
|
New-SPClientFieldDateTime.ps1
|
#Requires -Version 3.0
# New-SPClientFieldDateTime.ps1
#
# Copyright (c) 2017 karamem0
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
function New-SPClientFieldDateTime {
<#
.SYNOPSIS
Creates a new field which user can enter a date and time.
.PARAMETER ClientContext
Indicates the client context.
If not specified, uses default context.
.PARAMETER ParentList
Indicates the list which a field to be created.
.PARAMETER Name
Indicates the internal name.
.PARAMETER Title
Indicates the title.
.PARAMETER Identity
Indicates the field GUID.
.PARAMETER Description
Indicates the description.
.PARAMETER Required
Indicates a value whether the field is required.
.PARAMETER EnforceUniqueValues
Indicates a value whether the field must to have unique value.
.PARAMETER DisplayFormat
Indicates the display format.
- DateOnly
- DateTime
.PARAMETER FriendlyDisplayFormat
Indicates the friendly display format.
- Unspecified
- Disabled
- Relative
.PARAMETER DefaultValue
Indicates the default value.
.PARAMETER AddToDefaultView
If true, the field is add to default view.
.PARAMETER Retrievals
Indicates the data retrieval expression.
#>
[CmdletBinding()]
param (
[Parameter(Mandatory = $false)]
[Microsoft.SharePoint.Client.ClientContext]
$ClientContext = $SPClient.ClientContext,
[Parameter(Mandatory = $false, ValueFromPipeline = $true)]
[Microsoft.SharePoint.Client.List]
$ParentList,
[string]
$Name,
[Parameter(Mandatory = $false)]
[string]
$Title = $Name,
[Parameter(Mandatory = $false)]
[guid]
$Identity,
[Parameter(Mandatory = $false)]
[string]
$Description,
[Parameter(Mandatory = $false)]
[bool]
$Required,
[Parameter(Mandatory = $false)]
[bool]
$EnforceUniqueValues,
[Parameter(Mandatory = $false)]
[ValidateSet('DateOnly', 'DateTime')]
[string]
$DisplayFormat,
[Parameter(Mandatory = $false)]
[ValidateSet('Unspecified', 'Disabled', 'Relative')]
[string]
$FriendlyDisplayFormat,
[Parameter(Mandatory = $false)]
[string]
$DefaultValue,
[Parameter(Mandatory = $false)]
[bool]
$AddToDefaultView,
[Parameter(Mandatory = $false)]
[string]
$Retrievals
)
process {
if ($ClientContext -eq $null) {
throw "Cannot bind argument to parameter 'ClientContext' because it is null."
}
$XmlDocument = New-Object System.Xml.XmlDocument
$FieldElement = $XmlDocument.AppendChild($XmlDocument.CreateElement('Field'))
$FieldElement.SetAttribute('Type', 'DateTime')
$FieldElement.SetAttribute('Name', $Name)
$FieldElement.SetAttribute('DisplayName', $Title)
if ($MyInvocation.BoundParameters.ContainsKey('Identity')) {
$FieldElement.SetAttribute('ID', $Identity)
}
if ($MyInvocation.BoundParameters.ContainsKey('Description')) {
$FieldElement.SetAttribute('Description', $Description)
}
if ($MyInvocation.BoundParameters.ContainsKey('Required')) {
$FieldElement.SetAttribute('Required', $Required.ToString().ToUpper())
}
if ($MyInvocation.BoundParameters.ContainsKey('EnforceUniqueValues')) {
$FieldElement.SetAttribute('EnforceUniqueValues', $EnforceUniqueValues.ToString().ToUpper())
$FieldElement.SetAttribute('Indexed', $EnforceUniqueValues.ToString().ToUpper())
}
if ($MyInvocation.BoundParameters.ContainsKey('DisplayFormat')) {
$FieldElement.SetAttribute('Format', $DisplayFormat)
}
if ($MyInvocation.BoundParameters.ContainsKey('FriendlyDisplayFormat')) {
$FieldElement.SetAttribute('FriendlyDisplayFormat', $FriendlyDisplayFormat)
}
if ($MyInvocation.BoundParameters.ContainsKey('DefaultValue')) {
$DefaultElement = $XmlDocument.CreateElement('Default')
$DefaultElement.InnerText = $DefaultValue
$FieldElement.AppendChild($DefaultElement) | Out-Null
}
$AddFieldOptions = [Microsoft.SharePoint.Client.AddFieldOptions]::AddFieldInternalNameHint
$ClientObject = $ParentList.Fields.AddFieldAsXml($XmlDocument.InnerXml, $AddToDefaultView, $AddFieldOptions)
Invoke-SPClientLoadQuery `
-ClientContext $ClientContext `
-ClientObject $ClientObject `
-Retrievals $Retrievals
$ClientObject = Convert-SPClientField `
-ClientContext $ClientContext `
-ClientObject $ClientObject
Write-Output $ClientObject
}
}
|
PowerShellCorpus/PowerShellGallery/SPClient/0.9/functions/SPClientField/Remove-SPClientField.ps1
|
Remove-SPClientField.ps1
|
#Requires -Version 3.0
# Remove-SPClientField.ps1
#
# Copyright (c) 2017 karamem0
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
function Remove-SPClientField {
<#
.SYNOPSIS
Deletes a field.
.PARAMETER ClientContext
Indicates the client context.
If not specified, uses default context.
.PARAMETER ClientObject
Indicates the field to delete.
.PARAMETER ParentList
Indicates the list which the field is contained.
.PARAMETER Identity
Indicates the field GUID.
.PARAMETER Name
Indicates the field title or internal name.
#>
[CmdletBinding(DefaultParameterSetName = 'ClientObject')]
param (
[Parameter(Mandatory = $false)]
[Microsoft.SharePoint.Client.ClientContext]
$ClientContext = $SPClient.ClientContext,
[Parameter(Mandatory = $true, ValueFromPipeline = $true, ParameterSetName = 'ClientObject')]
[Microsoft.SharePoint.Client.Field]
$ClientObject,
[Parameter(Mandatory = $true, ValueFromPipeline = $true, ParameterSetName = 'Identity')]
[Parameter(Mandatory = $true, ValueFromPipeline = $true, ParameterSetName = 'Name')]
[Microsoft.SharePoint.Client.List]
$ParentList,
[Parameter(Mandatory = $true, ParameterSetName = 'Identity')]
[Alias('Id')]
[guid]
$Identity,
[Parameter(Mandatory = $true, ParameterSetName = 'Name')]
[Alias('Title')]
[string]
$Name
)
process {
if ($ClientContext -eq $null) {
throw "Cannot bind argument to parameter 'ClientContext' because it is null."
}
if ($PSCmdlet.ParameterSetName -eq 'ClientObject') {
if (-not $ClientObject.IsPropertyAvailable('Id')) {
Invoke-SPClientLoadQuery `
-ClientContext $ClientContext `
-ClientObject $ClientObject `
-Retrievals 'Id,SchemaXml'
}
} else {
$ClientObjectCollection = $ParentList.Fields
if ($PSCmdlet.ParameterSetName -eq 'Identity') {
$PathMethod = New-Object Microsoft.SharePoint.Client.ObjectPathMethod( `
$ClientContext, `
$ClientObjectCollection.Path, `
'GetById', `
[object[]]$Identity)
$ClientObject = New-Object Microsoft.SharePoint.Client.Field($ClientContext, $PathMethod)
Invoke-SPClientLoadQuery `
-ClientContext $ClientContext `
-ClientObject $ClientObject `
-Retrievals 'Id,SchemaXml'
trap {
throw 'The specified field could not be found.'
}
}
if ($PSCmdlet.ParameterSetName -eq 'Name') {
$PathMethod = New-Object Microsoft.SharePoint.Client.ObjectPathMethod( `
$ClientContext, `
$ClientObjectCollection.Path, `
'GetByInternalNameOrTitle', `
[object[]]$Name)
$ClientObject = New-Object Microsoft.SharePoint.Client.Field($ClientContext, $PathMethod)
Invoke-SPClientLoadQuery `
-ClientContext $ClientContext `
-ClientObject $ClientObject `
-Retrievals 'Id,SchemaXml'
trap {
throw 'The specified field could not be found.'
}
}
}
$Xml = [xml]$ClientObject.SchemaXml
$Xml.DocumentElement.SetAttribute('Hidden', 'FALSE')
$Xml.DocumentElement.SetAttribute('ReadOnly', 'FALSE')
$ClientObject.SchemaXml = $Xml.InnerXml
$ClientObject.DeleteObject()
$ClientContext.ExecuteQuery()
}
}
|
PowerShellCorpus/PowerShellGallery/SPClient/0.9/functions/SPClientField/New-SPClientFieldUser.ps1
|
New-SPClientFieldUser.ps1
|
#Requires -Version 3.0
# New-SPClientFieldUser.ps1
#
# Copyright (c) 2017 karamem0
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
function New-SPClientFieldUser {
<#
.SYNOPSIS
Creates a new field which user can enter a user lookup value.
.PARAMETER ClientContext
Indicates the client context.
If not specified, uses default context.
.PARAMETER ParentList
Indicates the list which a field to be created.
.PARAMETER Name
Indicates the internal name.
.PARAMETER Title
Indicates the title.
.PARAMETER Identity
Indicates the field GUID.
.PARAMETER Description
Indicates the description.
.PARAMETER Required
Indicates a value whether the field is required.
.PARAMETER EnforceUniqueValues
Indicates a value whether the field must to have unique value.
.PARAMETER AllowMultipleValues
Indicates a value whether the field allows multiple values.
.PARAMETER SelectionMode
Indicates user selection mode.
- PeopleOnly: users and groups
- PeopleAndGroups: users only
.PARAMETER SelectionGroup
Indicates the identifier of the SharePoint group whose members can be selected.
.PARAMETER LookupField
Indicates the field internal name of the user lookup value.
.PARAMETER AddToDefaultView
If true, the field is add to default view.
.PARAMETER Retrievals
Indicates the data retrieval expression.
#>
[CmdletBinding()]
param (
[Parameter(Mandatory = $false)]
[Microsoft.SharePoint.Client.ClientContext]
$ClientContext = $SPClient.ClientContext,
[Parameter(Mandatory = $false, ValueFromPipeline = $true)]
[Microsoft.SharePoint.Client.List]
$ParentList,
[Parameter(Mandatory = $true)]
[string]
$Name,
[Parameter(Mandatory = $false)]
[string]
$Title = $Name,
[Parameter(Mandatory = $false)]
[guid]
$Identity,
[Parameter(Mandatory = $false)]
[string]
$Description,
[Parameter(Mandatory = $false)]
[bool]
$Required,
[Parameter(Mandatory = $false)]
[bool]
$EnforceUniqueValues,
[Parameter(Mandatory = $false)]
[bool]
$AllowMultipleValues,
[Parameter(Mandatory = $false)]
[ValidateSet('PeopleOnly', 'PeopleAndGroups')]
[string]
$SelectionMode,
[Parameter(Mandatory = $false)]
[int]
$SelectionGroup,
[Parameter(Mandatory = $false)]
[string]
$LookupField,
[Parameter(Mandatory = $false)]
[bool]
$AddToDefaultView,
[Parameter(Mandatory = $false)]
[string]
$Retrievals
)
process {
if ($ClientContext -eq $null) {
throw "Cannot bind argument to parameter 'ClientContext' because it is null."
}
$XmlDocument = New-Object System.Xml.XmlDocument
$FieldElement = $XmlDocument.AppendChild($XmlDocument.CreateElement('Field'))
$FieldElement.SetAttribute('Type', 'User')
$FieldElement.SetAttribute('Name', $Name)
$FieldElement.SetAttribute('DisplayName', $Title)
if ($MyInvocation.BoundParameters.ContainsKey('Identity')) {
$FieldElement.SetAttribute('ID', $Identity)
}
if ($MyInvocation.BoundParameters.ContainsKey('Description')) {
$FieldElement.SetAttribute('Description', $Description)
}
if ($MyInvocation.BoundParameters.ContainsKey('Required')) {
$FieldElement.SetAttribute('Required', $Required.ToString().ToUpper())
}
if ($MyInvocation.BoundParameters.ContainsKey('EnforceUniqueValues')) {
$FieldElement.SetAttribute('EnforceUniqueValues', $EnforceUniqueValues.ToString().ToUpper())
$FieldElement.SetAttribute('Indexed', $EnforceUniqueValues.ToString().ToUpper())
}
if ($MyInvocation.BoundParameters.ContainsKey('AllowMultipleValues')) {
if ($AllowMultipleValues -eq $true) {
if ($EnforceUniqueValues -eq $true) {
throw "Cannot be EnforceUniqueValues to true when AllowMultipleValues is true."
}
$FieldElement.SetAttribute('Type', 'UserMulti')
$FieldElement.SetAttribute('Mult', $AllowMultipleValues.ToString().ToUpper())
}
}
if ($MyInvocation.BoundParameters.ContainsKey('SelectionMode')) {
$FieldElement.SetAttribute('UserSelectionMode', $SelectionMode)
}
if ($MyInvocation.BoundParameters.ContainsKey('SelectionGroup')) {
$FieldElement.SetAttribute('UserSelectionScope', $SelectionGroup)
}
if ($MyInvocation.BoundParameters.ContainsKey('LookupField')) {
$FieldElement.SetAttribute('ShowField', $LookupField)
}
$AddFieldOptions = [Microsoft.SharePoint.Client.AddFieldOptions]::AddFieldInternalNameHint
$ClientObject = $ParentList.Fields.AddFieldAsXml($XmlDocument.InnerXml, $AddToDefaultView, $AddFieldOptions)
Invoke-SPClientLoadQuery `
-ClientContext $ClientContext `
-ClientObject $ClientObject `
-Retrievals $Retrievals
$ClientObject = Convert-SPClientField `
-ClientContext $ClientContext `
-ClientObject $ClientObject
Write-Output $ClientObject
}
}
|
PowerShellCorpus/PowerShellGallery/SPClient/0.9/functions/SPClientField/New-SPClientFieldLookup.ps1
|
New-SPClientFieldLookup.ps1
|
#Requires -Version 3.0
# New-SPClientFieldLookup.ps1
#
# Copyright (c) 2017 karamem0
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
function New-SPClientFieldLookup {
<#
.SYNOPSIS
Creates a new field which user can enter a field lookup value.
.PARAMETER ClientContext
Indicates the client context.
If not specified, uses default context.
.PARAMETER ParentList
Indicates the list which a field to be created.
.PARAMETER Name
Indicates the internal name.
.PARAMETER Title
Indicates the title.
.PARAMETER Identity
Indicates the field GUID.
.PARAMETER Description
Indicates the description.
.PARAMETER Required
Indicates a value whether the field is required.
.PARAMETER EnforceUniqueValues
Indicates a value whether the field must to have unique value.
.PARAMETER AllowMultipleValues
Indicates a value whether the field allows multiple values.
.PARAMETER LookupField
Indicates the internal field name of the user lookup value.
.PARAMETER AddToDefaultView
If true, the field is add to default view.
.PARAMETER Retrievals
Indicates the data retrieval expression.
#>
[CmdletBinding()]
param (
[Parameter(Mandatory = $false)]
[Microsoft.SharePoint.Client.ClientContext]
$ClientContext = $SPClient.ClientContext,
[Parameter(Mandatory = $false, ValueFromPipeline = $true)]
[Microsoft.SharePoint.Client.List]
$ParentList,
[Parameter(Mandatory = $true)]
[string]
$Name,
[Parameter(Mandatory = $false)]
[string]
$Title = $Name,
[Parameter(Mandatory = $false)]
[guid]
$Identity,
[Parameter(Mandatory = $false)]
[string]
$Description,
[Parameter(Mandatory = $false)]
[bool]
$Required,
[Parameter(Mandatory = $false)]
[bool]
$EnforceUniqueValues,
[Parameter(Mandatory = $false)]
[bool]
$AllowMultipleValues,
[Parameter(Mandatory = $true)]
[guid]
$LookupList,
[Parameter(Mandatory = $true)]
[string]
$LookupField,
[Parameter(Mandatory = $false)]
[ValidateSet('None', 'Cascade', 'Restrict')]
[string]
$RelationshipDeleteBehavior,
[Parameter(Mandatory = $false)]
[bool]
$AddToDefaultView,
[Parameter(Mandatory = $false)]
[string]
$Retrievals
)
process {
if ($ClientContext -eq $null) {
throw "Cannot bind argument to parameter 'ClientContext' because it is null."
}
$XmlDocument = New-Object System.Xml.XmlDocument
$FieldElement = $XmlDocument.AppendChild($XmlDocument.CreateElement('Field'))
$FieldElement.SetAttribute('Type', 'Lookup')
$FieldElement.SetAttribute('Name', $Name)
$FieldElement.SetAttribute('DisplayName', $Title)
if ($MyInvocation.BoundParameters.ContainsKey('Identity')) {
$FieldElement.SetAttribute('ID', $Identity)
}
if ($MyInvocation.BoundParameters.ContainsKey('Description')) {
$FieldElement.SetAttribute('Description', $Description)
}
if ($MyInvocation.BoundParameters.ContainsKey('Required')) {
$FieldElement.SetAttribute('Required', $Required.ToString().ToUpper())
}
if ($MyInvocation.BoundParameters.ContainsKey('EnforceUniqueValues')) {
$FieldElement.SetAttribute('EnforceUniqueValues', $EnforceUniqueValues.ToString().ToUpper())
$FieldElement.SetAttribute('Indexed', $EnforceUniqueValues.ToString().ToUpper())
}
if ($MyInvocation.BoundParameters.ContainsKey('AllowMultipleValues')) {
if ($AllowMultipleValues -eq $true) {
if ($EnforceUniqueValues -eq $true) {
throw "Cannot be EnforceUniqueValues to true when AllowMultipleValues is true."
}
$FieldElement.SetAttribute('Type', 'LookupMulti')
$FieldElement.SetAttribute('Mult', $AllowMultipleValues.ToString().ToUpper())
}
}
if ($MyInvocation.BoundParameters.ContainsKey('LookupList')) {
$FieldElement.SetAttribute('List', $LookupList.ToString('B'))
}
if ($MyInvocation.BoundParameters.ContainsKey('LookupField')) {
$FieldElement.SetAttribute('ShowField', $LookupField)
}
if ($MyInvocation.BoundParameters.ContainsKey('RelationshipDeleteBehavior')) {
$FieldElement.SetAttribute('RelationshipDeleteBehavior', $RelationshipDeleteBehavior)
}
$AddFieldOptions = [Microsoft.SharePoint.Client.AddFieldOptions]::AddFieldInternalNameHint
$ClientObject = $ParentList.Fields.AddFieldAsXml($XmlDocument.InnerXml, $AddToDefaultView, $AddFieldOptions)
Invoke-SPClientLoadQuery `
-ClientContext $ClientContext `
-ClientObject $ClientObject `
-Retrievals $Retrievals
$ClientObject = Convert-SPClientField `
-ClientContext $ClientContext `
-ClientObject $ClientObject
Write-Output $ClientObject
}
}
|
PowerShellCorpus/PowerShellGallery/SPClient/0.9/functions/SPClientField/Get-SPClientField.ps1
|
Get-SPClientField.ps1
|
#Requires -Version 3.0
# Get-SPClientField.ps1
#
# Copyright (c) 2017 karamem0
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
function Get-SPClientField {
<#
.SYNOPSIS
Lists all fields or retrieve the specified field.
.DESCRIPTION
If not specified filterable parameter, returns all fields of the list.
Otherwise, returns a field which matches the parameter.
.PARAMETER ClientContext
Indicates the client context.
If not specified, uses default context.
.PARAMETER ParentList
Indicates the list which the fields are contained.
.PARAMETER Identity
Indicates the field GUID.
.PARAMETER Name
Indicates the field title or internal name.
.PARAMETER Retrievals
Indicates the data retrieval expression.
#>
[CmdletBinding(DefaultParameterSetName = 'All')]
param (
[Parameter(Mandatory = $false, ParameterSetName = 'All')]
[Parameter(Mandatory = $false, ParameterSetName = 'Identity')]
[Parameter(Mandatory = $false, ParameterSetName = 'Name')]
[Microsoft.SharePoint.Client.ClientContext]
$ClientContext = $SPClient.ClientContext,
[Parameter(Mandatory = $true, ValueFromPipeline = $true)]
[Microsoft.SharePoint.Client.List]
$ParentList,
[Parameter(Mandatory = $true, ParameterSetName = 'Identity')]
[Alias('Id')]
[guid]
$Identity,
[Parameter(Mandatory = $true, ParameterSetName = 'Name')]
[Alias('Title')]
[string]
$Name,
[Parameter(Mandatory = $false)]
[string]
$Retrievals
)
process {
if ($ClientContext -eq $null) {
throw "Cannot bind argument to parameter 'ClientContext' because it is null."
}
$ClientObjectCollection = $ParentList.Fields
if ($PSCmdlet.ParameterSetName -eq 'All') {
Invoke-SPClientLoadQuery `
-ClientContext $ClientContext `
-ClientObject $ClientObjectCollection `
-Retrievals $Retrievals
Write-Output @(, $ClientObjectCollection)
}
if ($PSCmdlet.ParameterSetName -eq 'Identity') {
$PathMethod = New-Object Microsoft.SharePoint.Client.ObjectPathMethod( `
$ClientContext, `
$ClientObjectCollection.Path, `
'GetById', `
[object[]]$Identity)
$ClientObject = New-Object Microsoft.SharePoint.Client.Field($ClientContext, $PathMethod)
Invoke-SPClientLoadQuery `
-ClientContext $ClientContext `
-ClientObject $ClientObject `
-Retrievals $Retrievals
Write-Output $ClientObject
trap {
throw 'The specified field could not be found.'
}
}
if ($PSCmdlet.ParameterSetName -eq 'Name') {
$PathMethod = New-Object Microsoft.SharePoint.Client.ObjectPathMethod( `
$ClientContext, `
$ClientObjectCollection.Path, `
'GetByInternalNameOrTitle', `
[object[]]$Name)
$ClientObject = New-Object Microsoft.SharePoint.Client.Field($ClientContext, $PathMethod)
Invoke-SPClientLoadQuery `
-ClientContext $ClientContext `
-ClientObject $ClientObject `
-Retrievals $Retrievals
Write-Output $ClientObject
trap {
throw 'The specified field could not be found.'
}
}
}
}
|
PowerShellCorpus/PowerShellGallery/SPClient/0.9/functions/SPClientField/New-SPClientFieldCurrency.ps1
|
New-SPClientFieldCurrency.ps1
|
#Requires -Version 3.0
# New-SPClientFieldCurrency.ps1
#
# Copyright (c) 2017 karamem0
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
function New-SPClientFieldCurrency {
<#
.SYNOPSIS
Creates a new field which user can enter a currency value.
.PARAMETER ClientContext
Indicates the client context.
If not specified, uses default context.
.PARAMETER ParentList
Indicates the list which a field to be created.
.PARAMETER Name
Indicates the internal name.
.PARAMETER Title
Indicates the title.
.PARAMETER Identity
Indicates the field GUID.
.PARAMETER Description
Indicates the description.
.PARAMETER Required
Indicates a value whether the field is required.
.PARAMETER EnforceUniqueValues
Indicates a value whether the field must to have unique value.
.PARAMETER MinimumValue
Indicates the minimum value.
.PARAMETER MaximumValue
Indicates the maximum value.
.PARAMETER Decimals
Indicates the number of decimals.
.PARAMETER LocaleId
Indicates the language code identifier (LCID).
.PARAMETER DefaultValue
Indicates the default value.
.PARAMETER AddToDefaultView
If true, the field is add to default view.
.PARAMETER Retrievals
Indicates the data retrieval expression.
#>
[CmdletBinding()]
param (
[Parameter(Mandatory = $false)]
[Microsoft.SharePoint.Client.ClientContext]
$ClientContext = $SPClient.ClientContext,
[Parameter(Mandatory = $false, ValueFromPipeline = $true)]
[Microsoft.SharePoint.Client.List]
$ParentList,
[Parameter(Mandatory = $true)]
[string]
$Name,
[Parameter(Mandatory = $false)]
[string]
$Title = $Name,
[Parameter(Mandatory = $false)]
[guid]
$Identity,
[Parameter(Mandatory = $false)]
[string]
$Description,
[Parameter(Mandatory = $false)]
[bool]
$Required,
[Parameter(Mandatory = $false)]
[bool]
$EnforceUniqueValues,
[Parameter(Mandatory = $false)]
[double]
$MinimumValue,
[Parameter(Mandatory = $false)]
[double]
$MaximumValue,
[Parameter(Mandatory = $false)]
[int]
$Decimals,
[Parameter(Mandatory = $false)]
[int]
$LocaleId,
[Parameter(Mandatory = $false)]
[double]
$DefaultValue,
[Parameter(Mandatory = $false)]
[bool]
$AddToDefaultView,
[Parameter(Mandatory = $false)]
[string]
$Retrievals
)
process {
if ($ClientContext -eq $null) {
throw "Cannot bind argument to parameter 'ClientContext' because it is null."
}
$XmlDocument = New-Object System.Xml.XmlDocument
$FieldElement = $XmlDocument.AppendChild($XmlDocument.CreateElement('Field'))
$FieldElement.SetAttribute('Type', 'Currency')
$FieldElement.SetAttribute('Name', $Name)
$FieldElement.SetAttribute('DisplayName', $Title)
if ($MyInvocation.BoundParameters.ContainsKey('Identity')) {
$FieldElement.SetAttribute('ID', $Identity)
}
if ($MyInvocation.BoundParameters.ContainsKey('Description')) {
$FieldElement.SetAttribute('Description', $Description)
}
if ($MyInvocation.BoundParameters.ContainsKey('Required')) {
$FieldElement.SetAttribute('Required', $Required.ToString().ToUpper())
}
if ($MyInvocation.BoundParameters.ContainsKey('EnforceUniqueValues')) {
$FieldElement.SetAttribute('EnforceUniqueValues', $EnforceUniqueValues.ToString().ToUpper())
$FieldElement.SetAttribute('Indexed', $EnforceUniqueValues.ToString().ToUpper())
}
if ($MyInvocation.BoundParameters.ContainsKey('MinimumValue')) {
$FieldElement.SetAttribute('Min', $MinimumValue)
}
if ($MyInvocation.BoundParameters.ContainsKey('MaximumValue')) {
$FieldElement.SetAttribute('Max', $MaximumValue)
}
if ($MyInvocation.BoundParameters.ContainsKey('Decimals')) {
$FieldElement.SetAttribute('Decimals', $Decimals)
}
if ($MyInvocation.BoundParameters.ContainsKey('LocaleId')) {
$FieldElement.SetAttribute('LCID', $LocaleId)
}
if ($MyInvocation.BoundParameters.ContainsKey('DefaultValue')) {
$DefaultElement = $XmlDocument.CreateElement('Default')
$DefaultElement.InnerText = $DefaultValue
$FieldElement.AppendChild($DefaultElement) | Out-Null
}
$AddFieldOptions = [Microsoft.SharePoint.Client.AddFieldOptions]::AddFieldInternalNameHint
$ClientObject = $ParentList.Fields.AddFieldAsXml($XmlDocument.InnerXml, $AddToDefaultView, $AddFieldOptions)
Invoke-SPClientLoadQuery `
-ClientContext $ClientContext `
-ClientObject $ClientObject `
-Retrievals $Retrievals
$ClientObject = Convert-SPClientField `
-ClientContext $ClientContext `
-ClientObject $ClientObject
Write-Output $ClientObject
}
}
|
PowerShellCorpus/PowerShellGallery/SPClient/0.9/functions/SPClientField/Convert-SPClientField.ps1
|
Convert-SPClientField.ps1
|
#Requires -Version 3.0
# Convert-SPClientField.ps1
#
# Copyright (c) 2017 karamem0
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
function Convert-SPClientField {
<#
.SYNOPSIS
Casts a specified field to its derived type.
.PARAMETER ClientContext
Indicates the client context.
If not specified, uses default context.
.PARAMETER ClientObject
Indicates the field.
#>
[CmdletBinding()]
param (
[Parameter(Mandatory = $false)]
[Microsoft.SharePoint.Client.ClientContext]
$ClientContext = $SPClient.ClientContext,
[Parameter(Mandatory = $false, ValueFromPipeline = $true)]
[Microsoft.SharePoint.Client.Field]
$ClientObject
)
process {
if ($ClientContext -eq $null) {
throw "Cannot bind argument to parameter 'ClientContext' because it is null."
}
$Table = @{
Text = 'Microsoft.SharePoint.Client.FieldText'
Note = 'Microsoft.SharePoint.Client.FieldMultilineText'
Choice = 'Microsoft.SharePoint.Client.FieldChoice'
MultiChoice = 'Microsoft.SharePoint.Client.FieldMultiChoice'
Number = 'Microsoft.SharePoint.Client.FieldNumber'
Currency = 'Microsoft.SharePoint.Client.FieldCurrency'
DateTime = 'Microsoft.SharePoint.Client.FieldDateTime'
Lookup = 'Microsoft.SharePoint.Client.FieldLookup'
LookupMulti = 'Microsoft.SharePoint.Client.FieldLookup'
Boolean = 'Microsoft.SharePoint.Client.FieldNumber'
User = 'Microsoft.SharePoint.Client.FieldUser'
UserMulti = 'Microsoft.SharePoint.Client.FieldUser'
Url = 'Microsoft.SharePoint.Client.FieldUrl'
Calculated = 'Microsoft.SharePoint.Client.FieldCalculated'
}
if (-not $ClientObject.IsPropertyAvailable('TypeAsString')) {
Invoke-SPClientLoadQuery `
-ClientContext $ClientContext `
-ClientObject $ClientObject `
-Retrievals 'Id,TypeAsString'
}
$Method = $ClientContext.GetType().GetMethod('CastTo')
$Method = $Method.MakeGenericMethod([type[]]$Table[$ClientObject.TypeAsString])
Write-Output $Method.Invoke($ClientContext, @($ClientObject))
}
}
|
PowerShellCorpus/PowerShellGallery/SPClient/0.9/functions/SPClientField/New-SPClientFieldNumber.ps1
|
New-SPClientFieldNumber.ps1
|
#Requires -Version 3.0
# New-SPClientFieldNumber.ps1
#
# Copyright (c) 2017 karamem0
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
function New-SPClientFieldNumber {
<#
.SYNOPSIS
Creates a new field which user can enter a floating point number.
.PARAMETER ClientContext
Indicates the client context.
If not specified, uses default context.
.PARAMETER ParentList
Indicates the list which a field to be created.
.PARAMETER Name
Indicates the internal name.
.PARAMETER Title
Indicates the title.
.PARAMETER Identity
Indicates the field GUID.
.PARAMETER Description
Indicates the description.
.PARAMETER Required
Indicates a value whether the field is required.
.PARAMETER EnforceUniqueValues
Indicates a value whether the field must to have unique value.
.PARAMETER MinimumValue
Indicates the minimum value.
.PARAMETER MaximumValue
Indicates the maximum value.
.PARAMETER Decimals
Indicates the number of decimals.
.PARAMETER Percentage
Indicates a value whether the field shows as percentage.
.PARAMETER DefaultValue
Indicates the default value.
.PARAMETER AddToDefaultView
If true, the field is add to default view.
.PARAMETER Retrievals
Indicates the data retrieval expression.
#>
[CmdletBinding()]
param (
[Parameter(Mandatory = $false)]
[Microsoft.SharePoint.Client.ClientContext]
$ClientContext = $SPClient.ClientContext,
[Parameter(Mandatory = $false, ValueFromPipeline = $true)]
[Microsoft.SharePoint.Client.List]
$ParentList,
[Parameter(Mandatory = $true)]
[string]
$Name,
[Parameter(Mandatory = $false)]
[string]
$Title = $Name,
[Parameter(Mandatory = $false)]
[guid]
$Identity,
[Parameter(Mandatory = $false)]
[string]
$Description,
[Parameter(Mandatory = $false)]
[bool]
$Required,
[Parameter(Mandatory = $false)]
[bool]
$EnforceUniqueValues,
[Parameter(Mandatory = $false)]
[double]
$MinimumValue,
[Parameter(Mandatory = $false)]
[double]
$MaximumValue,
[Parameter(Mandatory = $false)]
[int]
$Decimals,
[Parameter(Mandatory = $false)]
[bool]
$Percentage,
[Parameter(Mandatory = $false)]
[double]
$DefaultValue,
[Parameter(Mandatory = $false)]
[bool]
$AddToDefaultView,
[Parameter(Mandatory = $false)]
[string]
$Retrievals
)
process {
if ($ClientContext -eq $null) {
throw "Cannot bind argument to parameter 'ClientContext' because it is null."
}
$XmlDocument = New-Object System.Xml.XmlDocument
$FieldElement = $XmlDocument.AppendChild($XmlDocument.CreateElement('Field'))
$FieldElement.SetAttribute('Type', 'Number')
$FieldElement.SetAttribute('Name', $Name)
$FieldElement.SetAttribute('DisplayName', $Title)
if ($MyInvocation.BoundParameters.ContainsKey('Identity')) {
$FieldElement.SetAttribute('ID', $Identity)
}
if ($MyInvocation.BoundParameters.ContainsKey('Description')) {
$FieldElement.SetAttribute('Description', $Description)
}
if ($MyInvocation.BoundParameters.ContainsKey('Required')) {
$FieldElement.SetAttribute('Required', $Required.ToString().ToUpper())
}
if ($MyInvocation.BoundParameters.ContainsKey('EnforceUniqueValues')) {
$FieldElement.SetAttribute('EnforceUniqueValues', $EnforceUniqueValues.ToString().ToUpper())
$FieldElement.SetAttribute('Indexed', $EnforceUniqueValues.ToString().ToUpper())
}
if ($MyInvocation.BoundParameters.ContainsKey('MinimumValue')) {
$FieldElement.SetAttribute('Min', $MinimumValue)
}
if ($MyInvocation.BoundParameters.ContainsKey('MaximumValue')) {
$FieldElement.SetAttribute('Max', $MaximumValue)
}
if ($MyInvocation.BoundParameters.ContainsKey('Decimals')) {
$FieldElement.SetAttribute('Decimals', $Decimals)
}
if ($MyInvocation.BoundParameters.ContainsKey('Percentage')) {
$FieldElement.SetAttribute('Percentage', $Percentage.ToString().ToUpper())
}
if ($MyInvocation.BoundParameters.ContainsKey('DefaultValue')) {
$DefaultElement = $XmlDocument.CreateElement('Default')
$DefaultElement.InnerText = $DefaultValue
$FieldElement.AppendChild($DefaultElement) | Out-Null
}
$AddFieldOptions = [Microsoft.SharePoint.Client.AddFieldOptions]::AddFieldInternalNameHint
$ClientObject = $ParentList.Fields.AddFieldAsXml($XmlDocument.InnerXml, $AddToDefaultView, $AddFieldOptions)
Invoke-SPClientLoadQuery `
-ClientContext $ClientContext `
-ClientObject $ClientObject `
-Retrievals $Retrievals
$ClientObject = Convert-SPClientField `
-ClientContext $ClientContext `
-ClientObject $ClientObject
Write-Output $ClientObject
}
}
|
PowerShellCorpus/PowerShellGallery/SPClient/0.9/functions/SPClientField/New-SPClientFieldChoice.ps1
|
New-SPClientFieldChoice.ps1
|
#Requires -Version 3.0
# New-SPClientFieldChoice.ps1
#
# Copyright (c) 2017 karamem0
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
function New-SPClientFieldChoice {
<#
.SYNOPSIS
Creates a new field which user can select a value.
.PARAMETER ClientContext
Indicates the client context.
If not specified, uses default context.
.PARAMETER ParentList
Indicates the list which a field to be created.
.PARAMETER Name
Indicates the internal name.
.PARAMETER Title
Indicates the title.
.PARAMETER Identity
Indicates the field GUID.
.PARAMETER Description
Indicates the description.
.PARAMETER Required
Indicates a value whether the field is required.
.PARAMETER EnforceUniqueValues
Indicates a value whether the field must to have unique value.
.PARAMETER Choices
Indicates values that are available for selection in the field.
.PARAMETER EditFormat
Indicates the display format.
- Dropdown
- RadioButtons
- Checkboxes
.PARAMETER FillInChoice
Indicates a value whether the field can accept values other than those specified in Choices.
.PARAMETER DefaultValue
Indicates the default value.
.PARAMETER AddToDefaultView
If true, the field is add to default view.
.PARAMETER Retrievals
Indicates the data retrieval expression.
#>
[CmdletBinding()]
param (
[Parameter(Mandatory = $false)]
[Microsoft.SharePoint.Client.ClientContext]
$ClientContext = $SPClient.ClientContext,
[Parameter(Mandatory = $false, ValueFromPipeline = $true)]
[Microsoft.SharePoint.Client.List]
$ParentList,
[Parameter(Mandatory = $true)]
[string]
$Name,
[Parameter(Mandatory = $false)]
[string]
$Title = $Name,
[Parameter(Mandatory = $false)]
[guid]
$Identity,
[Parameter(Mandatory = $false)]
[string]
$Description,
[Parameter(Mandatory = $false)]
[bool]
$Required,
[Parameter(Mandatory = $false)]
[bool]
$EnforceUniqueValues,
[Parameter(Mandatory = $false)]
[string[]]
$Choices,
[Parameter(Mandatory = $false)]
[ValidateSet('Dropdown', 'RadioButtons', 'Checkboxes')]
[string]
$EditFormat,
[Parameter(Mandatory = $false)]
[bool]
$FillInChoice,
[Parameter(Mandatory = $false)]
[string]
$DefaultValue,
[Parameter(Mandatory = $false)]
[bool]
$AddToDefaultView,
[Parameter(Mandatory = $false)]
[string]
$Retrievals
)
process {
if ($ClientContext -eq $null) {
throw "Cannot bind argument to parameter 'ClientContext' because it is null."
}
$XmlDocument = New-Object System.Xml.XmlDocument
$FieldElement = $XmlDocument.AppendChild($XmlDocument.CreateElement('Field'))
$FieldElement.SetAttribute('Type', 'Choice')
$FieldElement.SetAttribute('Name', $Name)
$FieldElement.SetAttribute('DisplayName', $Title)
if ($MyInvocation.BoundParameters.ContainsKey('Identity')) {
$FieldElement.SetAttribute('ID', $Identity)
}
if ($MyInvocation.BoundParameters.ContainsKey('Description')) {
$FieldElement.SetAttribute('Description', $Description)
}
if ($MyInvocation.BoundParameters.ContainsKey('Required')) {
$FieldElement.SetAttribute('Required', $Required.ToString().ToUpper())
}
if ($MyInvocation.BoundParameters.ContainsKey('EnforceUniqueValues')) {
$FieldElement.SetAttribute('EnforceUniqueValues', $EnforceUniqueValues.ToString().ToUpper())
$FieldElement.SetAttribute('Indexed', $EnforceUniqueValues.ToString().ToUpper())
}
if ($MyInvocation.BoundParameters.ContainsKey('Choices')) {
$ChoicesElement = $XmlDocument.CreateElement('CHOICES')
$Choices | ForEach-Object {
$ChoiceElement = $XmlDocument.CreateElement('CHOICE')
$ChoiceElement.InnerText = $_
$ChoicesElement.AppendChild($ChoiceElement) | Out-Null
}
$FieldElement.AppendChild($ChoicesElement) | Out-Null
}
if ($MyInvocation.BoundParameters.ContainsKey('EditFormat')) {
if ($EditFormat -eq 'Checkboxes') {
if ($EnforceUniqueValues -eq $true) {
throw "Cannot be EnforceUniqueValues to true when EditFormat is 'Checkboxes'."
}
$FieldElement.SetAttribute('Type', 'MultiChoice')
}
$FieldElement.SetAttribute('Format', $EditFormat)
}
if ($MyInvocation.BoundParameters.ContainsKey('FillInChoice')) {
$FieldElement.SetAttribute('FillInChoice', $FillInChoice.ToString().ToUpper())
}
if ($MyInvocation.BoundParameters.ContainsKey('DefaultValue')) {
$DefaultElement = $XmlDocument.CreateElement('Default')
$DefaultElement.InnerText = $DefaultValue
$FieldElement.AppendChild($DefaultElement) | Out-Null
}
$AddFieldOptions = [Microsoft.SharePoint.Client.AddFieldOptions]::AddFieldInternalNameHint
$ClientObject = $ParentList.Fields.AddFieldAsXml($XmlDocument.InnerXml, $AddToDefaultView, $AddFieldOptions)
Invoke-SPClientLoadQuery `
-ClientContext $ClientContext `
-ClientObject $ClientObject `
-Retrievals $Retrievals
$ClientObject = Convert-SPClientField `
-ClientContext $ClientContext `
-ClientObject $ClientObject
Write-Output $ClientObject
}
}
|
PowerShellCorpus/PowerShellGallery/SPClient/0.9/functions/SPClientField/New-SPClientFieldMultiLineText.ps1
|
New-SPClientFieldMultiLineText.ps1
|
#Requires -Version 3.0
# New-SPClientFieldMultiLineText.ps1
#
# Copyright (c) 2017 karamem0
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
function New-SPClientFieldMultiLineText {
<#
.SYNOPSIS
Creates a new field which user can enter multiple lines of text.
.PARAMETER ClientContext
Indicates the client context.
If not specified, uses default context.
.PARAMETER ParentList
Indicates the list which a field to be created.
.PARAMETER Name
Indicates the internal name.
.PARAMETER Title
Indicates the title.
.PARAMETER Identity
Indicates the field GUID.
.PARAMETER Description
Indicates the description.
.PARAMETER Required
Indicates a value whether the field is required.
.PARAMETER NumberOfLines
Indicates the maximum number of lines.
.PARAMETER RichText
Indicates a value whether the field supports rich formatting.
.PARAMETER DefaultValue
Indicates the default value.
.PARAMETER AddToDefaultView
If true, the field is add to default view.
.PARAMETER Retrievals
Indicates the data retrieval expression.
#>
[CmdletBinding()]
param (
[Parameter(Mandatory = $false)]
[Microsoft.SharePoint.Client.ClientContext]
$ClientContext = $SPClient.ClientContext,
[Parameter(Mandatory = $false, ValueFromPipeline = $true)]
[Microsoft.SharePoint.Client.List]
$ParentList,
[Parameter(Mandatory = $true)]
[string]
$Name,
[Parameter(Mandatory = $false)]
[string]
$Title = $Name,
[Parameter(Mandatory = $false)]
[guid]
$Identity,
[Parameter(Mandatory = $false)]
[string]
$Description,
[Parameter(Mandatory = $false)]
[bool]
$Required,
[Parameter(Mandatory = $false)]
[int]
$NumberOfLines,
[Parameter(Mandatory = $false)]
[bool]
$RichText,
[Parameter(Mandatory = $false)]
[string]
$DefaultValue,
[Parameter(Mandatory = $false)]
[bool]
$AddToDefaultView,
[Parameter(Mandatory = $false)]
[string]
$Retrievals
)
process {
if ($ClientContext -eq $null) {
throw "Cannot bind argument to parameter 'ClientContext' because it is null."
}
$XmlDocument = New-Object System.Xml.XmlDocument
$FieldElement = $XmlDocument.AppendChild($XmlDocument.CreateElement('Field'))
$FieldElement.SetAttribute('Type', 'Note')
$FieldElement.SetAttribute('Name', $Name)
$FieldElement.SetAttribute('DisplayName', $Title)
if ($MyInvocation.BoundParameters.ContainsKey('Identity')) {
$FieldElement.SetAttribute('ID', $Identity)
}
if ($MyInvocation.BoundParameters.ContainsKey('Description')) {
$FieldElement.SetAttribute('Description', $Description)
}
if ($MyInvocation.BoundParameters.ContainsKey('Required')) {
$FieldElement.SetAttribute('Required', $Required.ToString().ToUpper())
}
if ($MyInvocation.BoundParameters.ContainsKey('NumberOfLines')) {
$FieldElement.SetAttribute('NumLines', $NumberOfLines)
}
if ($MyInvocation.BoundParameters.ContainsKey('RichText')) {
$FieldElement.SetAttribute('RichText', $RichText.ToString().ToUpper())
$FieldElement.SetAttribute('RichTextMode', 'FullHtml')
}
if ($MyInvocation.BoundParameters.ContainsKey('DefaultValue')) {
$DefaultElement = $XmlDocument.CreateElement('Default')
$DefaultElement.InnerText = $DefaultValue
$FieldElement.AppendChild($DefaultElement) | Out-Null
}
$AddFieldOptions = [Microsoft.SharePoint.Client.AddFieldOptions]::AddFieldInternalNameHint
$ClientObject = $ParentList.Fields.AddFieldAsXml($XmlDocument.InnerXml, $AddToDefaultView, $AddFieldOptions)
Invoke-SPClientLoadQuery `
-ClientContext $ClientContext `
-ClientObject $ClientObject `
-Retrievals $Retrievals
$ClientObject = Convert-SPClientField `
-ClientContext $ClientContext `
-ClientObject $ClientObject
Write-Output $ClientObject
}
}
|
PowerShellCorpus/PowerShellGallery/SPClient/0.9/functions/SPClientField/New-SPClientFieldUrl.ps1
|
New-SPClientFieldUrl.ps1
|
#Requires -Version 3.0
# New-SPClientFieldUrl.ps1
#
# Copyright (c) 2017 karamem0
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
function New-SPClientFieldUrl {
<#
.SYNOPSIS
Creates a new field which user can enter a url.
.PARAMETER ClientContext
Indicates the client context.
If not specified, uses default context.
.PARAMETER ParentList
Indicates the list which a field to be created.
.PARAMETER Name
Indicates the internal name.
.PARAMETER Title
Indicates the title.
.PARAMETER Identity
Indicates the field GUID.
.PARAMETER Description
Indicates the description.
.PARAMETER Required
Indicates a value whether the field is required.
.PARAMETER DisplayFormat
Indicates the display format.
- Hyperlink
- Image
.PARAMETER AddToDefaultView
If true, the field is add to default view.
.PARAMETER Retrievals
Indicates the data retrieval expression.
#>
[CmdletBinding()]
param (
[Parameter(Mandatory = $false)]
[Microsoft.SharePoint.Client.ClientContext]
$ClientContext = $SPClient.ClientContext,
[Parameter(Mandatory = $false, ValueFromPipeline = $true)]
[Microsoft.SharePoint.Client.List]
$ParentList,
[Parameter(Mandatory = $true)]
[string]
$Name,
[Parameter(Mandatory = $false)]
[string]
$Title = $Name,
[Parameter(Mandatory = $false)]
[guid]
$Identity,
[Parameter(Mandatory = $false)]
[string]
$Description,
[Parameter(Mandatory = $false)]
[bool]
$Required,
[Parameter(Mandatory = $false)]
[ValidateSet('Hyperlink', 'Image')]
[string]
$DisplayFormat,
[Parameter(Mandatory = $false)]
[bool]
$AddToDefaultView,
[Parameter(Mandatory = $false)]
[string]
$Retrievals
)
process {
if ($ClientContext -eq $null) {
throw "Cannot bind argument to parameter 'ClientContext' because it is null."
}
$XmlDocument = New-Object System.Xml.XmlDocument
$FieldElement = $XmlDocument.AppendChild($XmlDocument.CreateElement('Field'))
$FieldElement.SetAttribute('Type', 'URL')
$FieldElement.SetAttribute('Name', $Name)
$FieldElement.SetAttribute('DisplayName', $Title)
if ($MyInvocation.BoundParameters.ContainsKey('Identity')) {
$FieldElement.SetAttribute('ID', $Identity)
}
if ($MyInvocation.BoundParameters.ContainsKey('Description')) {
$FieldElement.SetAttribute('Description', $Description)
}
if ($MyInvocation.BoundParameters.ContainsKey('Required')) {
$FieldElement.SetAttribute('Required', $Required.ToString().ToUpper())
}
if ($MyInvocation.BoundParameters.ContainsKey('DisplayFormat')) {
$FieldElement.SetAttribute('Format', $DisplayFormat)
}
$AddFieldOptions = [Microsoft.SharePoint.Client.AddFieldOptions]::AddFieldInternalNameHint
$ClientObject = $ParentList.Fields.AddFieldAsXml($XmlDocument.InnerXml, $AddToDefaultView, $AddFieldOptions)
Invoke-SPClientLoadQuery `
-ClientContext $ClientContext `
-ClientObject $ClientObject `
-Retrievals $Retrievals
$ClientObject = Convert-SPClientField `
-ClientContext $ClientContext `
-ClientObject $ClientObject
Write-Output $ClientObject
}
}
|
PowerShellCorpus/PowerShellGallery/SPClient/0.9/functions/SPClientField/New-SPClientFieldBoolean.ps1
|
New-SPClientFieldBoolean.ps1
|
#Requires -Version 3.0
# New-SPClientFieldBoolean.ps1
#
# Copyright (c) 2017 karamem0
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
function New-SPClientFieldBoolean {
<#
.SYNOPSIS
Creates a new field which user can enter a true/false value.
.PARAMETER ClientContext
Indicates the client context.
If not specified, uses default context.
.PARAMETER ParentList
Indicates the list which a field to be created.
.PARAMETER Name
Indicates the internal name.
.PARAMETER Title
Indicates the title.
.PARAMETER Identity
Indicates the field GUID.
.PARAMETER Description
Indicates the description.
.PARAMETER Required
Indicates a value whether the field is required.
.PARAMETER DefaultValue
Indicates the default value.
.PARAMETER AddToDefaultView
If true, the field is add to default view.
.PARAMETER Retrievals
Indicates the data retrieval expression.
#>
[CmdletBinding()]
param (
[Parameter(Mandatory = $false)]
[Microsoft.SharePoint.Client.ClientContext]
$ClientContext = $SPClient.ClientContext,
[Parameter(Mandatory = $false, ValueFromPipeline = $true)]
[Microsoft.SharePoint.Client.List]
$ParentList,
[Parameter(Mandatory = $true)]
[string]
$Name,
[Parameter(Mandatory = $false)]
[string]
$Title = $Name,
[Parameter(Mandatory = $false)]
[guid]
$Identity,
[Parameter(Mandatory = $false)]
[string]
$Description,
[Parameter(Mandatory = $false)]
[bool]
$Required,
[Parameter(Mandatory = $false)]
[bool]
$DefaultValue,
[Parameter(Mandatory = $false)]
[bool]
$AddToDefaultView,
[Parameter(Mandatory = $false)]
[string]
$Retrievals
)
process {
if ($ClientContext -eq $null) {
throw "Cannot bind argument to parameter 'ClientContext' because it is null."
}
$XmlDocument = New-Object System.Xml.XmlDocument
$FieldElement = $XmlDocument.AppendChild($XmlDocument.CreateElement('Field'))
$FieldElement.SetAttribute('Type', 'Boolean')
$FieldElement.SetAttribute('Name', $Name)
$FieldElement.SetAttribute('DisplayName', $Title)
if ($MyInvocation.BoundParameters.ContainsKey('Identity')) {
$FieldElement.SetAttribute('ID', $Identity)
}
if ($MyInvocation.BoundParameters.ContainsKey('Description')) {
$FieldElement.SetAttribute('Description', $Description)
}
if ($MyInvocation.BoundParameters.ContainsKey('Required')) {
$FieldElement.SetAttribute('Required', $Required.ToString().ToUpper())
}
if ($MyInvocation.BoundParameters.ContainsKey('DefaultValue')) {
$DefaultElement = $XmlDocument.CreateElement('Default')
$DefaultElement.InnerText = [int]$DefaultValue
$FieldElement.AppendChild($DefaultElement) | Out-Null
}
$AddFieldOptions = [Microsoft.SharePoint.Client.AddFieldOptions]::AddFieldInternalNameHint
$ClientObject = $ParentList.Fields.AddFieldAsXml($XmlDocument.InnerXml, $AddToDefaultView, $AddFieldOptions)
Invoke-SPClientLoadQuery `
-ClientContext $ClientContext `
-ClientObject $ClientObject `
-Retrievals $Retrievals
$ClientObject = Convert-SPClientField `
-ClientContext $ClientContext `
-ClientObject $ClientObject
Write-Output $ClientObject
}
}
|
PowerShellCorpus/PowerShellGallery/SPClient/0.9/functions/SPClientField/New-SPClientFieldText.ps1
|
New-SPClientFieldText.ps1
|
#Requires -Version 3.0
# New-SPClientFieldText.ps1
#
# Copyright (c) 2017 karamem0
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
function New-SPClientFieldText {
<#
.SYNOPSIS
Creates a new field which user can enter a single line of text.
.PARAMETER ClientContext
Indicates the client context.
If not specified, uses default context.
.PARAMETER ParentList
Indicates the list which a field to be created.
.PARAMETER Name
Indicates the internal name.
.PARAMETER Title
Indicates the title.
.PARAMETER Identity
Indicates the field GUID.
.PARAMETER Description
Indicates the description.
.PARAMETER Required
Indicates a value whether the field is required.
.PARAMETER EnforceUniqueValues
Indicates a value whether the field must to have unique value.
.PARAMETER MaxLength
Indicates the maximum number of characters.
.PARAMETER DefaultValue
Indicates the default value.
.PARAMETER AddToDefaultView
If true, the field is add to default view.
.PARAMETER Retrievals
Indicates the data retrieval expression.
#>
[CmdletBinding()]
param (
[Parameter(Mandatory = $false)]
[Microsoft.SharePoint.Client.ClientContext]
$ClientContext = $SPClient.ClientContext,
[Parameter(Mandatory = $false, ValueFromPipeline = $true)]
[Microsoft.SharePoint.Client.List]
$ParentList,
[Parameter(Mandatory = $true)]
[string]
$Name,
[Parameter(Mandatory = $false)]
[string]
$Title = $Name,
[Parameter(Mandatory = $false)]
[guid]
$Identity,
[Parameter(Mandatory = $false)]
[string]
$Description,
[Parameter(Mandatory = $false)]
[bool]
$Required,
[Parameter(Mandatory = $false)]
[bool]
$EnforceUniqueValues,
[Parameter(Mandatory = $false)]
[int]
$MaxLength,
[Parameter(Mandatory = $false)]
[string]
$DefaultValue,
[Parameter(Mandatory = $false)]
[bool]
$AddToDefaultView,
[Parameter(Mandatory = $false)]
[string]
$Retrievals
)
process {
if ($ClientContext -eq $null) {
throw "Cannot bind argument to parameter 'ClientContext' because it is null."
}
$XmlDocument = New-Object System.Xml.XmlDocument
$FieldElement = $XmlDocument.AppendChild($XmlDocument.CreateElement('Field'))
$FieldElement.SetAttribute('Type', 'Text')
$FieldElement.SetAttribute('Name', $Name)
$FieldElement.SetAttribute('DisplayName', $Title)
if ($MyInvocation.BoundParameters.ContainsKey('Identity')) {
$FieldElement.SetAttribute('ID', $Identity)
}
if ($MyInvocation.BoundParameters.ContainsKey('Description')) {
$FieldElement.SetAttribute('Description', $Description)
}
if ($MyInvocation.BoundParameters.ContainsKey('Required')) {
$FieldElement.SetAttribute('Required', $Required.ToString().ToUpper())
}
if ($MyInvocation.BoundParameters.ContainsKey('EnforceUniqueValues')) {
$FieldElement.SetAttribute('EnforceUniqueValues', $EnforceUniqueValues.ToString().ToUpper())
$FieldElement.SetAttribute('Indexed', $EnforceUniqueValues.ToString().ToUpper())
}
if ($MyInvocation.BoundParameters.ContainsKey('MaxLength')) {
$FieldElement.SetAttribute('MaxLength', $MaxLength)
}
if ($MyInvocation.BoundParameters.ContainsKey('DefaultValue')) {
$DefaultElement = $XmlDocument.CreateElement('Default')
$DefaultElement.InnerText = $DefaultValue
$FieldElement.AppendChild($DefaultElement) | Out-Null
}
$AddFieldOptions = [Microsoft.SharePoint.Client.AddFieldOptions]::AddFieldInternalNameHint
$ClientObject = $ParentList.Fields.AddFieldAsXml($XmlDocument.InnerXml, $AddToDefaultView, $AddFieldOptions)
Invoke-SPClientLoadQuery `
-ClientContext $ClientContext `
-ClientObject $ClientObject `
-Retrievals $Retrievals
$ClientObject = Convert-SPClientField `
-ClientContext $ClientContext `
-ClientObject $ClientObject
Write-Output $ClientObject
}
}
|
PowerShellCorpus/PowerShellGallery/SPClient/0.9/functions/SPClientWeb/New-SPClientWeb.ps1
|
New-SPClientWeb.ps1
|
#Requires -Version 3.0
# New-SPClientWeb.ps1
#
# Copyright (c) 2017 karamem0
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
function New-SPClientWeb {
<#
.SYNOPSIS
Creates a new web.
.PARAMETER ClientContext
Indicates the client context.
If not specified, uses default context.
.PARAMETER ParentWeb
Indicates the web which a web to be created.
.PARAMETER Url
Indicates the url.
.PARAMETER Title
Indicates the title.
If not specified, uses default title of the web template.
.PARAMETER Description
Indicates the description.
.PARAMETER Language
Indicates the locale ID in which the language is used.
If not specified, uses the parent web language.
.PARAMETER Template
Indicates the template name.
.PARAMETER UniquePermissions
If specified, the web uses unique permissions.
.PARAMETER Retrievals
Indicates the data retrieval expression.
#>
[CmdletBinding()]
param (
[Parameter(Mandatory = $false)]
[Microsoft.SharePoint.Client.ClientContext]
$ClientContext = $SPClient.ClientContext,
[Parameter(Mandatory = $true, ValueFromPipeline = $true)]
[Microsoft.SharePoint.Client.Web]
$ParentWeb,
[Parameter(Mandatory = $true)]
[string]
$Url,
[Parameter(Mandatory = $false)]
[string]
$Title,
[Parameter(Mandatory = $false)]
[string]
$Description,
[Parameter(Mandatory = $false)]
[string]
$Language,
[Parameter(Mandatory = $false)]
[string]
$Template,
[Parameter(Mandatory = $false)]
[switch]
$UniquePermissions,
[Parameter(Mandatory = $false)]
[string]
$Retrievals
)
process {
if ($ClientContext -eq $null) {
throw "Cannot bind argument to parameter 'ClientContext' because it is null."
}
$Creation = New-Object Microsoft.SharePoint.Client.WebCreationInformation
$Creation.Url = $Url
$Creation.Language = $Language
$Creation.WebTemplate = $Template
$Creation.Title = $Title
$Creation.Description = $Description
$Creation.UseSamePermissionsAsParentSite = -not $UniquePermissions
$ClientObject = $ParentWeb.Webs.Add($Creation)
$ClientObject.Update()
Invoke-SPClientLoadQuery `
-ClientContext $ClientContext `
-ClientObject $ClientObject `
-Retrievals $Retrievals
Write-Output $ClientObject
}
}
|
PowerShellCorpus/PowerShellGallery/SPClient/0.9/functions/SPClientWeb/Get-SPClientWeb.ps1
|
Get-SPClientWeb.ps1
|
#Requires -Version 3.0
# Get-SPClientWeb.ps1
#
# Copyright (c) 2017 karamem0
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
function Get-SPClientWeb {
<#
.SYNOPSIS
Lists all webs or retrieve the specified web.
.DESCRIPTION
If not specified filterable parameter, returns default web and its
descendants. Otherwise, returns a web which matches the parameter.
.PARAMETER ClientContext
Indicates the client context.
If not specified, uses default context.
.PARAMETER Identity
Indicates the web GUID.
.PARAMETER Url
Indicates the web relative url.
.PARAMETER Default
If specified, returns default web of the client context.
.PARAMETER Root
If specified, returns root web.
.PARAMETER Retrievals
Indicates the data retrieval expression.
#>
[CmdletBinding(DefaultParameterSetName = 'All')]
param (
[Parameter(Mandatory = $false, ParameterSetName = 'All')]
[Parameter(Mandatory = $false, ParameterSetName = 'Identity')]
[Parameter(Mandatory = $false, ParameterSetName = 'Url')]
[Parameter(Mandatory = $false, ParameterSetName = 'Default')]
[Parameter(Mandatory = $false, ParameterSetName = 'Root')]
[Microsoft.SharePoint.Client.ClientContext]
$ClientContext = $SPClient.ClientContext,
[Parameter(Mandatory = $true, ParameterSetName = 'Identity')]
[Alias('Id')]
[guid]
$Identity,
[Parameter(Mandatory = $true, ParameterSetName = 'Url')]
[string]
$Url,
[Parameter(Mandatory = $true, ParameterSetName = 'Default')]
[switch]
$Default,
[Parameter(Mandatory = $true, ParameterSetName = 'Root')]
[switch]
$Root,
[Parameter(Mandatory = $false)]
[string]
$Retrievals
)
process {
if ($ClientContext -eq $null) {
throw "Cannot bind argument to parameter 'ClientContext' because it is null."
}
if ($PSCmdlet.ParameterSetName -eq 'All') {
$ClientObject = $ClientContext.Web
Invoke-SPClientLoadQuery `
-ClientContext $ClientContext `
-ClientObject $ClientObject `
-Retrievals $Retrievals
Write-Output $ClientObject
$Stack = New-Object System.Collections.Stack
do {
Invoke-SPClientLoadQuery `
-ClientContext $ClientContext `
-ClientObject $ClientObject.Webs `
-Retrievals $Retrievals
while ($ClientObject.Webs.Count -gt 0) {
$Item = @{
Collection = $ClientObject.Webs
Index = 0
}
$Stack.Push($Item)
$ClientObject = $Item.Collection[$Item.Index]
Write-Output $ClientObject
Invoke-SPClientLoadQuery `
-ClientContext $ClientContext `
-ClientObject $ClientObject.Webs `
-Retrievals $Retrievals
}
while ($Stack.Count -gt 0) {
$Item = $Stack.Pop()
$Item.Index += 1
if ($Item.Index -lt $Item.Collection.Count) {
$Stack.Push($Item)
$ClientObject = $Item.Collection[$Item.Index]
Write-Output $ClientObject
break
}
}
} while ($Stack.Count -gt 0)
}
if ($PSCmdlet.ParameterSetName -eq 'Identity') {
$PathMethod = New-Object Microsoft.SharePoint.Client.ObjectPathMethod( `
$ClientContext, `
$ClientContext.Site.Path, `
'OpenWebById', `
[object[]]$Identity)
$ClientObject = New-Object Microsoft.SharePoint.Client.Web($ClientContext, $PathMethod)
Invoke-SPClientLoadQuery `
-ClientContext $ClientContext `
-ClientObject $ClientObject `
-Retrievals $Retrievals
Write-Output $ClientObject
trap {
throw 'The specified web could not be found.'
}
}
if ($PSCmdlet.ParameterSetName -eq 'Url') {
$PathMethod = New-Object Microsoft.SharePoint.Client.ObjectPathMethod( `
$ClientContext, `
$ClientContext.Site.Path, `
'OpenWeb', `
[object[]]$Url)
$ClientObject = New-Object Microsoft.SharePoint.Client.Web($ClientContext, $PathMethod)
Invoke-SPClientLoadQuery `
-ClientContext $ClientContext `
-ClientObject $ClientObject `
-Retrievals $Retrievals
Write-Output $ClientObject
trap {
throw 'The specified web could not be found.'
}
}
if ($PSCmdlet.ParameterSetName -eq 'Default') {
$ClientObject = $ClientContext.Web
Invoke-SPClientLoadQuery `
-ClientContext $ClientContext `
-ClientObject $ClientObject `
-Retrievals $Retrievals
Write-Output $ClientObject
}
if ($PSCmdlet.ParameterSetName -eq 'Root') {
$ClientObject = $ClientContext.Site.RootWeb
Invoke-SPClientLoadQuery `
-ClientContext $ClientContext `
-ClientObject $ClientObject `
-Retrievals $Retrievals
Write-Output $ClientObject
}
}
}
|
PowerShellCorpus/PowerShellGallery/SPClient/0.9/functions/SPClientWeb/Remove-SPClientWeb.ps1
|
Remove-SPClientWeb.ps1
|
#Requires -Version 3.0
# Remove-SPClientWeb.ps1
#
# Copyright (c) 2017 karamem0
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
function Remove-SPClientWeb {
<#
.SYNOPSIS
Deletes a web.
.PARAMETER ClientContext
Indicates the client context.
If not specified, uses default context.
.PARAMETER ClientObject
Indicates the web to delete.
.PARAMETER Identity
Indicates the web GUID.
.PARAMETER Url
Indicates the web relative url.
#>
[CmdletBinding(DefaultParameterSetName = 'ClientObject')]
param (
[Parameter(Mandatory = $false)]
[Microsoft.SharePoint.Client.ClientContext]
$ClientContext = $SPClient.ClientContext,
[Parameter(Mandatory = $true, ValueFromPipeline = $true, ParameterSetName = 'ClientObject')]
[Microsoft.SharePoint.Client.Web]
$ClientObject,
[Parameter(Mandatory = $true, ParameterSetName = 'Identity')]
[Alias('Id')]
[guid]
$Identity,
[Parameter(Mandatory = $true, ParameterSetName = 'Url')]
[string]
$Url
)
process {
if ($ClientContext -eq $null) {
throw "Cannot bind argument to parameter 'ClientContext' because it is null."
}
if ($PSCmdlet.ParameterSetName -eq 'ClientObject') {
if (-not $ClientObject.IsPropertyAvailable('Id')) {
Invoke-SPClientLoadQuery `
-ClientContext $ClientContext `
-ClientObject $ClientObject `
-Retrievals 'Id'
}
$ClientContext.ExecuteQuery()
} else {
if ($PSCmdlet.ParameterSetName -eq 'Identity') {
$PathMethod = New-Object Microsoft.SharePoint.Client.ObjectPathMethod( `
$ClientContext, `
$ClientContext.Site.Path, `
'OpenWebById', `
[object[]]$Identity)
$ClientObject = New-Object Microsoft.SharePoint.Client.Web($ClientContext, $PathMethod)
Invoke-SPClientLoadQuery `
-ClientContext $ClientContext `
-ClientObject $ClientObject `
-Retrievals 'Id'
}
if ($PSCmdlet.ParameterSetName -eq 'Url') {
$PathMethod = New-Object Microsoft.SharePoint.Client.ObjectPathMethod( `
$ClientContext, `
$ClientContext.Site.Path, `
'OpenWeb', `
[object[]]$Url)
$ClientObject = New-Object Microsoft.SharePoint.Client.Web($ClientContext, $PathMethod)
Invoke-SPClientLoadQuery `
-ClientContext $ClientContext `
-ClientObject $ClientObject `
-Retrievals 'Id'
}
trap {
throw 'The specified web could not be found.'
}
}
$ClientObject.DeleteObject()
$ClientContext.ExecuteQuery()
}
}
|
PowerShellCorpus/PowerShellGallery/SPClient/0.9/functions/SPClientType/Use-SPClientType.ps1
|
Use-SPClientType.ps1
|
#Requires -Version 3.0
# Use-SPClientType.ps1
#
# Copyright (c) 2017 karamem0
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
function Use-SPClientType {
<#
.SYNOPSIS
Loads SharePoint Client Components assemblies.
.DESCRIPTION
By default, this cmdlet loads assemblies below.
- %COMMONPROGRAMFILES%\Microsoft Shared\Web Server Extensions\<VERSION>\ISAPI
- Microsoft.SharePoint.Client.dll
- Microsoft.SharePoint.Client.Runtime.dll
.PARAMETER Version
Indicates the version of SharePoint Client Components.
The version must be "15" (SharePoint 2013), or "16" (SharePoint 2016).
If not specified, uses the latest version.
.PARAMETER LiteralPath
Indicates the path that locates SharePoint Client Components.
#>
[CmdletBinding(DefaultParameterSetName = 'Version')]
param (
[Parameter(Mandatory = $false, ParameterSetName = 'Version')]
[ValidateSet('15', '16')]
[string]
$Version,
[Parameter(Mandatory = $true, ParameterSetName = 'LiteralPath')]
[string]
$LiteralPath
)
process {
if ($PSCmdlet.ParameterSetName -eq 'Version') {
$Path = $Env:CommonProgramFiles
if (-not [string]::IsNullOrEmpty($Env:CommonProgramW6432)) {
$Path = $Env:CommonProgramW6432
}
$Path = Join-Path -Path $Path -ChildPath 'Microsoft Shared\Web Server Extensions'
if (-not (Test-Path -Path $Path)) {
throw 'Cannot find SharePoint Client Component assemblies.'
}
if (-not (Get-ChildItem -Path $Path)) {
throw 'Cannot find SharePoint Client Component assemblies.'
}
if ([string]::IsNullOrEmpty($Version)) {
$Version = [string](Get-ChildItem -Path $Path | Sort-Object -Descending)[0]
}
$Path = Join-Path -Path $Path $Version
$Path = Join-Path -Path $Path 'ISAPI'
}
if ($PSCmdlet.ParameterSetName -eq 'LiteralPath') {
if (-not (Test-Path -Path $LiteralPath)) {
throw 'Cannot find SharePoint Client Component assemblies.'
}
$Path = $LiteralPath
}
Add-Type -Path (Join-Path -Path $Path -ChildPath 'Microsoft.SharePoint.Client.dll')
Add-Type -Path (Join-Path -Path $Path -ChildPath 'Microsoft.SharePoint.Client.Runtime.dll')
}
}
|
PowerShellCorpus/PowerShellGallery/SPClient/0.9/functions/SPClientGroup/Get-SPClientGroup.ps1
|
Get-SPClientGroup.ps1
|
#Requires -Version 3.0
# Get-SPClientGroup.ps1
#
# Copyright (c) 2017 karamem0
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
function Get-SPClientGroup {
<#
.SYNOPSIS
Lists all site groups or retrieve the specified site group.
.DESCRIPTION
If not specified filterable parameter, returns site all groups. Otherwise,
returns a group which matches the parameter.
.PARAMETER ClientContext
Indicates the client context.
If not specified, uses default context.
.PARAMETER Identity
Indicates the group id.
.PARAMETER Name
Indicates the group name.
.PARAMETER Retrievals
Indicates the data retrieval expression.
#>
[CmdletBinding(DefaultParameterSetName = 'All')]
param (
[Parameter(Mandatory = $false, ParameterSetName = 'All')]
[Parameter(Mandatory = $false, ParameterSetName = 'Identity')]
[Parameter(Mandatory = $false, ParameterSetName = 'Name')]
[Microsoft.SharePoint.Client.ClientContext]
$ClientContext = $SPClient.ClientContext,
[Parameter(Mandatory = $true, ParameterSetName = 'Identity')]
[Alias('Id')]
[int]
$Identity,
[Parameter(Mandatory = $true, ParameterSetName = 'Name')]
[Alias('Title')]
[string]
$Name,
[Parameter(Mandatory = $false)]
[string]
$Retrievals
)
process {
if ($ClientContext -eq $null) {
throw "Cannot bind argument to parameter 'ClientContext' because it is null."
}
$ClientObjectCollection = $ClientContext.Site.RootWeb.SiteGroups
if ($PSCmdlet.ParameterSetName -eq 'All') {
Invoke-SPClientLoadQuery `
-ClientContext $ClientContext `
-ClientObject $ClientObjectCollection `
-Retrievals $Retrievals
Write-Output @(, $ClientObjectCollection)
}
if ($PSCmdlet.ParameterSetName -eq 'Identity') {
$PathMethod = New-Object Microsoft.SharePoint.Client.ObjectPathMethod( `
$ClientContext, `
$ClientObjectCollection.Path, `
'GetById', `
[object[]]$Identity)
$ClientObject = New-Object Microsoft.SharePoint.Client.Group($ClientContext, $PathMethod)
Invoke-SPClientLoadQuery `
-ClientContext $ClientContext `
-ClientObject $ClientObject `
-Retrievals $Retrievals
Write-Output $ClientObject
trap {
throw 'The specified group could not be found.'
}
}
if ($PSCmdlet.ParameterSetName -eq 'Name') {
$PathMethod = New-Object Microsoft.SharePoint.Client.ObjectPathMethod( `
$ClientContext, `
$ClientObjectCollection.Path, `
'GetByName', `
[object[]]$Name)
$ClientObject = New-Object Microsoft.SharePoint.Client.Group($ClientContext, $PathMethod)
Invoke-SPClientLoadQuery `
-ClientContext $ClientContext `
-ClientObject $ClientObject `
-Retrievals $Retrievals
Write-Output $ClientObject
trap {
throw 'The specified group could not be found.'
}
}
}
}
|
PowerShellCorpus/PowerShellGallery/SPClient/0.9/functions/SPClientGroup/New-SPClientGroup.ps1
|
New-SPClientGroup.ps1
|
#Requires -Version 3.0
# New-SPClientGroup.ps1
#
# Copyright (c) 2017 karamem0
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
function New-SPClientGroup {
<#
.SYNOPSIS
Creates a new group.
.PARAMETER ClientContext
Indicates the client context.
If not specified, uses default context.
.PARAMETER Name
Indicates the group name.
.PARAMETER Description
Indicates the description.
.PARAMETER Owner
Indicates the owner.
.PARAMETER Users
Indicates the collection of users to add to group.
.PARAMETER Retrievals
Indicates the data retrieval expression.
#>
[CmdletBinding()]
param (
[Parameter(Mandatory = $false)]
[Microsoft.SharePoint.Client.ClientContext]
$ClientContext = $SPClient.ClientContext,
[Parameter(Mandatory = $true)]
[Alias('Title')]
[string]
$Name,
[Parameter(Mandatory = $false)]
[string]
$Description,
[Parameter(Mandatory = $false)]
[Microsoft.SharePoint.Client.Principal]
$Owner,
[Parameter(Mandatory = $false)]
[Microsoft.SharePoint.Client.User[]]
$Users,
[Parameter(Mandatory = $false)]
[string]
$Retrievals
)
process {
if ($ClientContext -eq $null) {
throw "Cannot bind argument to parameter 'ClientContext' because it is null."
}
$Creation = New-Object Microsoft.SharePoint.Client.GroupCreationInformation
$Creation.Title = $Name
$Creation.Description = $Description
$ClientObject = $ClientContext.Site.RootWeb.SiteGroups.Add($Creation)
if ($MyInvocation.BoundParameters.ContainsKey('Owner')) {
$ClientObject.Owner = $Owner
}
if ($MyInvocation.BoundParameters.ContainsKey('Users')) {
foreach ($User in $Users) {
$ClientObject.Users.AddUser($User) | Out-Null
}
}
$ClientObject.Update()
Invoke-SPClientLoadQuery `
-ClientContext $ClientContext `
-ClientObject $ClientObject `
-Retrievals $Retrievals
Write-Output $ClientObject
}
}
|
PowerShellCorpus/PowerShellGallery/SPClient/0.9/functions/SPClientGroup/Remove-SPClientGroup.ps1
|
Remove-SPClientGroup.ps1
|
#Requires -Version 3.0
# Remove-SPClientGroup.ps1
#
# Copyright (c) 2017 karamem0
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
function Remove-SPClientGroup {
<#
.SYNOPSIS
Deletes a group.
.PARAMETER ClientContext
Indicates the client context.
If not specified, uses default context.
.PARAMETER ClientObject
Indicates the group to delete.
.PARAMETER Identity
Indicates the group id.
.PARAMETER Name
Indicates the group name.
#>
[CmdletBinding(DefaultParameterSetName = 'ClientObject')]
param (
[Parameter(Mandatory = $false)]
[Microsoft.SharePoint.Client.ClientContext]
$ClientContext = $SPClient.ClientContext,
[Parameter(Mandatory = $true, ValueFromPipeline = $true, ParameterSetName = 'ClientObject')]
[Microsoft.SharePoint.Client.Group]
$ClientObject,
[Parameter(Mandatory = $true, ParameterSetName = 'Identity')]
[Alias('Id')]
[int]
$Identity,
[Parameter(Mandatory = $true, ParameterSetName = 'Name')]
[Alias('Title')]
[string]
$Name
)
process {
if ($ClientContext -eq $null) {
throw "Cannot bind argument to parameter 'ClientContext' because it is null."
}
$ClientObjectCollection = $ClientContext.Site.RootWeb.SiteGroups
if ($PSCmdlet.ParameterSetName -eq 'ClientObject') {
if (-not $ClientObject.IsPropertyAvailable('Id')) {
Invoke-SPClientLoadQuery `
-ClientContext $ClientContext `
-ClientObject $ClientObject `
-Retrievals 'Id'
}
} else {
if ($PSCmdlet.ParameterSetName -eq 'Identity') {
$PathMethod = New-Object Microsoft.SharePoint.Client.ObjectPathMethod( `
$ClientContext, `
$ClientObjectCollection.Path, `
'GetById', `
[object[]]$Identity)
$ClientObject = New-Object Microsoft.SharePoint.Client.Group($ClientContext, $PathMethod)
Invoke-SPClientLoadQuery `
-ClientContext $ClientContext `
-ClientObject $ClientObject `
-Retrievals 'Id'
trap {
throw 'The specified group could not be found.'
}
}
if ($PSCmdlet.ParameterSetName -eq 'Name') {
$PathMethod = New-Object Microsoft.SharePoint.Client.ObjectPathMethod( `
$ClientContext, `
$ClientObjectCollection.Path, `
'GetByName', `
[object[]]$Name)
$ClientObject = New-Object Microsoft.SharePoint.Client.Group($ClientContext, $PathMethod)
Invoke-SPClientLoadQuery `
-ClientContext $ClientContext `
-ClientObject $ClientObject `
-Retrievals 'Id'
trap {
throw 'The specified group could not be found.'
}
}
}
$ClientObjectCollection.Remove($ClientObject)
$ClientContext.ExecuteQuery()
}
}
|
PowerShellCorpus/PowerShellGallery/SMLetsExt/1.0.14/SMLetsExt.tests.ps1
|
SMLetsExt.tests.ps1
|
#Requires -Modules Pester
<#
.SYNOPSIS
Tests the SCSMReviewActivities module
.EXAMPLE
Invoke-Pester
.NOTES
This script originated from work found here: https://github.com/kmarquette/PesterInAction
scriptanalyzer section basics taken from DSCResource.Tests
#>
Import-Module -Name (Join-Path -Path $PSScriptRoot -ChildPath 'ModuleHelper.psm1') -Force
$ErrorActionPreference = 'stop'
Set-StrictMode -Version latest
$RepoRoot = Split-Path -Parent $MyInvocation.MyCommand.Path
Write-Verbose -Verbose "RepoRoot $($reporoot)"
$module = 'SMLetsExt'
$psVersion = $PSVersionTable.PSVersion
Write-Verbose -Verbose "Module $($Module)"
#region PSScriptanalyzer
if ($psVersion.Major -ge 5)
{
Write-Verbose -Verbose "Installing PSScriptAnalyzer"
$PSScriptAnalyzerModuleName = "PSScriptAnalyzer"
Install-PackageProvider -Name NuGet -Force
Install-Module -Name $PSScriptAnalyzerModuleName -Scope CurrentUser -Force
$PSScriptAnalyzerModule = get-module -Name $PSScriptAnalyzerModuleName -ListAvailable
if ($PSScriptAnalyzerModule) {
# Import the module if it is available
$PSScriptAnalyzerModule | Import-Module -Force
}
else
{
# Module could not/would not be installed - so warn user that tests will fail.
Write-Warning -Message ( @(
"The 'PSScriptAnalyzer' module is not installed. "
"The 'PowerShell modules scriptanalyzer' Pester test will fail "
) -Join '' )
}
}
else
{
Write-Verbose -Verbose "Skipping installation of PSScriptAnalyzer since it requires PSVersion 5.0 or greater. Used PSVersion: $($PSVersion)"
}
#endregion
Describe 'Text files formatting' {
$allTextFiles = Get-TextFilesList $RepoRoot
Context 'Files encoding' {
It "Doesn't use Unicode encoding" {
$unicodeFilesCount = 0
$allTextFiles | %{
if (Test-FileUnicode $_) {
$unicodeFilesCount += 1
Write-Warning "File $($_.FullName) contains 0x00 bytes. It's probably uses Unicode and need to be converted to UTF-8. Use Fixer 'Get-UnicodeFilesList `$pwd | ConvertTo-UTF8'."
}
}
$unicodeFilesCount | Should Be 1
}
}
Context 'Indentations' {
It 'Uses spaces for indentation, not tabs' {
$totalTabsCount = 0
$allTextFiles | %{
$fileName = $_.FullName
Get-Content $_.FullName -Raw | Select-String "`t" | % {
Write-Warning "There are tab in $fileName. Use Fixer 'Get-TextFilesList `$pwd | ConvertTo-SpaceIndentation'."
$totalTabsCount++
}
}
$totalTabsCount | Should Be 0
}
}
}
Describe "Module: $module" -Tags Unit {
#region ScriptAnalyzer
Context 'PSScriptAnalyzer' {
It "passes Invoke-ScriptAnalyzer" {
# Perform PSScriptAnalyzer scan.
# Using ErrorAction SilentlyContinue not to cause it to fail due to parse errors caused by unresolved resources.
# Many of our examples try to import different modules which may not be present on the machine and PSScriptAnalyzer throws parse exceptions even though examples are valid.
# Errors will still be returned as expected.
$PSScriptAnalyzerErrors = Invoke-ScriptAnalyzer -path $RepoRoot -Severity Error -Recurse -ErrorAction SilentlyContinue
if ($PSScriptAnalyzerErrors -ne $null) {
Write-Error "There are PSScriptAnalyzer errors that need to be fixed:`n $PSScriptAnalyzerErrors"
Write-Error "For instructions on how to run PSScriptAnalyzer on your own machine, please go to https://github.com/powershell/psscriptAnalyzer/"
$PSScriptAnalyzerErrors.Count | Should Be $null
}
}
}
#endregion
#region Generic PS module tests
Context "Module Configuration"{
It "Has a root module file ($module.psm1)" {
"$RepoRoot\$module.psm1" | Should Exist
}
It "Is valid Powershell (Has no script errors)" {
$contents = Get-Content -Path "$RepoRoot\$module.psm1" -ErrorAction SilentlyContinue
$errors = $null
$null = [System.Management.Automation.PSParser]::Tokenize($contents, [ref]$errors)
$errors.Count | Should Be 0
}
It "Has a manifest file ($module.psd1)" {
"$RepoRoot\$module.psd1" | Should Exist
}
It "Contains a root module path in the manifest (RootModule = '.\$module.psm1')" {
"$RepoRoot\$module.psd1" | Should Exist
"$RepoRoot\$module.psd1" | Should Contain "\.\\$module.psm1"
}
It "Is valid Powershell (Has no script errors)" {
$contents = Get-Content -Path "$RepoRoot\$module.psm1" -ErrorAction Stop
$errors = $null
$null = [System.Management.Automation.PSParser]::Tokenize($contents, [ref]$errors)
$errors.Count | Should Be 0
}
}
#endregion
#region module content
Context 'Module loads and Functions exist' {
$manifest = Test-ModuleManifest -Path "$RepoRoot\$module.psd1"
$ExportedCommands = $manifest.ExportedCommands
$ModuleName = $manifest.Name
BeforeEach {
if (get-module $Module) {remove-module $Module}
import-Module "$RepoRoot\$module.psd1" -ErrorAction SilentlyContinue
$loadedModule = Get-Module $module -ErrorAction SilentlyContinue
$loadedFunctions = $loadedModule.ExportedCommands.Keys
}
It 'Module should load without error' {
$loadedModule.Name | Should Be $ModuleName
}
It 'Exported commands should include all functions' {
$loadedFunctions | Should Be $ExportedCommands.Keys
}
AfterEach {
remove-module $module
$loadedModule = $null
$loadedFunctions = $null
}
}
#endregion
#region functions
Context 'Help provided for Functions' {
BeforeAll {
if (get-module $Module) {remove-module $Module}
import-Module "$RepoRoot\$module.psd1" -ErrorAction SilentlyContinue
$loadedModule = Get-Module $module -ErrorAction SilentlyContinue
$loadedFunctions = $loadedModule.ExportedCommands.keys
}
Foreach ($Function in $loadedFunctions) {
$Help = Get-Help $Function
It "$Function should have a non-default Synopsis section in help" {
$Help.Synopsis | Should Not Match "\r\n$Function*"
}
It "$Function should have help examples" {
$Help.Examples.Example.Count | Should Not Be 0
}
}
AfterAll {
remove-module $module
$loadedFunctions = $null
$loadedModule = $null
}
}
}
#endregion
|
PowerShellCorpus/PowerShellGallery/EPS/0.4.0/Each.ps1
|
Each.ps1
|
function Each {
[CmdletBinding()]
Param(
[Parameter(ValueFromPipeline=$True, ValueFromPipelinebyPropertyName=$True)]
[Object[]]$InputObject,
[Parameter(Mandatory=$True, Position=0)]
[ScriptBlock]$Process,
[ScriptBlock]$Begin,
[ScriptBlock]$End,
[String]$Join
)
Begin {
$StringBuilderVar = New-Object -TypeName 'System.Management.Automation.PSVariable' 'sb'
$ItemVar = New-Object -TypeName 'System.Management.Automation.PSVariable' '_'
$IndexVar = New-Object -TypeName 'System.Management.Automation.PSVariable' @('index', 0)
$Vars = @($ItemVar, $StringBuilderVar, $IndexVar)
function Invoke-InnerBlock {
Param(
[ScriptBlock]$ScriptBlock,
$Item = $Null
)
if ($ScriptBlock) {
$fsb = New-Object -TypeName 'System.Text.StringBuilder'
$StringBuilderVar.Value = $fsb
$ItemVar.Value = $Item
[void]$ScriptBlock.InvokeWithContext(@{}, $Vars)
$fsb.ToString()
}
}
if ($Join) {
$Accumulator = New-Object -TypeName 'System.Collections.ArrayList'
[void]$Accumulator.Add((Invoke-InnerBlock -ScriptBlock $Begin))
} else {
[void]$sb.Append((Invoke-InnerBlock -ScriptBlock $Begin))
}
}
Process {
if ($Join) {
foreach($item in $InputObject) {
[void]$Accumulator.Add((Invoke-InnerBlock -ScriptBlock $Process -Item $item))
$IndexVar.Value += 1
}
} else {
foreach($item in $InputObject) {
[void]$sb.Append((Invoke-InnerBlock -ScriptBlock $Process -Item $item))
$IndexVar.Value += 1
}
}
}
End {
if ($Join) {
[void]$Accumulator.Add((Invoke-InnerBlock -ScriptBlock $End))
[void]$sb.Append($Accumulator.Where({ $_ -ne $Null}) -Join $Join)
} else {
[void]$sb.Append((Invoke-InnerBlock -ScriptBlock $End))
}
}
}
|
PowerShellCorpus/PowerShellGallery/EPS/0.4.0/New-EpsTemplateScript.ps1
|
New-EpsTemplateScript.ps1
|
function New-EpsTemplateScript {
Param(
[Parameter(Mandatory = $True)]
[AllowEmptyString()]
[String]$Template
)
$position = 0
$Pattern = [regex]"(?sm)<%(?<ind>={1,2}|-|#|%)?(?<code>.*?)(?<tailch>[-=])?%>(?<rspace>[ \t]*\r?\n)?"
$StringBuilder = New-Object -TypeName "System.Text.StringBuilder"
function Add-Prolog {
[void]$StringBuilder.`
Append("`$sb = New-Object -TypeName 'System.Text.StringBuilder'`n").`
Append("[void]`$(`n")
}
function Add-String {
Param([String]$Value, [switch]$NoEscape)
if ($Value) {
if (!$NoEscape) {
$Value = ($Value -replace "<%%", "<%") -replace "%%>", "%>"
}
$Value = $Value -replace '([`"$])', '`$1'
[void]$StringBuilder.Append(";`$sb.Append(`"").Append($Value).Append("`");")
}
}
function Add-LiteralString {
Param([String[]]$Values)
foreach ($Value in $Values) {
[void]$StringBuilder.Append($Value)
}
}
function Add-Expression {
Param([String]$Value)
[void]$StringBuilder.`
Append("`$sb.Append(`"`$(").`
Append($Value).`
Append(")`");")
}
function Add-Code {
Param([String]$Value)
[void]$StringBuilder.Append($Value)
}
function Add-Epilog {
[void]$StringBuilder.Append("`n)`n`$sb.ToString()")
}
Add-Prolog
$Pattern.Matches($Template) | ForEach-Object {
$match = $_
$contentLength = $match.Index - $position
$content = $Template.Substring($position, $contentLength)
$position = $match.Index + $match.Length
$ind = $Match.Groups["ind"].Value
$code = $Match.Groups["code"].Value
$tail = $Match.Groups["tailch"].Value
$rspace = $Match.Groups["rspace"].Value
if (($ind -ne '-') -and ($content -ne "")) {
Add-String $content
} else {
Add-Code ";"
}
switch ($ind) {
'=' {
Add-Expression $code.Trim()
}
'-' {
Add-String ($content -replace '(?smi)([\n\r]+|\A)[ \t]+\z', '$1')
Add-Code $code.Trim()
}
'' {
Add-Code $code.Trim()
}
'%' {
Add-LiteralString "`$sb.Append('<%", $code, ">');"
Add-String $rspace -NoEscape
}
'#' {
}
}
if (($ind -ne '%') -and (($tail -ne '-') -or ($rspace -match '^[^\r\n]'))) {
Add-String $rspace -NoEscape
} else {
Add-Code ";"
}
}
if ($position -eq 0) {
Add-String $Template
} elseif ($position -lt $Template.Length) {
Add-String $Template.Substring($position, $Template.Length - $position)
}
Add-Epilog
[ScriptBlock]::Create($StringBuilder.ToString())
}
|
PowerShellCorpus/PowerShellGallery/EPS/0.4.0/Invoke-EpsTemplate.ps1
|
Invoke-EpsTemplate.ps1
|
$ErrorActionPreference = "Stop"
function Invoke-EpsTemplate {
[CmdletBinding()]
[Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidUsingInvokeExpression", "")]
Param(
[Parameter(ParameterSetName='String template')]
[String]$Template,
[Parameter(ParameterSetName='File template')]
[String]$Path,
[Parameter(ValueFromPipeline=$True, ValueFromPipelinebyPropertyName=$True)]
[Hashtable]$Binding = @{},
[switch]$Safe
)
if ($PSCmdlet.ParameterSetName -eq 'File template') {
$Template = [IO.File]::ReadAllText($Path)
}
$templateScriptBlock = New-EpsTemplateScript -Template $Template
Write-Verbose "Executing script @'`n$templateScriptBlock`n'@."
if($Safe) {
$block = {
Param([ScriptBlock]$Script, [Hashtable]$Binding)
$Binding.GetEnumerator() | ForEach-Object { New-Variable -Name $_.Key -Value $_.Value }
$Script.Invoke()
}
try {
$powershell = [powershell]::Create()
$powershell.`
AddScript((Get-Content "$PSScriptRoot/Each.ps1" -Raw)).`
AddScript($block).`
AddParameter("Binding", $Binding).`
AddParameter("Script", $templateScriptBlock).`
Invoke()
} finally {
if ($powershell) {
$powershell.Dispose()
}
}
} else {
if ($templateScriptBlock.psobject.Methods['InvokeWithContext']) {
# InvokeWithContext was introduced in PowerShell version 3.0
$variablesToDefine = $Binding.GetEnumerator() |
ForEach-Object { New-Object System.Management.Automation.PSVariable @($_.Key, $_.Value) }
$templateScriptBlock.InvokeWithContext(@{}, $variablesToDefine)
} else {
$Binding.GetEnumerator() | ForEach-Object { New-Variable -Name $_.Key -Value $_.Value }
$templateScriptBlock.Invoke()
}
}
}
|
PowerShellCorpus/PowerShellGallery/VMware.VimAutomation.HorizonView/7.1.0.5307191/VMware.VimAutomation.HorizonView.ps1
|
VMware.VimAutomation.HorizonView.ps1
|
# Script to import Connect/Disconnect HVServer cmdlets
[VMware.VimAutomation.Sdk.Interop.V1.CoreServiceFactory]::CoreService.OnImportModule(
"VMware.VimAutomation.HorizonView.Commands",
(Split-Path $script:MyInvocation.MyCommand.Path));
# This script contains routines for additional module initialization.
function global:Get-HvCommand([string] $Name = "*") {
get-command -module VMware.VimAutomation.HorizonView.Commands -Name $Name
}
# SIG # Begin signature block
# MIIdVgYJKoZIhvcNAQcCoIIdRzCCHUMCAQExCzAJBgUrDgMCGgUAMGkGCisGAQQB
# gjcCAQSgWzBZMDQGCisGAQQBgjcCAR4wJgIDAQAABBAfzDtgWUsITrck0sYpfvNR
# AgEAAgEAAgEAAgEAAgEAMCEwCQYFKw4DAhoFAAQU1ldGjobOHzN1mT5ulaup+gJM
# YkWgghhpMIID7jCCA1egAwIBAgIQfpPr+3zGTlnqS5p31Ab8OzANBgkqhkiG9w0B
# AQUFADCBizELMAkGA1UEBhMCWkExFTATBgNVBAgTDFdlc3Rlcm4gQ2FwZTEUMBIG
# A1UEBxMLRHVyYmFudmlsbGUxDzANBgNVBAoTBlRoYXd0ZTEdMBsGA1UECxMUVGhh
# d3RlIENlcnRpZmljYXRpb24xHzAdBgNVBAMTFlRoYXd0ZSBUaW1lc3RhbXBpbmcg
# Q0EwHhcNMTIxMjIxMDAwMDAwWhcNMjAxMjMwMjM1OTU5WjBeMQswCQYDVQQGEwJV
# UzEdMBsGA1UEChMUU3ltYW50ZWMgQ29ycG9yYXRpb24xMDAuBgNVBAMTJ1N5bWFu
# dGVjIFRpbWUgU3RhbXBpbmcgU2VydmljZXMgQ0EgLSBHMjCCASIwDQYJKoZIhvcN
# AQEBBQADggEPADCCAQoCggEBALGss0lUS5ccEgrYJXmRIlcqb9y4JsRDc2vCvy5Q
# WvsUwnaOQwElQ7Sh4kX06Ld7w3TMIte0lAAC903tv7S3RCRrzV9FO9FEzkMScxeC
# i2m0K8uZHqxyGyZNcR+xMd37UWECU6aq9UksBXhFpS+JzueZ5/6M4lc/PcaS3Er4
# ezPkeQr78HWIQZz/xQNRmarXbJ+TaYdlKYOFwmAUxMjJOxTawIHwHw103pIiq8r3
# +3R8J+b3Sht/p8OeLa6K6qbmqicWfWH3mHERvOJQoUvlXfrlDqcsn6plINPYlujI
# fKVOSET/GeJEB5IL12iEgF1qeGRFzWBGflTBE3zFefHJwXECAwEAAaOB+jCB9zAd
# BgNVHQ4EFgQUX5r1blzMzHSa1N197z/b7EyALt0wMgYIKwYBBQUHAQEEJjAkMCIG
# CCsGAQUFBzABhhZodHRwOi8vb2NzcC50aGF3dGUuY29tMBIGA1UdEwEB/wQIMAYB
# Af8CAQAwPwYDVR0fBDgwNjA0oDKgMIYuaHR0cDovL2NybC50aGF3dGUuY29tL1Ro
# YXd0ZVRpbWVzdGFtcGluZ0NBLmNybDATBgNVHSUEDDAKBggrBgEFBQcDCDAOBgNV
# HQ8BAf8EBAMCAQYwKAYDVR0RBCEwH6QdMBsxGTAXBgNVBAMTEFRpbWVTdGFtcC0y
# MDQ4LTEwDQYJKoZIhvcNAQEFBQADgYEAAwmbj3nvf1kwqu9otfrjCR27T4IGXTdf
# plKfFo3qHJIJRG71betYfDDo+WmNI3MLEm9Hqa45EfgqsZuwGsOO61mWAK3ODE2y
# 0DGmCFwqevzieh1XTKhlGOl5QGIllm7HxzdqgyEIjkHq3dlXPx13SYcqFgZepjhq
# IhKjURmDfrYwggSjMIIDi6ADAgECAhAOz/Q4yP6/NW4E2GqYGxpQMA0GCSqGSIb3
# DQEBBQUAMF4xCzAJBgNVBAYTAlVTMR0wGwYDVQQKExRTeW1hbnRlYyBDb3Jwb3Jh
# dGlvbjEwMC4GA1UEAxMnU3ltYW50ZWMgVGltZSBTdGFtcGluZyBTZXJ2aWNlcyBD
# QSAtIEcyMB4XDTEyMTAxODAwMDAwMFoXDTIwMTIyOTIzNTk1OVowYjELMAkGA1UE
# BhMCVVMxHTAbBgNVBAoTFFN5bWFudGVjIENvcnBvcmF0aW9uMTQwMgYDVQQDEytT
# eW1hbnRlYyBUaW1lIFN0YW1waW5nIFNlcnZpY2VzIFNpZ25lciAtIEc0MIIBIjAN
# BgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAomMLOUS4uyOnREm7Dv+h8GEKU5Ow
# mNutLA9KxW7/hjxTVQ8VzgQ/K/2plpbZvmF5C1vJTIZ25eBDSyKV7sIrQ8Gf2Gi0
# jkBP7oU4uRHFI/JkWPAVMm9OV6GuiKQC1yoezUvh3WPVF4kyW7BemVqonShQDhfu
# ltthO0VRHc8SVguSR/yrrvZmPUescHLnkudfzRC5xINklBm9JYDh6NIipdC6Anqh
# d5NbZcPuF3S8QYYq3AhMjJKMkS2ed0QfaNaodHfbDlsyi1aLM73ZY8hJnTrFxeoz
# C9Lxoxv0i77Zs1eLO94Ep3oisiSuLsdwxb5OgyYI+wu9qU+ZCOEQKHKqzQIDAQAB
# o4IBVzCCAVMwDAYDVR0TAQH/BAIwADAWBgNVHSUBAf8EDDAKBggrBgEFBQcDCDAO
# BgNVHQ8BAf8EBAMCB4AwcwYIKwYBBQUHAQEEZzBlMCoGCCsGAQUFBzABhh5odHRw
# Oi8vdHMtb2NzcC53cy5zeW1hbnRlYy5jb20wNwYIKwYBBQUHMAKGK2h0dHA6Ly90
# cy1haWEud3Muc3ltYW50ZWMuY29tL3Rzcy1jYS1nMi5jZXIwPAYDVR0fBDUwMzAx
# oC+gLYYraHR0cDovL3RzLWNybC53cy5zeW1hbnRlYy5jb20vdHNzLWNhLWcyLmNy
# bDAoBgNVHREEITAfpB0wGzEZMBcGA1UEAxMQVGltZVN0YW1wLTIwNDgtMjAdBgNV
# HQ4EFgQURsZpow5KFB7VTNpSYxc/Xja8DeYwHwYDVR0jBBgwFoAUX5r1blzMzHSa
# 1N197z/b7EyALt0wDQYJKoZIhvcNAQEFBQADggEBAHg7tJEqAEzwj2IwN3ijhCcH
# bxiy3iXcoNSUA6qGTiWfmkADHN3O43nLIWgG2rYytG2/9CwmYzPkSWRtDebDZw73
# BaQ1bHyJFsbpst+y6d0gxnEPzZV03LZc3r03H0N45ni1zSgEIKOq8UvEiCmRDoDR
# EfzdXHZuT14ORUZBbg2w6jiasTraCXEQ/Bx5tIB7rGn0/Zy2DBYr8X9bCT2bW+IW
# yhOBbQAuOA2oKY8s4bL0WqkBrxWcLC9JG9siu8P+eJRRw4axgohd8D20UaF5Mysu
# e7ncIAkTcetqGVvP6KUwVyyJST+5z3/Jvz4iaGNTmr1pdKzFHTx/kuDDvBzYBHUw
# ggTRMIIDuaADAgECAhBlO8IY/xbhmnONwPCxJt5hMA0GCSqGSIb3DQEBCwUAMH8x
# CzAJBgNVBAYTAlVTMR0wGwYDVQQKExRTeW1hbnRlYyBDb3Jwb3JhdGlvbjEfMB0G
# A1UECxMWU3ltYW50ZWMgVHJ1c3QgTmV0d29yazEwMC4GA1UEAxMnU3ltYW50ZWMg
# Q2xhc3MgMyBTSEEyNTYgQ29kZSBTaWduaW5nIENBMB4XDTE1MDcyNDAwMDAwMFoX
# DTE4MDgyMjIzNTk1OVowZDELMAkGA1UEBhMCVVMxEzARBgNVBAgTCkNhbGlmb3Ju
# aWExEjAQBgNVBAcTCVBhbG8gQWx0bzEVMBMGA1UEChQMVk13YXJlLCBJbmMuMRUw
# EwYDVQQDFAxWTXdhcmUsIEluYy4wggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEK
# AoIBAQDCmS07ZAwM9eVLBDfxw1rKIge6PZwfP8Xh2YSsyjzRUzzBouY4j7GTjM2e
# OZLiZhL+B32ps1BdfKJfSBaOein4ynaxVgCf9XuVWQKIZMzss+FJcf5gOk0dV/9t
# CHzIfoC81H1/PrnkX0uXRHcuz22m9FH9ggA3CLJPQlumTcxtqftNFSJsX0BT3Afg
# VDs/lsCEeY8VodT9AJzGGVGMz0YIB2J0gM8w9s9/1znjh4BFRp2AfrBk2Y0Ujoh2
# gaZEoLMfX1mI+QJdsKRNRt+lBerbyH93DupYJPviUavYiEg/b3+4xsYmkjq7dcNc
# ZTB93URHdg6ipSo3/R6B4PzUow5fAgMBAAGjggFiMIIBXjAJBgNVHRMEAjAAMA4G
# A1UdDwEB/wQEAwIHgDArBgNVHR8EJDAiMCCgHqAchhpodHRwOi8vc3Yuc3ltY2Iu
# Y29tL3N2LmNybDBmBgNVHSAEXzBdMFsGC2CGSAGG+EUBBxcDMEwwIwYIKwYBBQUH
# AgEWF2h0dHBzOi8vZC5zeW1jYi5jb20vY3BzMCUGCCsGAQUFBwICMBkMF2h0dHBz
# Oi8vZC5zeW1jYi5jb20vcnBhMBMGA1UdJQQMMAoGCCsGAQUFBwMDMFcGCCsGAQUF
# BwEBBEswSTAfBggrBgEFBQcwAYYTaHR0cDovL3N2LnN5bWNkLmNvbTAmBggrBgEF
# BQcwAoYaaHR0cDovL3N2LnN5bWNiLmNvbS9zdi5jcnQwHwYDVR0jBBgwFoAUljtT
# 8Hkzl699g+8uK8zKt4YecmYwHQYDVR0OBBYEFGaw3m9kanGu85olA8OJIdV3JXR/
# MA0GCSqGSIb3DQEBCwUAA4IBAQA27zm4ThfMqwr7AVYhk6efINp10t4N+ip4DxqQ
# t8Z+SSnPUeO23MmoUHFVWhJS57lgx0FVdAcUBdSmh/N7YvtoGfTOr4Q6k6Z6bjmV
# hUD3QIL77lGPGeotS8QIPeb9F5lX4Y/eiwRZ8254MFM0D2r+CgSVs123MS0zEZjF
# r7ychqVu77UXEuaQFDHkS1fEsiaRqrEnu8pNhcFVwZCzLJnn9DYOfpfgG8s8pwCF
# 2J6Cxs5MFPiO35OfZuXqRRx/7wlCIj6rcyb4sq62ksRA1On8OP6svY6AucSzTTFI
# SYrHImOnHnffhNrBogdf5uuwEuom3KoKMOt/0QqAXDt4cO9fMIIFWTCCBEGgAwIB
# AgIQPXjX+XZJYLJhffTwHsqGKjANBgkqhkiG9w0BAQsFADCByjELMAkGA1UEBhMC
# VVMxFzAVBgNVBAoTDlZlcmlTaWduLCBJbmMuMR8wHQYDVQQLExZWZXJpU2lnbiBU
# cnVzdCBOZXR3b3JrMTowOAYDVQQLEzEoYykgMjAwNiBWZXJpU2lnbiwgSW5jLiAt
# IEZvciBhdXRob3JpemVkIHVzZSBvbmx5MUUwQwYDVQQDEzxWZXJpU2lnbiBDbGFz
# cyAzIFB1YmxpYyBQcmltYXJ5IENlcnRpZmljYXRpb24gQXV0aG9yaXR5IC0gRzUw
# HhcNMTMxMjEwMDAwMDAwWhcNMjMxMjA5MjM1OTU5WjB/MQswCQYDVQQGEwJVUzEd
# MBsGA1UEChMUU3ltYW50ZWMgQ29ycG9yYXRpb24xHzAdBgNVBAsTFlN5bWFudGVj
# IFRydXN0IE5ldHdvcmsxMDAuBgNVBAMTJ1N5bWFudGVjIENsYXNzIDMgU0hBMjU2
# IENvZGUgU2lnbmluZyBDQTCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEB
# AJeDHgAWryyx0gjE12iTUWAecfbiR7TbWE0jYmq0v1obUfejDRh3aLvYNqsvIVDa
# nvPnXydOC8KXyAlwk6naXA1OpA2RoLTsFM6RclQuzqPbROlSGz9BPMpK5KrA6Dmr
# U8wh0MzPf5vmwsxYaoIV7j02zxzFlwckjvF7vjEtPW7ctZlCn0thlV8ccO4XfduL
# 5WGJeMdoG68ReBqYrsRVR1PZszLWoQ5GQMWXkorRU6eZW4U1V9Pqk2JhIArHMHck
# EU1ig7a6e2iCMe5lyt/51Y2yNdyMK29qclxghJzyDJRewFZSAEjM0/ilfd4v1xPk
# OKiE1Ua4E4bCG53qWjjdm9sCAwEAAaOCAYMwggF/MC8GCCsGAQUFBwEBBCMwITAf
# BggrBgEFBQcwAYYTaHR0cDovL3MyLnN5bWNiLmNvbTASBgNVHRMBAf8ECDAGAQH/
# AgEAMGwGA1UdIARlMGMwYQYLYIZIAYb4RQEHFwMwUjAmBggrBgEFBQcCARYaaHR0
# cDovL3d3dy5zeW1hdXRoLmNvbS9jcHMwKAYIKwYBBQUHAgIwHBoaaHR0cDovL3d3
# dy5zeW1hdXRoLmNvbS9ycGEwMAYDVR0fBCkwJzAloCOgIYYfaHR0cDovL3MxLnN5
# bWNiLmNvbS9wY2EzLWc1LmNybDAdBgNVHSUEFjAUBggrBgEFBQcDAgYIKwYBBQUH
# AwMwDgYDVR0PAQH/BAQDAgEGMCkGA1UdEQQiMCCkHjAcMRowGAYDVQQDExFTeW1h
# bnRlY1BLSS0xLTU2NzAdBgNVHQ4EFgQUljtT8Hkzl699g+8uK8zKt4YecmYwHwYD
# VR0jBBgwFoAUf9Nlp8Ld7LvwMAnzQzn6Aq8zMTMwDQYJKoZIhvcNAQELBQADggEB
# ABOFGh5pqTf3oL2kr34dYVP+nYxeDKZ1HngXI9397BoDVTn7cZXHZVqnjjDSRFph
# 23Bv2iEFwi5zuknx0ZP+XcnNXgPgiZ4/dB7X9ziLqdbPuzUvM1ioklbRyE07guZ5
# hBb8KLCxR/Mdoj7uh9mmf6RWpT+thC4p3ny8qKqjPQQB6rqTog5QIikXTIfkOhFf
# 1qQliZsFay+0yQFMJ3sLrBkFIqBgFT/ayftNTI/7cmd3/SeUx7o1DohJ/o39KK9K
# Er0Ns5cF3kQMFfo2KwPcwVAB8aERXRTl4r0nS1S+K4ReD6bDdAUK75fDiSKxH3fz
# vc1D1PFMqT+1i4SvZPLQFCEwggWaMIIDgqADAgECAgphGZPkAAAAAAAcMA0GCSqG
# SIb3DQEBBQUAMH8xCzAJBgNVBAYTAlVTMRMwEQYDVQQIEwpXYXNoaW5ndG9uMRAw
# DgYDVQQHEwdSZWRtb25kMR4wHAYDVQQKExVNaWNyb3NvZnQgQ29ycG9yYXRpb24x
# KTAnBgNVBAMTIE1pY3Jvc29mdCBDb2RlIFZlcmlmaWNhdGlvbiBSb290MB4XDTEx
# MDIyMjE5MjUxN1oXDTIxMDIyMjE5MzUxN1owgcoxCzAJBgNVBAYTAlVTMRcwFQYD
# VQQKEw5WZXJpU2lnbiwgSW5jLjEfMB0GA1UECxMWVmVyaVNpZ24gVHJ1c3QgTmV0
# d29yazE6MDgGA1UECxMxKGMpIDIwMDYgVmVyaVNpZ24sIEluYy4gLSBGb3IgYXV0
# aG9yaXplZCB1c2Ugb25seTFFMEMGA1UEAxM8VmVyaVNpZ24gQ2xhc3MgMyBQdWJs
# aWMgUHJpbWFyeSBDZXJ0aWZpY2F0aW9uIEF1dGhvcml0eSAtIEc1MIIBIjANBgkq
# hkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAryQICCl6NZ5gDKrnSztO3Hy8PEUcuyvg
# /ikC+VcIo2SFFSf18a3IMYldIugqqqZCs4/4uVW3sbdLs/6PfgdX7O9D22ZiFWHP
# YA2k2N744MNiCD1UE+tJyllUhSblK48bn+v1oZHCM0nYQ2NqUkvSj+hwUU3RiWl7
# x3D2s9wSdNt7XUtW05a/FXehsPSiJfKvHJJnGOX0BgTvkLnkAOTdOrUZ/wK69Dzu
# 4IvrN4vs9Nes8vbwPa/ddZEzGR0cQMt0JBkhk9kU/qwqUseP1QRJ5I1jR4g8aYPL
# /ke9K35PxZWuDp3U0UPAZ3PjFAh+5T+fc7gzCs9dPzSHloruU+glFQIDAQABo4HL
# MIHIMBEGA1UdIAQKMAgwBgYEVR0gADAPBgNVHRMBAf8EBTADAQH/MAsGA1UdDwQE
# AwIBhjAdBgNVHQ4EFgQUf9Nlp8Ld7LvwMAnzQzn6Aq8zMTMwHwYDVR0jBBgwFoAU
# YvsKIVt/Q24R2glUUGv10pZx8Z4wVQYDVR0fBE4wTDBKoEigRoZEaHR0cDovL2Ny
# bC5taWNyb3NvZnQuY29tL3BraS9jcmwvcHJvZHVjdHMvTWljcm9zb2Z0Q29kZVZl
# cmlmUm9vdC5jcmwwDQYJKoZIhvcNAQEFBQADggIBAIEqghaMNGcr5QPrNHuMoqNQ
# ivRVhvEejI6ufe4DGc5ylRhIrWIR/SD9P0cGAVri4G+MFSxOPGpQbAs2o896DZxC
# vFz4GdVg42nm4iNBZ4xog3Yrj5OjKrV/vln7qcmyJo/KovOCG5g+kZUnl4Zh7ltd
# B2vNhqjiZYCo4hXisr4jBWq6DPNHk02spIwHeTnAYRI6BQ2Jo+yfV4mE++zKfEdm
# FJHYtg8ZXea4Sqy8R8hxQ5bmMiCl3HeG/Tzji3Hbe5sD/LcdMmTrFlKgQ6P6Lq1Z
# kk58x/IzQkg4UTp8OMcbJCIoQB4aRh8X2xj38Cc1bLhj2c25ZF0rpV7vxim08sf4
# IcwEulf9Abarxmf559OZf/T1Ivpy9f3/OhxCOqH5gBil7o0c1GaeRQH+qu7/+xeP
# MPfxzSnFney11UkAPYW4y7uTOidqScAwrmbJ9yMoMnb5pINWyEjOWpaqoMwMxH+0
# jpevbeNUJ8OfhsDW5HMIlwXb0FRiXgNIwtWff6dmjNCdsE/U05hfS3rJf7IpUtAS
# gMcPVLYeZ83GoGwRA4TTSHXnKv6wO24KOqZrdpkFo/F3aGEzFEcG/FN/Ur2SFFxK
# JGpnjK+NkKrQ9nkhG5MmfMPOHr2IOJKuRcYZaklQswX4rlk3imolA5SxWYFQ6LqD
# gLcjNfR2uWcdWRitII2UMYIEVzCCBFMCAQEwgZMwfzELMAkGA1UEBhMCVVMxHTAb
# BgNVBAoTFFN5bWFudGVjIENvcnBvcmF0aW9uMR8wHQYDVQQLExZTeW1hbnRlYyBU
# cnVzdCBOZXR3b3JrMTAwLgYDVQQDEydTeW1hbnRlYyBDbGFzcyAzIFNIQTI1NiBD
# b2RlIFNpZ25pbmcgQ0ECEGU7whj/FuGac43A8LEm3mEwCQYFKw4DAhoFAKCBijAZ
# BgkqhkiG9w0BCQMxDAYKKwYBBAGCNwIBBDAcBgorBgEEAYI3AgELMQ4wDAYKKwYB
# BAGCNwIBFTAjBgkqhkiG9w0BCQQxFgQUmiN0ex0oJgIjBC9Rl1SitVtaEGEwKgYK
# KwYBBAGCNwIBDDEcMBqhGIAWaHR0cDovL3d3dy52bXdhcmUuY29tLzANBgkqhkiG
# 9w0BAQEFAASCAQCTtZ8xx22yCopxMlLowzdyKAg0dPxoZNaAc18O2Difi5NR9hXr
# pX9YU9+D2OrU8Ag1WTTs88k/AItedEyc8uaRBoqCgfbmYwJz0vB37qf7Q0wOTT5E
# ciBHKPVJbTpqgJpV8F3pwuE5iJnxdAFUqaonkO+4rItaaXsRNAS0655hQN1PFP1m
# zFkGyu6OsuePnh9riK+poHLwMewHYqQFj6EqeiBIx8tK+VEnasnlYU+s3zjpJoOl
# LS9yZACHs+2JlRLC4lrG+s1hQV9+0FXaNclPdIev5sEypIEuKlTGx0bYmvdP5ml+
# 9riUX3XMD8DoD6bbku1Ua5grsDfwciZ9bSmeoYICCzCCAgcGCSqGSIb3DQEJBjGC
# AfgwggH0AgEBMHIwXjELMAkGA1UEBhMCVVMxHTAbBgNVBAoTFFN5bWFudGVjIENv
# cnBvcmF0aW9uMTAwLgYDVQQDEydTeW1hbnRlYyBUaW1lIFN0YW1waW5nIFNlcnZp
# Y2VzIENBIC0gRzICEA7P9DjI/r81bgTYapgbGlAwCQYFKw4DAhoFAKBdMBgGCSqG
# SIb3DQEJAzELBgkqhkiG9w0BBwEwHAYJKoZIhvcNAQkFMQ8XDTE3MDQwNjEwMzUy
# OVowIwYJKoZIhvcNAQkEMRYEFAycjbU1rkM7+ZLGchS6PzGx7wqYMA0GCSqGSIb3
# DQEBAQUABIIBAGYvXvqeFRI6ZIUu+3C2hHGV/bAutBoBBaM6apOCeiA8dqQVMCF+
# EQu4cCqtKPQh0KtZpMSI+NzyT+r6EoE9nUCoUJfeopvvT/e54tdyyVazdLvHgROC
# r9liovD8c28mHKWY92hZGY8CDweXnV8lHhTNbqp9N6krPUIZlrDmhQ5PqjthsdDX
# ePdcAeKZsca9LlNCGd3A8u6qDbeZmHl4r8xyuxDTEXQBNuQAy2OBCx4TyBb3BSIE
# bA9DWzXe9xCIu9pnp1QbsAh6gEDbUrLwNZRSsYCgIM9AIzZx4R9ar5t6rYLO+jlN
# AfYtgtK/yM8WNFJ7+ad818CBC+HkRDuFJPw=
# SIG # End signature block
|
PowerShellCorpus/PowerShellGallery/DeploymentReadinessChecker/1.1.0/ReadinessValidationScript/Example.Tests.ps1
|
Example.Tests.ps1
|
#Requires -Modules 'Pester'
<#
PURPOSE: Pester script to validate that a machine meets the prerequisites for a software deployment/upgrade.
It generates a NUnit-style test result file for each computer and a summary report in HTML format.
This script is designed to be run remotely (not from the target machine).
#>
[CmdletBinding()]
Param(
[Parameter(Mandatory=$True)]
[ValidateScript({ Test-Connection -ComputerName $_ -Quiet })]
[string]$ComputerName,
[Parameter(Mandatory=$True)]
[pscredential]$Credential,
[Parameter(Mandatory=$True)]
[string]$DeploymentServerName,
[Parameter(Mandatory=$True)]
[string]$ManagementServerName
)
$RemoteSession = New-PSSession -ComputerName $ComputerName -Credential $Credential
Describe 'Hardware prerequisites' -Tag 'Hardware' {
It 'Has at least 4096 MB of total RAM' {
Invoke-Command -Session $RemoteSession {
(Get-CimInstance -ClassName Win32_PhysicalMemory).Capacity / 1MB } |
Should Not BeLessThan 4096
}
}
Describe 'Networking prerequisites' -Tag 'Networking' {
It 'Can ping the Management server by name' {
Invoke-Command -Session $RemoteSession { param($ManagementServerName)
Test-Connection -ComputerName $ManagementServerName -Quiet } -ArgumentList $ManagementServerName |
Should Be $True
}
It 'Can ping the Deployment server by name' {
Invoke-Command -Session $RemoteSession { param($DeploymentServerName)
Test-Connection -ComputerName $DeploymentServerName -Quiet } -ArgumentList $DeploymentServerName |
Should Be $True
}
It 'Has connectivity to the Management server on TCP port 80' {
Invoke-Command -Session $RemoteSession { param($ManagementServerName)
(Test-NetConnection -ComputerName $ManagementServerName -CommonTCPPort HTTP).TcpTestSucceeded } -ArgumentList $ManagementServerName |
Should Be $True
}
It 'Has the firewall profile set to "Domain" or "Private"' {
Invoke-Command -Session $RemoteSession {
$FirewallProfile = (Get-NetConnectionProfile)[0].NetworkCategory.ToString();
$FirewallProfile -eq 'Domain' -or $FirewallProfile -eq 'Private' } |
Should Be $True
}
}
Describe 'OS and runtime prerequisites' -Tag 'OS' {
It 'Has the Windows Update KB2883200' {
Invoke-Command -Session $RemoteSession {
Get-HotFix -Id KB2883200 -ErrorAction SilentlyContinue } |
Should Not BeNullOrEmpty
}
It 'Has the required version of the C++ 2010 runtime' {
Invoke-Command -Session $RemoteSession {
Get-CimInstance -ClassName Win32_Product -Filter "Name='Microsoft Visual C++ 2010 x64 Redistributable - 10.0.40219'" } |
Should Not BeNullOrEmpty
}
It 'Has the shell set to "explorer.exe" at the global level (HKLM)' {
Invoke-Command -Session $RemoteSession {
(Get-ItemProperty -Path 'HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Winlogon').Shell } |
Should Be 'explorer.exe'
}
}
Describe 'PowerShell prerequisites' {
It 'Has the execution policy set to "RemoteSigned" or "Unrestricted"' {
Invoke-Command -Session $RemoteSession {
$Policy = (Get-ExecutionPolicy); $Policy -eq 'RemoteSigned' -or $Policy -eq 'Unrestricted' } |
Should Be $True
}
It 'Has PowerShell version 4.0 or later' {
Invoke-Command -Session $RemoteSession {
$PSVersionTable.PSVersion -ge [System.Version]'4.0' } |
Should Be $True
}
It 'Has the PackageManagement module installed' {
Invoke-Command -Session $RemoteSession {
Get-Module -Name 'PackageManagement' -ListAvailable } |
Should Not BeNullOrEmpty
}
It 'Has Chocolatey in its registered package sources for the provider "Chocolatey"' {
Invoke-Command -Session $RemoteSession {
Get-PackageSource -Name Chocolatey -ProviderName Chocolatey } |
Should Not BeNullOrEmpty
}
}
|
PowerShellCorpus/PowerShellGallery/DeploymentReadinessChecker/1.1.0/Tests/Unit/DeploymentReadinessChecker.Tests.ps1
|
DeploymentReadinessChecker.Tests.ps1
|
Import-Module "$($PSScriptRoot)\..\..\DeploymentReadinessChecker.psd1" -Force
$ModuleName = 'DeploymentReadinessChecker'
$OutputPath = 'TestDrive:\OutputFolder'
$ComputerNames = 'Computer1','Computer2','Computer3'
$ScriptInfo = Get-Command (Get-ChildItem -Path "$PSScriptRoot\..\..\ReadinessValidationScript\" -Filter '*.Tests.ps1')[0].FullName
Describe 'General Module behaviour' {
$ModuleInfo = Get-Module -Name $ModuleName
It 'Exports only the function "Test-DeploymentReadiness"' {
$ModuleInfo.ExportedFunctions.Values.Name |
Should Be 'Test-DeploymentReadiness'
}
It 'Exports only the alias "tdr"' {
$ModuleInfo.ExportedAliases.Values.Name |
Should Be 'tdr'
}
It 'The only required module should be Pester' {
$ModuleInfo.RequiredModules.Name |
Should Be 'Pester'
}
}
Describe 'Test-DeploymentReadiness' {
Context 'Parameters behaviour' {
Mock -ModuleName $ModuleName Invoke-Pester { }
Mock -ModuleName $ModuleName Get-ChildItem { } -ParameterFilter {$Path -eq "$OutputPath\Index.html"}
Mock -ModuleName $ModuleName Invoke-ReportUnit { }
It "If the directory specified via the parameter 'OutputPath' doesn't exist, it should create it" {
Test-DeploymentReadiness -ComputerName $ComputerNames[0] -OutputPath $OutputPath
Test-Path -Path $OutputPath -PathType Container |
Should Be $True
}
It 'Should call Invoke-Pester once per Computer specified via the ComputerName parameter' {
Test-DeploymentReadiness -ComputerName $ComputerNames -OutputPath $OutputPath
Assert-MockCalled Invoke-Pester -Exactly 3 -Scope It -ModuleName $ModuleName
}
It 'Should call Invoke-Pester once per Computer specified via pipeline input' {
$ComputerNames | Test-DeploymentReadiness -OutputPath $OutputPath
Assert-MockCalled Invoke-Pester -Exactly 3 -Scope It -ModuleName $ModuleName
}
It 'If the Credential parameter is specified, it should add it into the Script parameter of Invoke-Pester' {
$Password = ConvertTo-SecureString 'TestPasswd' -AsPlainText -Force
$TestCred = New-Object System.Management.Automation.PSCredential ('TestUser', $Password)
Test-DeploymentReadiness -ComputerName $ComputerNames -OutputPath $OutputPath -Credential $TestCred
Assert-MockCalled Invoke-Pester -Scope It -ModuleName $ModuleName -ParameterFilter {
$Script.Parameters.Credential -eq $TestCred
}
}
It 'If the TestParameters parameter is specified, it should add all its key-value pairs into the Script parameter of Invoke-Pester' {
$TestParams = @{PesterScriptParam1 = 'Param1Value'
PesterScriptParam2 = 'Param2Value'
}
Test-DeploymentReadiness -ComputerName $ComputerNames[0] -TestParameters $TestParams
Foreach ( $Key in $TestParams.Keys ) {
Assert-MockCalled Invoke-Pester -Scope It -ModuleName $ModuleName -ParameterFilter {
$Script.Parameters.$Key -eq $TestParams.$Key
}
}
}
It 'Should pass all values in the Tag parameter to Invoke-Pester' {
$TestTags = 'Tag1','Tag2','Tag3'
Test-DeploymentReadiness -ComputerName $ComputerNames[0] -Tag $TestTags
Foreach ( $TestTag in $TestTags ) {
Assert-MockCalled Invoke-Pester -Scope It -ModuleName $ModuleName -ParameterFilter {
$Tag -contains $TestTag
}
}
}
It 'Should pass all values in the ExcludeTag parameter to Invoke-Pester' {
$TestExcludeTags = 'ExcludeTag1','ExcludeTag2'
Test-DeploymentReadiness -ComputerName $ComputerNames[0] -ExcludeTag $TestExcludeTags
Foreach ( $TestExcludeTag in $TestExcludeTags ) {
Assert-MockCalled Invoke-Pester -Scope It -ModuleName $ModuleName -ParameterFilter {
$ExcludeTag -contains $TestExcludeTag
}
}
}
}
Context 'General Function behaviour' {
Mock -ModuleName $ModuleName Invoke-Pester { }
Mock -ModuleName $ModuleName Get-ChildItem { } -ParameterFilter {$Path -eq "$OutputPath\Index.html"}
Mock -ModuleName $ModuleName Invoke-ReportUnit { }
It 'Should call ReportUnit only once, even when there are multiple computers' {
Test-DeploymentReadiness -ComputerName $ComputerNames -OutputPath $OutputPath
Assert-MockCalled Invoke-ReportUnit -Exactly 1 -Scope It -ModuleName $ModuleName
}
It 'Should call ReportUnit only once, even with multiple computers specified via pipeline input' {
$ComputerNames | Test-DeploymentReadiness -OutputPath $OutputPath
Assert-MockCalled Invoke-ReportUnit -Exactly 1 -Scope It -ModuleName $ModuleName
}
}
}
Describe 'Dynamic parameter "ValidationScript"' {
Mock -ModuleName $ModuleName Invoke-Pester { }
Mock -ModuleName $ModuleName Get-ChildItem { } -ParameterFilter {$Path -eq "$OutputPath\Index.html"}
Mock -ModuleName $ModuleName Get-ChildItem {
[PSCustomObject]@{ FullName = 'TestDrive:\Example1.Tests.ps1'; Name = 'Example1.Tests.ps1' },
[PSCustomObject]@{ FullName = 'TestDrive:\Example2.Tests.ps1'; Name = 'Example2.Tests.ps1' }
} -ParameterFilter {$Path -like '*ReadinessValidationScript*' -and $Filter -eq '*.Tests.ps1'}
Mock -ModuleName $ModuleName Invoke-ReportUnit { }
Mock -ModuleName $ModuleName Get-Command { $ScriptInfo }
It "Should throw when the value for the ValidationScript doesn't belong to the ValidateSet" {
{Test-DeploymentReadiness -ComputerName $ComputerNames[0] -ValidationScript 'NotThere.Tests.ps1'} |
Should Throw 'does not belong to the set "Example1.Tests.ps1,Example2.Tests.ps1"'
}
It 'Should call Invoke-Pester with the validation script specified via the ValidationScript parameter' {
Test-DeploymentReadiness -ComputerName $ComputerNames[0] -ValidationScript 'Example1.Tests.ps1'
Assert-MockCalled Invoke-Pester -Scope It -ModuleName $ModuleName -ParameterFilter {
$Script.Path -like '*\ReadinessValidationScript\Example1.Tests.ps1'
}
}
}
Describe 'Invoke-ReportUnit' {
InModuleScope $ModuleName {
$OutputPath = 'TestDrive:\OutputFolder'
Mock Invoke-Pester { }
Mock Get-ChildItem { } -ParameterFilter {$Path -eq "$OutputPath\Index.html"}
Mock Write-Host { }
It 'Should call Get-ChildItem on "$OutputPath\Index.html"' {
Invoke-ReportUnit -OutputPath $OutputPath
Assert-MockCalled Get-ChildItem -Scope It -ParameterFilter {
$Path -eq "$OutputPath\Index.html"
}
}
}
}
|
PowerShellCorpus/PowerShellGallery/ActiveDirectoryFever/1.0.0/Functions/Get-ADDirSyncChange.ps1
|
Get-ADDirSyncChange.ps1
|
<#
.SYNOPSIS
Use the DirSync function of Active Directory to monitor the changes.
.DESCRIPTION
Use the DirSync function of Active Directory to monitor the changes. To use
this functionality, the user needs 'Domain Administrators' privileges or
the 'Replication directory changes' is delegated to the user on the domain
level.
.PARAMETER Partition
Define the target partition to monitor the changes.
.PARAMETER ComputerName
Define the computer names for the Domain Controllers where the changes
were monitored.
.PARAMETER FilterRegex
Filter the objects inside the partition based on the distinguished name
with a regex filter. With the default filter value, all objects will be
displayed.
.PARAMETER FilterWildcard
Filter the objects inside the partition based on the distinguished name
with a wildcard filter. With the default filter value, all objects will
be displayed.
.PARAMETER CookieFile
The path to the cookie file. If the cookie exist, the current USN number
per domain controller will be loaded and the update scripts starts at
this USN number. If no file exists, a new cookie file will be created.
If no path will be specified, no cookie file will be used.
.PARAMETER CookieReadOnly
If this switch is specified, the cookie file will only be readed and not
updated with the new USN numbers.
.PARAMETER Once
The script executs only one search loop.
.EXAMPLE
C:\> Get-ADDirSyncChange
Start change monitoring with default values.
.EXAMPLE
C:\> Get-ADDirSyncChange -Partition 'DC=adds,DC=contoso,DC=com' -ComputerName 'DC21.adds.contoso.com'
Endless change monitoring every second inside the given partition targeting the DC21 domain controller.
.EXAMPLE
C:\> Get-ADDirSyncChange -Partition 'DC=adds,DC=contoso,DC=com' -ComputerName 'DC21.adds.contoso.com' -CookieFile 'cookie.xml' -Once
Create a cookie file for the current state of the partition.
.EXAMPLE
C:\> Get-ADDirSyncChange -Partition 'DC=adds,DC=contoso,DC=com' -ComputerName 'DC21.adds.contoso.com' -CookieFile 'cookie.xml' -CookieReadOnly -Once
Get all changes inside the partition which has been performed since the cookie creation. Preserve the cookie value.
.EXAMPLE
C:\> Get-ADDirSyncChange -Partition 'DC=adds,DC=contoso,DC=com' -FilterWildcard '*OU=Test,DC=adds,DC=contoso,DC=com'
Endless change monitoring but only for the test OU. With this filter, deleting objects is not reported.
.NOTES
Author : Claudio Spizzi
License : MIT License
Source : Microsoft Exchange FAQ, Author: Frank Carius, Website: http://www.msxfaq.de
This function is a complete rewrite of the original script 'Get-ADChanges'
provided by Frank Carius. Credits for initial concept and idea goes to him.
.LINK
https://github.com/claudiospizzi/ActiveDirectoryFever
.LINK
http://www.msxfaq.de/tools/exprivat/get-adchanges.htm
#>
function Get-ADDirSyncChange
{
[CmdletBinding()]
param
(
[Parameter(Mandatory=$false)]
[String] $Partition = ([ADSI] "LDAP://$env:USERDOMAIN/RootDSE").DefaultNamingContext,
[Parameter(Mandatory=$false)]
[String[]] $ComputerName = ([ADSI] "LDAP://$env:USERDOMAIN/RootDSE").DnsHostName,
[Parameter(Mandatory=$false)]
[String] $FilterRegex = ".*",
[Parameter(Mandatory=$false)]
[String] $FilterWildcard = "*",
[Parameter(Mandatory=$false)]
[AllowEmptyString()]
[String] $CookieFile = "",
[Parameter(Mandatory=$false)]
[Switch] $CookieReadOnly,
[Parameter(Mandatory=$false)]
[Switch] $Once
)
begin
{
# Counter variable to display the progress bar
$Count = 0
# Global hashtables to save the cookies and the serarcher objects per domain controller
$Cookie = @{}
$Searcher = @{}
# The Active Directory properties to load
$Properties = "WhenChanged", "ObjectCategory", "ObjectSID"
$CommonProperties = "", "ObjectGuid", "ParentGuid", "InstanceType", "DistinguishedName", "AdsPath", "Name", "IsDeleted", "LastKnownParent", "msds-LastKnownRDN"
# Check the cookie file variable
# - No path specified: Do not use a cookie file and do not store the USN numbers
# - Path specified, file existing: Load the latest USN numbers from the cookie file
# - Path specified, file not found: Create a new cookie file but start at the lastest USN number on the Domain Controller
if ($CookieFile -ne "" -and (Test-Path -Path $CookieFile))
{
try
{
$Cookie = [Hashtable] (Import-Clixml -Path $CookieFile)
}
catch
{
Write-Error "Error while loading the cookie file: $_"
return
}
}
# Initialize the directory searcher object for each Domain Controller. Define the searcher to point
# to the correct partition on the specified Domain Controllers and set the necessary properties.
foreach ($Computer in $ComputerName)
{
# If no DirSync cookie exists, create an empty array
if (-not $Cookie.ContainsKey($Computer))
{
$Cookie[$Computer] = @()
}
# Initialize directory searcher
$Searcher[$Computer] = New-Object -TypeName System.DirectoryServices.DirectorySearcher -ArgumentList ([ADSI] "LDAP://${Computer}/${Partition}")
$Searcher[$Computer].DirectorySynchronization = New-Object -TypeName System.DirectoryServices.DirectorySynchronization([System.DirectoryServices.DirectorySynchronizationOptions]::IncrementalValues, [System.Convert]::FromBase64String($Cookie[$Computer]))
$Searcher[$Computer].Filter = "(objectClass=*)"
# If the DirSync cookie is empty, initialize the DirSync cookie to the current value
if ($Cookie[$Computer].Count -eq 0)
{
# Set the filter temporary to exclude all objects, load all objects (ignore the result) and reset the filter
$Searcher[$Computer].Filter = "(objectClass=#)"
$Searcher[$Computer].FindAll() | Out-Null
$Searcher[$Computer].Filter = "(objectClass=*)"
# Update the cookie
$Cookie[$Computer] = [System.Convert]::ToBase64String($Searcher[$Computer].DirectorySynchronization.GetDirectorySynchronizationCookie())
}
}
}
process
{
do
{
# Iteratin Level 1: Computer
foreach ($Computer in $ComputerName)
{
Write-Progress -Activity "Active Directory Update Searcher..." -Status "Search for DirSync changes in $Partition on $Computer" -PercentComplete (($Count++) % 100)
# Execute the search for DirSync changes
$SearchResult = $Searcher[$Computer].FindAll()
# Filter search result with input filter (regex & wildcard)
$SearchFilter = $SearchResult | Where-Object { $_.Properties["DistinguishedName"] -like $FilterWildcard -and $_.Properties["DistinguishedName"] -match $FilterRegex }
# Iterating all result objects, parse the properties and return a object to the pipeline
if ($SearchFilter.Count -gt 0)
{
# Iteratin Level 2: Search result objects
foreach ($SearchObject in $SearchFilter)
{
# Verify if the object is deleted
if ($SearchObject.Path -like "*,CN=Deleted Objects,*")
{
# Search the deleted object
$DeletedSearcher = New-Object -TypeName System.DirectoryServices.DirectorySearcher -ArgumentList ([ADSI] "LDAP://${Computer}/${Partition}")
$DeletedSearcher.Tombstone = $true
$DeletedSearcher.Filter = "(&(objectClass=*)(isDeleted=TRUE)(name=$($SearchObject.Properties['Name'][0])))"
$SearchObjectFull = $DeletedSearcher.FindOne()
}
else
{
# Search the full object
$SearchObjectFull = ([ADSI] "LDAP://$Computer/$($SearchObject.Properties["DistinguishedName"][0])")
}
# Define common properties for the change object
$CommonParameter = @{
Timestamp = $SearchObjectFull.Properties["WhenChanged"][0]
ObjectClass = $SearchObjectFull.Properties["ObjectCategory"][0] + ""
ObjectGuid = $SearchObject.Properties["ObjectGUID"][0]
ObjectSid = (New-Object -TypeName "System.Security.Principal.SecurityIdentifier" -ArgumentList ($SearchObjectFull.Properties["ObjectSID"][0]) , 0)
Identity = $SearchObject.Properties["DistinguishedName"][0]
Account = $SearchObjectFull.Properties["SamAccountName"][0]
}
if ($SearchObject.Properties.Contains("IsDeleted") -and $SearchObject.Properties.Item("IsDeleted") -eq $true)
{
# Action: DELETE
New-ADChangeObject @CommonParameter -Action DELETE -Field "LastKnownDN" -Value "CN=$($SearchObject.Properties.Item('msds-LastKnownRDN')),$($SearchObject.Properties.Item('LastKnownParent'))"
}
elseif ($SearchObject.Properties.Contains("IsDeleted"))
{
# Action: RESTORE
New-ADChangeObject @CommonParameter -Action RESTORE -Field "ParentGuid" -Value ([String] [Guid] $SearchObject.Properties.Item("ParentGuid")[0])
}
elseif ($SearchObject.Properties.Contains("ParentGuid") -and $SearchObject.Properties.Contains("WhenCreated"))
{
# Action: CREATE
New-ADChangeObject @CommonParameter -Action CREATE -Field "ParentGuid" -Value ([String] [Guid] $SearchObject.Properties.Item("ParentGuid")[0])
}
elseif ($SearchObject.Properties.Contains("ParentGuid"))
{
# Action: MOVE
New-ADChangeObject @CommonParameter -Action MOVE -Field "ParentGuid" -Value ([String] [Guid] $SearchObject.Properties.Item("ParentGuid")[0])
}
# Iterating all modified properties without common properties
foreach ($Property in ($SearchObject.Properties.PropertyNames | Where-Object { $CommonProperties -notcontains $_ }))
{
switch -Wildcard ($Property)
{
"member;range=1-1"
{
foreach ($Member in $SearchObject.Properties.Item("member;range=1-1"))
{
# Action: MEMBER ADD
New-ADChangeObject @CommonParameter -Action MEMBER-ADD -Field "Member" -Value $Member
# Action: MEMBEROF ADD
# TODO
}
break
}
"member;range=0-0"
{
foreach ($Member in $SearchObject.Properties.Item("member;range=0-0"))
{
# Action: MEMBER REMOVE
New-ADChangeObject @CommonParameter -Action MEMBER-REMOVE -Field "Member" -Value $Member
# Action: MEMBEROF REMOVE
# TODO
}
break
}
"member;range=*"
{
# Action: MEMBER ERROR
New-ADChangeObject @CommonParameter -Action UNKNOWN -Field $Property -Value $SearchObject.Properties.Item($Property)
break
}
"*;range=1-1"
{
# Action: CUSTOM ADD
New-ADChangeObject @CommonParameter -Action CUSTOM-ADD -Field $Property.Replace(';range=1-1', '') -Value $SearchObject.Properties.Item($Property)
break
}
"*;range=0-0"
{
# Action: CUSTOM REMOVE
New-ADChangeObject @CommonParameter -Action CUSTOM-REMOVE -Field $Property.Replace(';range=1-1', '') -Value $SearchObject.Properties.Item($Property)
break
}
default
{
# Action: MODIFY
New-ADChangeObject @CommonParameter -Action MODIFY -Field $Property -Value $SearchObject.Properties.Item($Property)
}
}
}
}
# Update cookie value
$Cookie[$Computer] = [System.Convert]::ToBase64String($Searcher[$Computer].DirectorySynchronization.GetDirectorySynchronizationCookie())
}
# Update the cookie file if necessary
if (($CookieFile -ne "") -and (-not $CookieReadOnly))
{
$Cookie | Export-Clixml -Path $CookieFile -Encoding Unicode
}
}
Start-Sleep -Seconds 1
}
until ($Once)
}
end
{
}
}
|
PowerShellCorpus/PowerShellGallery/ActiveDirectoryFever/1.0.0/Functions/Test-ADDomainControllerDiagnostic.ps1
|
Test-ADDomainControllerDiagnostic.ps1
|
<#
.SYNOPSIS
Health test of Active Directory Domain Controllers by using the built-in
and trusted "dcdiag.exe" command line tool.
.DESCRIPTION
This function uses Windows PowerShell Remoting to connect to all specified
Active Directory Domain Controllers. Inside the session, dcdiag is executed
with best practice parameter values. The result is then parsed into
Windows PowerShell custom objects.
.PARAMETER ComputerName
The list of Domain Controllers to test. Aliases are defined to accept
pipeline input from the result of the Active Directory built-in cmdlets.
.PARAMETER Credential
Optionally, provide credentials to create the PowerShell Remoting session.
.INPUTS
System.String. You can pipe an array of strings representing the computer names.
.OUTPUTS
ActiveDirectoryFever.DiagnosticResult. A collection of result objects. One object per test.
.EXAMPLE
C:\> Test-ADDomainControllerDiagnostic -ComputerName LON-DC1.contoso.com
Run the diagnostic test against one Domain Controller.
.EXAMPLE
C:\> Test-ADDomainControllerDiagnostic -ComputerName LON-DC1.contoso.com -Credential (Get-Credential)
Run the diagnostic test against one Domain Controller by using custom credentials.
.EXAMPLE
C:\> Test-ADDomainControllerDiagnostic -ComputerName LON-DC1, LON-DC2 | Where-Object { -not $_.Result }
Run the diagnostic test against two Domain Controllers and filter failed tests.
.EXAMPLE
C:\> Get-ADDomainController | Test-ADDomainControllerDiagnostic
Run the diagnostic test on the current enumerated Domain Controller.
.EXAMPLE
C:\> Get-ADDomain -Identity "corp.contoso.com" | Test-ADDomainControllerDiagnostic
Run the diagnostic test on all writable and read-only Domain Controllers in the "corp.contoso.com" domain.
.EXAMPLE
C:\> Get-ADForest -Identity "contoso.com" | Test-ADDomainControllerDiagnostic
Run the diagnostic test on all Global Catalog Domain Controllers in the "contoso.com" forest.
.NOTES
Author : Claudio Spizzi
License : MIT License
.LINK
https://github.com/claudiospizzi/ActiveDirectoryFever
#>
function Test-ADDomainControllerDiagnostic
{
[CmdletBinding()]
param
(
[Parameter(Mandatory=$true,
ValueFromPipeline=$true,
ValueFromPipelineByPropertyName=$true)]
[Alias('HostName', 'DNSHostName', 'ReplicaDirectoryServers', 'GlobalCatalogs')]
[String[]] $ComputerName,
[Parameter(Mandatory=$false)]
[PSCredential] $Credential = $null
)
begin
{
$Jobs = @()
# Define the alternate credentials hash table
$CredentialParameter = @{}
if($Credential -ne $null) { $CredentialParameter['Credential'] = $Credential }
}
process
{
# For each provided computer name, use it as target to start the dcdiag
# command inside a remoting session and as a job. This allows parallel
# executing of all dcdiag commands.
foreach ($ComputerNameTarget in $ComputerName)
{
Write-Verbose -Message "Start Job to execute 'dcdiag.exe /v /c /Skip:OutboundSecureChannels' on $ComputerNameTarget with PowerShell Remoting..."
$Jobs += Invoke-Command -ComputerName $ComputerNameTarget -ScriptBlock { Write-Output (dcdiag.exe /v /c /Skip:OutboundSecureChannels) } @CredentialParameter -AsJob -JobName $ComputerNameTarget
}
}
end
{
Write-Verbose -Message 'Wait for all Jobs to complete.'
# Wait for all jobs to complete
$Jobs = $Jobs | Wait-Job
# Iterate all child jobs (one child job per domain controller)
foreach ($Job in $Jobs)
{
try
{
if ($Job.State -eq 'Completed')
{
# Fill name and domain with location
$Name = $Job.Name.Split('.', 2)[0]
$Domain = $(try { $Job.Name.Split('.', 2)[1] } catch { '' })
# Receive result (and error, if occured)
$Result = $Job | Receive-Job -ErrorAction Stop
# Iterating all lines
for ($Line = 0; $Line -lt $Result.length; $Line++)
{
# Correct wrong line breaks
if ($Result[$Line] -match '^\s{9}.{25} (\S+) (\S+) test$')
{
$Result[$Line] = $Result[$Line] + ' ' + $Result[$Line + 2].Trim()
}
# Verify test start line
if ($Result[$Line] -match '^\s{6}Starting test: \S+$')
{
$LineStart = $Line
}
# Verify test end line
if ($Result[$Line] -match '^\s{9}.{25} (\S+) (\S+) test (\S+)$')
{
# Create a custom result object with custom type
$DiagnosticResult = New-Object -TypeName PSObject -Property @{
Name = $Name
Domain = $Domain
Target = $Matches[1]
Test = $Matches[3]
Result = $Matches[2] -eq 'passed'
Data = $Result[$LineStart..$Line] -join [System.Environment]::NewLine
}
$DiagnosticResult.PSTypeNames.Insert(0, 'ActiveDirectoryFever.DiagnosticResult')
Write-Output $DiagnosticResult
}
}
}
else
{
$Job | Receive-Job -ErrorAction Stop | Out-Null
}
}
catch
{
Write-Error -Message "Failed to execute diagnistic test.`r`n$_" -Exception $_.Exception -TargetObject $Job.Location
}
}
# Cleanup jobs
$Job | Remove-Job -ErrorAction SilentlyContinue
}
}
|
PowerShellCorpus/PowerShellGallery/ActiveDirectoryFever/1.0.0/Functions/Test-ADDomainControllerReplication.ps1
|
Test-ADDomainControllerReplication.ps1
|
<#
.SYNOPSIS
Replication test of Active Directory Domain Controllers by using the
build-in and trusted "repadmin.exe" command line tool.
.DESCRIPTION
This function uses Windows PowerShell Remoting to connect to all specified
Active Directory Domain Controllers. Inside the session, repadmin is
executed with the /showrepl and /csv parameter. The result is then parsed
into Windows PowerShell custom objects.
.PARAMETER ComputerName
The list of Domain Controllers to test. Aliases are defined to accept
pipeline input from the result of the Active Directory built-in cmdlets.
.PARAMETER Credential
Optionally, provide credentials to create the PowerShell Remoting session.
.INPUTS
System.String. You can pipe an array of strings representing the computer names.
.OUTPUTS
ActiveDirectoryFever.ReplicationResult. A collection of result objects. One object per test.
.EXAMPLE
C:\> Test-ADDomainControllerReplication -ComputerName LON-DC1.contoso.com
Run the replication test against one Domain Controller.
.EXAMPLE
C:\> Test-ADDomainControllerReplication -ComputerName LON-DC1.contoso.com -Credential (Get-Credential)
Run the replication test against one Domain Controller by using custom credentials.
.EXAMPLE
C:\> Test-ADDomainControllerReplication -ComputerName LON-DC1, LON-DC2 | Where-Object { -not $_.Result }
Run the replication test against two Domain Controllers and filter failed tests.
.EXAMPLE
C:\> Get-ADDomainController | Test-ADDomainControllerReplication
Run the replication test on the current enumerated Domain Controller.
.EXAMPLE
C:\> Get-ADDomain -Identity "corp.contoso.com" | Test-ADDomainControllerReplication
Run the replication test on all writable and read-only Domain Controllers in the "corp.contoso.com" domain.
.EXAMPLE
C:\> Get-ADForest -Identity "contoso.com" | Test-ADDomainControllerReplication
Run the replication test on all Global Catalog Domain Controllers in the "contoso.com" forest.
.NOTES
Author : Claudio Spizzi
License : MIT License
.LINK
https://github.com/claudiospizzi/ActiveDirectoryFever
#>
function Test-ADDomainControllerReplication
{
[CmdletBinding()]
param
(
[Parameter(Mandatory=$true,
ValueFromPipeline=$true,
ValueFromPipelineByPropertyName=$true)]
[Alias('HostName', 'DNSHostName', 'ReplicaDirectoryServers', 'GlobalCatalogs')]
[String[]] $ComputerName,
[Parameter(Mandatory=$false)]
[PSCredential] $Credential = $null
)
begin
{
$Jobs = @()
# Define the alternate credentials hash table
$CredentialParameter = @{}
if($Credential -ne $null) { $CredentialParameter['Credential'] = $Credential }
}
process
{
# For each provided computer name, use it as target to start the replsum
# command inside a remoting session and as a job. This allows parallel
# executing of all replsum commands.
foreach ($ComputerNameTarget in $ComputerName)
{
Write-Verbose -Message "Start Job to execute 'repadmin.exe /showrepl /csv' on $ComputerNameTarget with PowerShell Remoting..."
$Jobs += Invoke-Command -ComputerName $ComputerNameTarget -ScriptBlock { Write-Output (repadmin.exe /showrepl /csv) } @CredentialParameter -AsJob -JobName $ComputerNameTarget
}
}
end
{
Write-Verbose -Message 'Wait for all Jobs to complete.'
# Wait for all jobs to complete
$Jobs = $Jobs | Wait-Job
# Iterate all child jobs (one child job per domain controller)
foreach ($Job in $Jobs)
{
try
{
if ($Job.State -eq 'Completed')
{
# Fill name and domain with location
$Name = $Job.Name.Split('.', 2)[0]
$Domain = try { $Job.Name.Split('.', 2)[1] } catch { '' }
# Receive result (and error, if occured)
$Result = $Job | Receive-Job -ErrorAction Stop
# Check if the result is empty
if ($Result -ne $null)
{
# Iterating all objects
foreach ($ChildResult in ($Result | ConvertFrom-Csv))
{
# Calculate last execution time
$LastTime = [DateTime]::MinValue
if (($ChildResult.'Last Failure Time' -ne '0') -and ($LastTime -lt ($LastFailureTime = [DateTime] $ChildResult.'Last Failure Time')))
{
$LastTime = $LastFailureTime
}
if (($ChildResult.'Last Success Time' -ne '0') -and ($LastTime -lt ($LastSuccessTime = [DateTime] $ChildResult.'Last Success Time')))
{
$LastTime = $LastSuccessTime
}
# Create a custom result object with custom type
$ReplicationResult = New-Object -TypeName PSObject -Property @{
Name = $Name
Domain = $Domain
NamingContext = $ChildResult.'Naming Context'
SourceSite = $ChildResult.'Source DSA Site'
SourceServer = $ChildResult.'Source DSA'
TargetSite = $ChildResult.'Destination DSA Site'
TargetServer = $ChildResult.'Destination DSA'
ExecutionTime = $LastTime
TransportType = $ChildResult.'Transport Type'
FailureCount = $ChildResult.'Number of Failures'
FailureStatus = $ChildResult.'Last Failure Status'
Result = $ChildResult.'Number of Failures' -eq '0'
}
$ReplicationResult.PSTypeNames.Insert(0, 'ActiveDirectoryFever.ReplicationResult')
Write-Output $ReplicationResult
}
}
else
{
Write-Warning "Replication test on $($Job.Location) does not return any data. This is expected, if the forest does only consist of one Domain Controller."
}
}
else
{
$Job | Receive-Job -ErrorAction Stop | Out-Null
}
}
catch
{
Write-Error -Message "Failed to execute diagnistic test.`r`n$_" -Exception $_.Exception -TargetObject $Job.Location
}
}
# Cleanup jobs
$Job | Remove-Job -ErrorAction SilentlyContinue
}
}
|
PowerShellCorpus/PowerShellGallery/ActiveDirectoryFever/1.0.0/Functions/Get-ADUsnNumberUpdate.ps1
|
Get-ADUsnNumberUpdate.ps1
|
<#
.SYNOPSIS
Uses the USN propertiy of Active Directory to monitor the updates.
.DESCRIPTION
Uses the update sequence number (USN) propertiy of Active Directory to
monitor the updates. Whenever an object is changed, its USN is incremented.
Each domain controller maintains its own USN, they cannot be conpared
between each other.
.PARAMETER Partition
Define the target partition to monitor the changes.
.PARAMETER ComputerName
Define the computer names for the Domain Controllers where the changes
were monitored.
.PARAMETER FilterRegex
Filter the objects inside the partition based on the distinguished name
with a regex filter. With the default filter value, all objects will be
displayed.
.PARAMETER FilterWildcard
Filter the objects inside the partition based on the distinguished name
with a wildcard filter. With the default filter value, all objects will
be displayed.
.PARAMETER CookieFile
The path to the cookie file. If the cookie exist, the current USN number
per domain controller will be loaded and the update scripts starts at
this USN number. If no file exists, a new cookie file will be created.
If no path will be specified, no cookie file will be used.
.PARAMETER CookieReadOnly
If this switch is specified, the cookie file will only be readed and not
updated with the new USN numbers.
.PARAMETER Once
The script executs only one search loop.
.EXAMPLE
C:\> Get-ADUsnNumberUpdate
Start change monitoring with default values.
.EXAMPLE
C:\> Get-ADUsnNumberUpdate -Partition 'DC=adds,DC=contoso,DC=com' -ComputerName 'DC21.adds.contoso.com'
Endless change monitoring every second inside the given partition targeting the DC21 domain controller.
.EXAMPLE
C:\> Get-ADUsnNumberUpdate -Partition 'DC=adds,DC=contoso,DC=com' -ComputerName 'DC21.adds.contoso.com' -CookieFile 'cookie.xml' -Once
Create a cookie file for the current state of the partition.
.EXAMPLE
C:\> Get-ADUsnNumberUpdate -Partition 'DC=adds,DC=contoso,DC=com' -ComputerName 'DC21.adds.contoso.com' -CookieFile 'cookie.xml' -CookieReadOnly -Once
Get all changes inside the partition which has been performed since the cookie creation. Preserve the cookie value.
.EXAMPLE
C:\> Get-ADUsnNumberUpdate -Partition 'DC=adds,DC=contoso,DC=com' -FilterWildcard '*OU=Test,DC=adds,DC=contoso,DC=com'
Endless change monitoring but only for the test OU. With this filter, deleting objects is not reported.
.NOTES
Author : Claudio Spizzi
License : MIT License
Source : Microsoft Exchange FAQ, Author: Frank Carius, Website: http://www.msxfaq.de
This function is a complete rewrite of the original script 'Get-USNChanges'
provided by Frank Carius. Credits for initial concept and idea goes to him.
.LINK
https://github.com/claudiospizzi/ActiveDirectoryFever
.LINK
http://www.msxfaq.de/tools/get-usnchanges.htm
#>
function Get-ADUsnNumberUpdate
{
[CmdletBinding()]
param
(
[Parameter(Mandatory=$false)]
[String] $Partition = ([ADSI] "LDAP://$env:USERDOMAIN/RootDSE").DefaultNamingContext,
[Parameter(Mandatory=$false)]
[String[]] $ComputerName = ([ADSI] "LDAP://$env:USERDOMAIN/RootDSE").DnsHostName,
[Parameter(Mandatory=$false)]
[String] $FilterRegex = ".*",
[Parameter(Mandatory=$false)]
[String] $FilterWildcard = "*",
[Parameter(Mandatory=$false)]
[AllowEmptyString()]
[String] $CookieFile = "",
[Parameter(Mandatory=$false)]
[Switch] $CookieReadOnly,
[Parameter(Mandatory=$false)]
[Switch] $Once
)
begin
{
# Counter variable to display the progress bar
$Count = 0
# Global hashtables to save the cookies and the serarcher objects per domain controller
$Cookie = @{}
$Searcher = @{}
# The Active Directory properties to load
$Properties = "DistinguishedName", "USNChanged", "USNCreated", "WhenChanged", "IsDeleted", "ObjectClass", "ObjectCategory", "ObjectGuid", "ObjectSID", "SamAccountName", "LastKnownParent", "msDS-LastKnownRDN"
# Check the cookie file variable
# - No path specified: Do not use a cookie file and do not store the USN numbers
# - Path specified, file existing: Load the latest USN numbers from the cookie file
# - Path specified, file not found: Create a new cookie file but start at the lastest USN number on the Domain Controller
if ($CookieFile -ne "" -and (Test-Path -Path $CookieFile))
{
try
{
$Cookie = [Hashtable] (Import-Clixml -Path $CookieFile)
}
catch
{
Write-Error "Error while loading the cookie file: $_"
return
}
}
# Initialize the directory searcher object for each Domain Controller. Define the searcher to point
# to the correct partition on the specified Domain Controllers and set the necessary properties.
foreach ($Computer in $ComputerName)
{
# Load the USN number from the Domain controller, if the cookie file does not contain this USN number
if (-not $Cookie.ContainsKey($Computer))
{
$RootDSE = [ADSI] "LDAP://${Computer}/RootDSE"
$Cookie[$Computer] = [Int64] $RootDSE.HighestCommittedUSN[0]
}
# Initialize directory searcher
$Searcher[$Computer] = New-Object -TypeName System.DirectoryServices.DirectorySearcher -ArgumentList ([ADSI] "LDAP://${Computer}/${Partition}")
$Searcher[$Computer].PropertiesToLoad.AddRange($Properties)
$Searcher[$Computer].Sort.PropertyName = "USNChanged"
$Searcher[$Computer].PageSize = 1000
$Searcher[$Computer].Tombstone = $true
}
}
process
{
do
{
foreach ($Computer in $ComputerName)
{
Write-Progress -Activity "Active Directory Update Searcher..." -Status "Search for USN updates in $Partition on $Computer" -PercentComplete (($Count++) % 100)
# Define the directory searcher filter with a new highest usn
$Searcher[$Computer].Filter = "(&(|(IsDeleted=*)(!IsDeleted=*))((!USNChanged<=$($Cookie[$Computer]))))"
# Execute the search and filter all objects with no USN number
$SearchResult = $Searcher[$Computer].FindAll() | Where-Object { $_.Properties["USNChanged"] -ne "" }
# Filter search result with input filter (regex & wildcard)
$SearchFilter = $SearchResult | Where-Object { $_.Properties["DistinguishedName"] -like $FilterWildcard -and $_.Properties["DistinguishedName"] -match $FilterRegex }
# Iterating all result objects, parse the properties and return a object to the pipeline
if ($SearchFilter.Count -gt 0)
{
# Iterating all objects
foreach ($SearchObject in $SearchFilter)
{
# Create an output object
$Object = New-Object -TypeName PSObject -Property @{
Timestamp = $SearchObject.Properties["WhenChanged"][0]
ObjectClass = $(try { $SearchObject.Properties["ObjectCategory"][0].Substring(3).Split(",")[0] } catch { "Unknown" })
ObjectGuid = [String] [Guid] $SearchObject.Properties["ObjectGUID"][0]
ObjectSid = [String] (New-Object -TypeName "System.Security.Principal.SecurityIdentifier" -ArgumentList ($SearchObject.Properties["ObjectSID"][0]) , 0)
Identity = $SearchObject.Properties["DistinguishedName"][0]
Account = $SearchObject.Properties["SamAccountName"][0]
Action = ""
Field = "USNChanged"
Value = $SearchObject.Properties["USNChanged"][0]
}
# Update the action and identity (if necessary)
if ($SearchObject.Properties["USNChanged"][0] -eq $SearchObject.Properties["USNCreated"][0])
{
$Object.Action = "CREATE"
}
elseif ($SearchObject.Properties["IsDeleted"][0] -eq $null)
{
$Object.Action = "MODIFY"
}
else
{
$Object.Action = "DELETE"
$Object.Identity = "CN=" + $SearchObject.Properties["msDS-LastKnownRDN"] + "," + $SearchObject.Properties["LastKnownParent"]
}
$Object.PSTypeNames.Insert(0, "ActiveDirectoryFever.GetADUpdate.Result")
Write-Output $Object
}
# Update the cookie variable
$Cookie[$Computer] = $SearchResult[-1].Properties["USNChanged"]
}
# Update the cookie file if necessary
if (($CookieFile -ne "") -and (-not $CookieReadOnly))
{
$Cookie | Export-Clixml -Path $CookieFile -Encoding Unicode
}
}
Start-Sleep -Seconds 1
}
until ($Once)
}
}
|
PowerShellCorpus/PowerShellGallery/ActiveDirectoryFever/1.0.0/Helpers/New-ADChangeObject.ps1
|
New-ADChangeObject.ps1
|
function New-ADChangeObject
{
param
(
[Parameter(Mandatory=$true)]
[DateTime] $Timestamp,
[Parameter(Mandatory=$true)]
[AllowEmptyString()]
[String] $ObjectClass,
[Parameter(Mandatory=$true)]
[Guid] $ObjectGuid,
[Parameter(Mandatory=$true)]
[System.Security.Principal.SecurityIdentifier] $ObjectSid,
[Parameter(Mandatory=$true)]
[String] $Identity,
[Parameter(Mandatory=$true)]
[String] $Account,
[Parameter(Mandatory=$true)]
[ValidateSet("CREATE", "DELETE", "RESTORE", "MOVE", "MODIFY", "MEMBER-ADD", "MEMBER-REMOVE", "MEMBEROF-ADD", "MEMBEROF-REMOVE", "CUSTOM-ADD", "CUSTOM-REMOVE", "UNKNOWN")]
[String] $Action,
[Parameter(Mandatory=$true)]
[String] $Field,
[Parameter(Mandatory=$true)]
[AllowEmptyCollection()]
[AllowEmptyString()]
[AllowNull()]
[Object] $Value
)
process
{
# Create an output object
$Object = New-Object -TypeName PSObject -Property @{
Timestamp = $Timestamp
ObjectClass = $(try { $ObjectClass.Substring(3).Split(",")[0] } catch { $ObjectClass })
ObjectGuid = [String] $ObjectGuid
ObjectSid = [String] $ObjectSid
Identity = $Identity
Account = $Account
Action = $Action
Field = $Field
Value = @()
}
# Check if the value has content
if ($Value -is [System.DirectoryServices.ResultPropertyValueCollection])
{
foreach ($Entry in $Value)
{
if ($Entry -is [System.Byte[]] -and $Field -eq "objectsid")
{
# Security Identifier Field
$Object.Value += [String] (New-Object -TypeName System.Security.Principal.SecurityIdentifier -ArgumentList ($Entry, 0))
}
elseif ($Entry -is [System.Byte[]] -and $Field -eq "ntsecuritydescriptor")
{
# Security Descriptor Field
$SecurityDescriptor = New-Object -TypeName System.DirectoryServices.ActiveDirectorySecurity
$SecurityDescriptor.SetSecurityDescriptorBinaryForm($Entry)
$Object.Value += $SecurityDescriptor
}
else
{
# Other Collection
$Object.Value += $Entry
}
}
}
else
{
# Simple Object (String, Integer)
$Object.Value += $Value
}
$Object.PSTypeNames.Insert(0, "ActiveDirectoryFever.GetADUpdate.Result")
Write-Output $Object
}
}
|
PowerShellCorpus/PowerShellGallery/OhMyPsh/0.0.5/plugins/fzf/Load.ps1
|
Load.ps1
|
$PreLoad = {
# Note, we skip using Import-OMPModule as the required module is packaged
# with this plugin.
Import-Module (Join-Path $PluginPath 'fzf\bin\PSFzf\PsFzf.psm1') -Global -Force
}
$PostLoad = {
Write-Output @'
Fuzzy logic provider has been loaded. Here are a few things you can do with this:
- Ctrl+F = Search through your history in a cool new way (try invoke-FuzzyHistory
to do the same but also launch the results!)
- Alt+C = Change your current directory like a boss!
- Alt+A = Parse through your argument history.
'@
}
$Config = {}
$Shutdown = {}
$UnLoad = {
Remove-OMPModule -Name 'PsFzf' -PluginSafe
}
|
PowerShellCorpus/PowerShellGallery/OhMyPsh/0.0.5/plugins/fzf/src/PSFzf.ps1
|
PSFzf.ps1
|
# Nothing
|
PowerShellCorpus/PowerShellGallery/OhMyPsh/0.0.5/plugins/fzf/bin/PSFzf/PSFzf.tests.ps1
|
PSFzf.tests.ps1
|
#
# This is a PowerShell Unit Test file.
# You need a unit test framework such as Pester to run PowerShell Unit tests.
# You can download Pester from http://go.microsoft.com/fwlink/?LinkID=534084
#
Get-Module PsFzf | Remove-Module
# set env variable so Import-Module doesn't fail:
if ([string]::IsNullOrEmpty($env:GOPATH)) {
$env:GOPATH = "c:\ADirectoryThatShouldNotExist\"
}
Import-Module $PSScriptRoot\PsFzf.psm1 -ErrorAction Stop
Describe "Find-CurrentPath" {
InModuleScope PsFzf {
Context "Function Exists" {
It "Should Return Nothing" {
$line = "" ; $cursor = 0
$leftCursor = $rightCursor = $null
Find-CurrentPath $line $cursor ([ref]$leftCursor) ([ref]$rightCursor) | Should Be $null
$leftCursor | Should Be 0
$rightCursor | Should Be 0
}
It "Should Return Nothing with Spaces Cursor at Beginning" {
$line = " " ; $cursor = 0
$leftCursor = $rightCursor = $null
Find-CurrentPath $line $cursor ([ref]$leftCursor) ([ref]$rightCursor) | Should Be " "
$leftCursor | Should Be 0
$rightCursor | Should Be 0
}
It "Should Return Nothing with Spaces Cursor at End" {
$line = " " ; $cursor = 1
$leftCursor = $rightCursor = $null
Find-CurrentPath $line $cursor ([ref]$leftCursor) ([ref]$rightCursor) | Should Be " "
$leftCursor | Should Be 0
$rightCursor | Should Be 0
}
It "Should Return Path Cursor at Beginning for Single Char" {
$line = "~" ; $cursor = 0
$leftCursor = $rightCursor = $null
Find-CurrentPath $line $cursor ([ref]$leftCursor) ([ref]$rightCursor) | Should Be "~"
$leftCursor | Should Be 0
$rightCursor | Should Be ($line.Length-1)
}
It "Should Return Path Cursor at Beginning" {
$line = "C:\Windows\" ; $cursor = 0
$leftCursor = $rightCursor = $null
Find-CurrentPath $line $cursor ([ref]$leftCursor) ([ref]$rightCursor) | Should Be "c:\Windows\"
$leftCursor | Should Be 0
$rightCursor | Should Be ($line.Length-1)
}
It "Should Return Path Cursor at End" {
$line = "C:\Windows\" ; $cursor = $line.Length
$leftCursor = $rightCursor = $null
Find-CurrentPath $line $cursor ([ref]$leftCursor) ([ref]$rightCursor) | Should Be "c:\Windows\"
$leftCursor | Should Be 0
$rightCursor | Should Be ($line.Length-1)
}
It "Should Return Command and Path Cursor at Beginning" {
$line = "cd C:\Windows\" ; $cursor = 0
$leftCursor = $rightCursor = $null
Find-CurrentPath $line $cursor ([ref]$leftCursor) ([ref]$rightCursor) | Should Be "cd"
$leftCursor | Should Be 0
$rightCursor | Should Be ('cd'.Length-1)
}
It "Should Return Command and Path Cursor at End" {
$line = "cd C:\Windows\" ; $cursor = $line.Length
$leftCursor = $rightCursor = $null
Find-CurrentPath $line $cursor ([ref]$leftCursor) ([ref]$rightCursor) | Should Be "c:\Windows\"
$leftCursor | Should Be 'cd '.Length
$rightCursor | Should Be ($line.Length-1)
}
It "Should Return Command and Path Cursor at End" {
$line = "cd C:\Windows\" ; $cursor = $line.Length-1
$leftCursor = $rightCursor = $null
Find-CurrentPath $line $cursor ([ref]$leftCursor) ([ref]$rightCursor) | Should Be "c:\Windows\"
$leftCursor | Should Be 'cd '.Length
$rightCursor | Should Be ($line.Length-1)
}
It "Should Return Path With Quotes Cursor at Beginning" {
'"',"'" | ForEach-Object {
$quote = $_
$line = $quote + 'C:\Program Files\' + $quote ; $cursor = 0
$leftCursor = $rightCursor = $null
Find-CurrentPath $line $cursor ([ref]$leftCursor) ([ref]$rightCursor) | Should Be 'C:\Program Files\'
$leftCursor | Should Be 0
$rightCursor | Should Be ($line.Length-1)
}
}
It "Should Return Path With Quotes Cursor at End" {
'"',"'" | ForEach-Object {
$quote = $_
$line = $quote + 'C:\Program Files\' + $quote ; $cursor = 0
$leftCursor = $rightCursor = $null
Find-CurrentPath $line $cursor ([ref]$leftCursor) ([ref]$rightCursor) | Should Be 'C:\Program Files\'
$leftCursor | Should Be 0
$rightCursor | Should Be ($line.Length-1)
}
}
}
}
}
Describe "Invoke-Fzf" {
InModuleScope PsFzf {
Context "Function Exists" {
It "Should Return Nothing" {
$result = '' | Invoke-Fzf -Query 'file1.txt' -Select1 -Exit0
#$result | Should Be $null
}
It "Should Return 1 Item, 1 Element" {
$result = 'file1.txt' | Invoke-Fzf -Query 'file1.txt' -Select1 -Exit0
#$result | Should Be 'file1.txt'
}
It "Should Return 1 Item, Case Insensitive" {
$result = 'file1.txt' | Invoke-Fzf -Query 'FILE1.TXT' -Select1 -Exit0 -CaseInsensitive
#$result | Should Be 'file1.txt'
}
It "Should Return Nothing, Case Sensitive" {
$result = 'file1.txt' | Invoke-Fzf -Query 'FILE1.TXT' -Select1 -Exit0 -CaseSensitive
#$result | Should Be $null
}
It "Should Return 1 Item, No Multi" {
$result = 'file1.txt','file2.txt' | Invoke-Fzf -Multi -Query 'file1' -Select1 -Exit0 -Filter "file1" -ReverseInput
#$result | Should Be 'file1.txt'
}
It "Should Return 2 Item, Multi" {
$result = 'file1.txt','file2.txt' | Invoke-Fzf -Multi -Query 'file' -Select1 -Exit0 -Filter "file" -ReverseInput
#$result.Length | Should Be 2
#$result[0] | Should Be 'file2.txt'
#$result[1] | Should Be 'file1.txt'
}
}
}
}
|
PowerShellCorpus/PowerShellGallery/OhMyPsh/0.0.5/plugins/fzf/bin/PSFzf/PSFzf.Functions.ps1
|
PSFzf.Functions.ps1
|
#.ExternalHelp PSFzf.psm1-help.xml
function Invoke-FuzzyEdit()
{
$files = @()
try {
Invoke-Fzf -Multi | ForEach-Object { $files += """$_""" }
} catch {
}
# HACK to check to see if we're running under Visual Studio Code.
# If so, reuse Visual Studio Code currently open windows:
$editorOptions = ''
if ($env:VSCODE_PID -ne $null) {
$editor = 'code'
$editorOptions += '--reuse-window'
} else {
$editor = $env:EDITOR
if ($editor -eq $null) {
if (!$IsWindows) {
$editor = 'vim'
} else {
$editor = 'code'
}
}
}
if ($files -ne $null) {
Invoke-Expression -Command ("$editor $editorOptions {0}" -f ($files -join ' '))
}
}
Set-Alias -Name fe -Value Invoke-FuzzyEdit
if (Get-Command Get-Frecents -ErrorAction SilentlyContinue) {
#.ExternalHelp PSFzf.psm1-help.xml
function Invoke-FuzzyFasd() {
$result = $null
try {
Get-Frecents | ForEach-Object { $_.FullPath } | Invoke-Fzf -ReverseInput -NoSort | ForEach-Object { $result = $_ }
} catch {
}
if ($result -ne $null) {
# use cd in case it's aliased to something else:
cd $result
}
}
Set-Alias -Name ff -Value Invoke-FuzzyFasd
} elseif (Get-Command fasd -ErrorAction SilentlyContinue) {
#.ExternalHelp PSFzf.psm1-help.xml
function Invoke-FuzzyFasd() {
$result = $null
try {
fasd -l | Invoke-Fzf -ReverseInput -NoSort | ForEach-Object { $result = $_ }
} catch {
}
if ($result -ne $null) {
# use cd in case it's aliased to something else:
cd $result
}
}
Set-Alias -Name ff -Value Invoke-FuzzyFasd
}
#.ExternalHelp PSFzf.psm1-help.xml
function Invoke-FuzzyHistory() {
$result = Get-History | ForEach-Object { $_.CommandLine } | Invoke-Fzf -Reverse -NoSort
if ($result -ne $null) {
Write-Output "Invoking '$result'`n"
Invoke-Expression "$result" -Verbose
}
}
Set-Alias -Name fh -Value Invoke-FuzzyHistory
#.ExternalHelp PSFzf.psm1-help.xml
function Invoke-FuzzyKillProcess() {
$result = Get-Process | Where-Object { ![string]::IsNullOrEmpty($_.ProcessName) } | ForEach-Object { "{0}: {1}" -f $_.Id,$_.ProcessName } | Invoke-Fzf -Multi
$result | ForEach-Object {
$id = $_ -replace "([0-9]+)(:)(.*)",'$1'
Stop-Process $id -Verbose
}
}
Set-Alias -Name fkill -Value Invoke-FuzzyKillProcess
#.ExternalHelp PSFzf.psm1-help.xml
function Invoke-FuzzySetLocation() {
param($Directory=$null)
if ($Directory -eq $null) { $Directory = $PWD.Path }
$result = $null
try {
Get-ChildItem $Directory -Recurse -ErrorAction SilentlyContinue | Where-Object{ $_.PSIsContainer } | Invoke-Fzf | ForEach-Object { $result = $_ }
} catch {
}
if ($result -ne $null) {
Set-Location $result
}
}
Set-Alias -Name fd -Value Invoke-FuzzySetLocation
if (Get-Command Search-Everything -ErrorAction SilentlyContinue) {
#.ExternalHelp PSFzf.psm1-help.xml
function Set-LocationFuzzyEverything() {
$result = $null
try {
Search-Everything | Invoke-Fzf | ForEach-Object { $result = $_ }
} catch {
}
if ($result -ne $null) {
# use cd in case it's aliased to something else:
cd $result
}
}
Set-Alias -Name cde -Value Set-LocationFuzzyEverything
}
if (Get-Command git -ErrorAction SilentlyContinue) {
#.ExternalHelp PSFzf.psm1-help.xml
function Invoke-FuzzyGitStatus() {
$result = @()
try {
git status --porcelain | Invoke-Fzf -Multi -Bind 'ctrl-a:select-all,ctrl-d:deselect-all,ctrl-t:toggle-all' | ForEach-Object { $result += '{0}' -f $_.Substring('?? '.Length) }
} catch {
# do nothing
}
if ($result -ne $null) {
$result
}
}
Set-Alias -Name fgs -Value Invoke-FuzzyGitStatus
}
|
PowerShellCorpus/PowerShellGallery/OhMyPsh/0.0.5/plugins/qod/Load.ps1
|
Load.ps1
|
$PreLoad = {
if (-not (Test-OMPProfileSetting -Name 'QuoteDirectory')) {
$QuoteDir = Join-Path $PluginPath "$Name\src\quotes.txt"
Write-Output "Setting Quote Directory to $QuoteDir"
Add-OMPProfileSetting -Name 'QuoteDirectory' -Value $QuoteDir
Export-OMPProfile
}
$QuoteDir = Get-OMPProfileSetting -Name 'QuoteDirectory'
}
$Config = {}
$PostLoad = {
Write-Host ''
Write-Host (Get-Quote -Path $QuoteDir)
}
$Shutdown = {}
$Unload = {
Remove-OMPProfileSetting -Name 'QuoteDirectory'
}
|
PowerShellCorpus/PowerShellGallery/OhMyPsh/0.0.5/plugins/qod/src/Plugin.ps1
|
Plugin.ps1
|
## Superfluous but fun quotes.
function Global:Get-Quote {
param(
$Path = (Get-OMPProfileSetting -Name 'QuoteDirectory'),
[int]$Count=1
)
if(-not (Test-Path $Path) ) {
$Path = Join-Path ${QuoteDir} $Path
if(-not (Test-Path $Path) ) {
$Path = $Path + ".txt"
}
}
Get-Content $Path | Where-Object { $_ } | Get-Random -Count $Count
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.