powershell 列出Tridion站点核心服务系统用户

list-system-users.ps1
# see https://github.com/pkjaer/tridion-powershell-modules
# see https://gist.github.com/jhorsman/b218ba7e2e5587d21c395d5968583b61 to learn more about configuring the Tridion-CoreService module

# Install the Tridion-CoreService module from the Tridion-Powershell-Modules project
Install-Module -Name Tridion-CoreService
Import-Module -Name Tridion-CoreService

# Set the server configuration
Set-TridionCoreServiceSettings -Credential (Get-Credential) -CredentialType Windows
Set-TridionCoreServiceSettings -HostName my-cms-server -Version Web-8.5 -ConnectionType Basic-SSL

# Test configuration by listing the current user
Get-TridionUser -Current

#List all system/built-in/predefined users
$client = Get-TridionCoreServiceClient
$filter = New-Object Tridion.ContentManager.CoreService.Client.UsersFilterData;
$filter.IsPredefined = $true;
$client.GetSystemWideList($filter) | Select-Object Id, Title, Description, IsPredefined, IsEnabled

powershell 从Tridion-Powershell-Modules项目安装和配置Tridion-CoreService模块

Install Tridion-CoreService module.ps1
# Install the Tridion-CoreService module from the Tridion-Powershell-Modules project. See https://github.com/pkjaer/tridion-powershell-modules
Install-Module -Name Tridion-CoreService
Import-Module -Name Tridion-CoreService

# Set the server configuration
Set-TridionCoreServiceSettings -HostName my-cms-server -Version Web-8.5 -ConnectionType Basic
Set-TridionCoreServiceSettings -Credential (Get-Credential) -CredentialType Windows

# Alternatively use SSL (https)
#Set-TridionCoreServiceSettings -HostName my-cms-server -Version Web-8.5 -ConnectionType Basic-SSL
#Set-TridionCoreServiceSettings -Credential (Get-Credential) -CredentialType Windows

# Alternatively if it is safe to save the password in plain-text format...
#Set-TridionCoreServiceSettings -HostName localhost -Version Web-8.5 -ConnectionType Basic
#$credential = New-Object System.Management.Automation.PSCredential("vagrant", (ConvertTo-SecureString "vagrant" -AsPlainText -Force))
#Set-TridionCoreServiceSettings -Credential $credential -CredentialType Windows 

# Test configuration by listing the current user
#Get-TridionUser -Current

powershell 测试ComObject

使用PowerShell测试COM对象的存在。

Test-ComObject.ps1
#region Test-ComObject
function Test-ComObject {
    [CmdletBinding()]
    PARAM(
        [Parameter(Mandatory = $false, Position = 0, ValueFromPipeline = $true)]
        [string]
        $ComputerName = $env:COMPUTERNAME
        ,
        [Parameter(Mandatory = $true, Position = 1, ValueFromPipeline = $true)]
        [string]
        $ComObject
    )

    begin {
        Write-Verbose $MyInvocation.MyCommand
    }

    process {
        try {
            $Type = [System.Type]::GetTypeFromProgID($ComObject, $ComputerName, $true)
        }
        catch {
        }
        finally {
            if ($Type) {
                $true
            }
            else {
                $false
            }
        }
    }

    end {
    }
}
#endregion Test-ComObject

powershell 各种Windows桌面和资源管理器设置,但PowerShell

Windows Desktop and Explorer settings.ps1
# from https://superuser.com/a/1479800/477803

function Test-DesktopIconHidden {            
  [CmdletBinding(SupportsShouldProcess=$false)]
  Param()

  Process {
    $Shell = New-Object -ComObject "Shell.Application"
    $Shell.GetSetting(0x4000)
  }
}

function Test-RegistryKeyValue {
  [CmdletBinding(SupportsShouldProcess=$false)]
  Param([Parameter(Position=0, Mandatory=$true, ValueFromPipeline=$true)] [string]$Path,
        [Parameter(Position=1, Mandatory=$true, ValueFromPipeline=$true)] [string]$Value)

  Process {
    if (Test-Path $Path) {
      $Key=Get-Item -LiteralPath $Path
      if ($Key.GetValue($Value, $null) -ne $null) { $true } else { $false }
    }
    else { $false }
  }
}

$RegPath="HKCU:\Software\Microsoft\Windows\CurrentVersion\Explorer\Advanced"
$KeyList=@(@{Name="TaskbarGlomLevel";     Value=1; Description="Combine taskbar buttons"},
           @{Name="TaskbarSmallIcons";    Value=1; Description="Use small taskbar buttons"},
           @{Name="HideFileExt";          Value=0; Description="Hide file extensions"},
           @{Name="HideIcons";            Value=0; Description="Hide Desktop icons"},
           @{Name="Hidden";               Value=1; Description="Show Hidden files"},
           @{Name="HideDrivesWithNoMedia";Value=1; Description="Show all drives"},
           @{Name="HideMergeConflicts";   Value=0; Description="Hide merge conflicts"},
           @{Name="ListviewShadow";       Value=0; Description="ListviewShadow"},
           @{Name="MMTaskbarEnabled";     Value=0; Description="MMTaskbarEnabled"},
           @{Name="SharingWizardOn";      Value=0; Description="Use Sharing Wizard"},
           @{Name="TaskbarAnimations";    Value=1; Description="TaskbarAnimations"})

for ($i=0; $i -lt $KeyList.Count; $i++) {
  if (Test-RegistryKeyValue -Path $RegPath -Value $KeyList[$i].Name) {
    if ((Get-ItemPropertyValue -Path $RegPath -Name $KeyList[$i].Name) -eq $KeyList[$i].Value) {
      Write-Verbose "$($KeyList[$i].Description) is already set"
    }
    else { Set-ItemProperty -Path $RegPath -Name $KeyList[$i].Name -Value $KeyList[$i].Value }
  }
  else { New-ItemProperty -Path $RegPath -Name $KeyList[$i].Name -Value $KeyList[$i].Value -PropertyType DWORD -Force > $null }
}

$RegPath="HKCU:\Software\Microsoft\Windows\CurrentVersion\Explorer\HideDesktopIcons\NewStartPanel"
$KeyList=@(@{Name="{20D04FE0-3AEA-1069-A2D8-08002B30309D}"; Value=0; Description="My Computer icon"},
           #@{Name="{5399E694-6CE5-4D6C-8FCE-1D8870FDCBA0}"; Value=0; Description="Control Panel icon"},
           @{Name="{59031a47-3f72-44a7-89c5-5595fe6b30ee}"; Value=0; Description="User Files icon"},
           @{Name="{645FF040-5081-101B-9F08-00AA002F954E}"; Value=0; Description="Recycle Bin icon"},
           @{Name="{F02C1A0D-BE21-4350-88B0-7367FC96EF3C}"; Value=0; Description="Network icon"},
           @{Name="{018D5C66-4533-4307-9B53-224DE2ED1FE6}"; Value=0; Description="Unknown icon"})

for ($i=0; $i -lt $KeyList.Count; $i++) {
  if (Test-RegistryKeyValue -Path $RegPath -Value $KeyList[$i].Name) {
    if ((Get-ItemPropertyValue -Path $RegPath -Name $KeyList[$i].Name) -eq $KeyList[$i].Value) {
      Write-Verbose "$($KeyList[$i].Description) is already set"
    }
    else { Set-ItemProperty -Path $RegPath -Name $KeyList[$i].Name -Value $KeyList[$i].Value }
  }
  else { New-ItemProperty -Path $RegPath -Name $KeyList[$i].Name -Value $KeyList[$i].Value -PropertyType DWORD -Force > $null }
}

powershell Set-DxAddon.ps1将SDL Tridion Sites 9.1(及更高版本)附加组件上载到附加服务

Set-DxAddon.ps1
# Usage examples
#   .\Set-DxAddon.ps1 -Url "http://server:83" -Path addon.zip
#   .\Set-DxAddon.ps1 -Path addon.zip

param (
    [parameter(Mandatory=$false, HelpMessage="Tridion DX Add-on service URL. Defaults to 'http://localhost:83'")]
    [string] $Url = "http://localhost:83",

    [parameter(Mandatory=$true, HelpMessage="Path to to the add-on.")]
    [string] $Path
)

$ErrorActionPreference = "Stop"

if(-not (Test-Path $Path))
{
    Write-Error "File '$Path' does not exist"
}

$filename = Split-Path $Path -Leaf
$fileBytes = [System.IO.File]::ReadAllBytes($Path);
$fileEnc = [System.Text.Encoding]::GetEncoding('ISO-8859-1').GetString($fileBytes);
$boundary = [System.Guid]::NewGuid().ToString(); 
$LF = "`r`n";
$bodyLines = ( 
    "--$boundary",
    "Content-Disposition: form-data; name=`"File`"; filename=`"$filename`"",
    "Content-Type: application/x-zip-compressed$LF",
    $fileEnc,
    "--$boundary--$LF" 
) -join $LF

$postUrl = $Url + "/addon/api/v1/addons"
Invoke-RestMethod -Uri $postUrl -Method Post -ContentType "multipart/form-data; boundary=`"$boundary`"" -Body $bodyLines

powershell GET-DismWindowsFeature

Get-DismWindowsFeature.ps1
#region Get-DismWindowsFeature
function Get-DismWindowsFeature {
    [CmdletBinding()]
    PARAM(
        [Parameter(Mandatory = $false, Position = 0, ValueFromPipeline = $true)]
        [string]
        $Name
        ,
        [Parameter(Mandatory = $false, Position = 0, ValueFromPipeline = $true)]
        [switch]
        $Enabled
    )

    begin {
        Write-Verbose $MyInvocation.MyCommand
        $script:EnabledPreference = $PSBoundParameters.ContainsKey('Enabled')

        filter FilterByName {
            if ($Name) {
                $_ | Where-Object {$_.FeatureName -eq $Name}
            }
            else {
                $_
            }
        }

        filter FilterByEnabled {
            if ($script:EnabledPreference -eq $false) {
                $_
            }
            elseif ($Enabled -eq $true) {
                $_ | Where-Object { $_.State -eq 'Enabled' }
            }
            elseif ($Enabled -eq $false) {
                $_ | Where-Object { $_.State -ne 'Enabled' }
            }
        }
    }

    process {
        try {
            dism.exe /online /get-features /format:table | Select-Object -Skip 12 | ConvertFrom-Csv -Header "Feature Name", "State" -Delimiter "|" | ForEach-Object {
                $Properties = @{
                    FeatureName = $null
                    State       = $null
                }
                if ($_."Feature Name" -notmatch "The operation completed successfully.") {
                    $Properties.FeatureName = $_."Feature Name".Trim() ;
                    $Properties.State       = $_.State.Trim() ;
                    $obj = New-Object -TypeName PSObject -Property $Properties
                    Write-Output -InputObject $obj
                }
            } | FilterByName | FilterByEnabled
        }
        catch {
            Throw $_
        }
    }

    end {
    }
}
#endregion Get-DismWindowsFeature

# Get-DismWindowsFeature
# Get-DismWindowsFeature -Enabled
# Get-DismWindowsFeature -Enabled:$false
# Get-DismWindowsFeature -Name 'IIS-ASP' -Enabled
# Get-DismWindowsFeature -Name 'IIS-ASP' -Enabled:$false -Verbose

powershell MS SQL Powershell使用SQLPS创建视图

MS SQL Powershell使用SQLPS创建视图

MS SQL Powershell Creating Views Using SQLPS.ps1
# Set the path context to the local, default instance 
# of SQL Server and get a reference to AdventureWorks2014  
CD \sql\localhost\default\databases  
$db = get-item AdventureWorks2014  
  
# Define a View object variable by supplying the parent database,
# view name and schema in the constructor.   
$myview  = New-Object -TypeName Microsoft.SqlServer.Management.SMO.View `  
-argumentlist $db, "Test_View", "Sales"  
  
# Set the TextHeader and TextBody property to define the view.   
$myview.TextHeader = "CREATE VIEW [Sales].[Test_View] AS"  
$myview.TextBody =
"   
     SELECT h.SalesOrderID, d.OrderQty 
     FROM Sales.SalesOrderHeader AS h 
     INNER JOIN Sales.SalesOrderDetail AS d
     ON h.SalesOrderID = d.SalesOrderID
"  
  
# Create the view on the instance of SQL Server.   
$myview.Create()  
  
# Remove the view.   
$myview.Drop();  

powershell MS SQL Powershell使用TSQL创建表

MS SQL Powershell使用TSQL创建表

MS SQL Powershell Create Table Using TSQL.ps1
[string] $userName = "<user-name>"
[string] $pwd = '<pwd>'

[string] $connStr = "Server=localhost;Database=master;
                     User ID=$userName;Password=$pwd;
                     Encrypt=false;TrustServerCertificate=False;
                     Connection Timeout=30;"

$connection = New-Object System.Data.SqlClient.SqlConnection
$connection.ConnectionString = $connStr
$connection.Open();

$cmd = $connection.CreateCommand()
$cmd.CommandText = 
"
  CREATE TABLE tbl1
  (col1 INT,
   col2 VARCHAR(20)
  )
"
$reader = $cmd.ExecuteReader()
$reader.HasRows

$cmd.Dispose()
$connection.Close()

powershell MS SQL Powershell使用SQLPS创建表

MS SQL Powershell使用SQLPS创建表

MS SQL Powershell Create Table Using SQLPS.ps1
#Load the assembly containing the objects used in this example  
[reflection.assembly]::LoadWithPartialName("Microsoft.SqlServer.Types")  
  
# Set the path context to the local, default instance of SQL Server.  
CD \sql\localhost\default\Databases\  
  
#And the database object corresponding to AdventureWorks2012.  
$db = get-item AdventureWorks2012  
  
#Create a SMO Table  
$tb = New-Object -TypeName Microsoft.SqlServer.Management.SMO.Table -argumentlist $db, "Test_Table"  
  
#Add various columns to the table.   
$Type = [Microsoft.SqlServer.Management.SMO.DataType]::NChar(50)  
$col1 =  New-Object -TypeName Microsoft.SqlServer.Management.SMO.Column -argumentlist $tb,"Name", $Type  
$col1.Collation = "Latin1_General_CI_AS"  
$col1.Nullable = $true  
$tb.Columns.Add($col1)  
  
$Type = [Microsoft.SqlServer.Management.SMO.DataType]::Int  
$col2 =  New-Object -TypeName Microsoft.SqlServer.Management.SMO.Column -argumentlist $tb,"ID", $Type  
$col2.Identity = $true  
$col2.IdentitySeed = 1  
$col2.IdentityIncrement = 1  
$tb.Columns.Add($col2)   
  
$Type = [Microsoft.SqlServer.Management.SMO.DataType]::Real  
$col3 =  New-Object -TypeName Microsoft.SqlServer.Management.SMO.Column -argumentlist $tb,"Value", $Type  
$tb.Columns.Add($col3)   
  
$Type = [Microsoft.SqlServer.Management.SMO.DataType]::DateTime  
$col4 =  New-Object -TypeName Microsoft.SqlServer.Management.SMO.Column -argumentlist $tb,"Date", $Type  
$col4.Nullable = $false  
$tb.Columns.Add($col4)   
  
#Create the table  
$tb.Create()  
  
$Type = [Microsoft.SqlServer.Management.SMO.DataType]::DateTime  
$col5 =  New-Object -TypeName Microsoft.SqlServer.Management.SMO.Column -argumentlist $tb,"ExpiryDate", $Type  
$col5.Nullable = $false  
$tb.Columns.Add($col5)   
  
#Run the Alter method to make the change on the instance of SQL Server.   
$tb.Alter()  
  
#Remove the table from the database.   
$tb.Drop()  
  

powershell MS SQL Powershell使用本机TSQL创建数据库

MS SQL Powershell使用本机TSQL创建数据库

MS SQL Powershell Create Database Using Native TSQL.ps1
[string] $userName = "<user-name>"
[string] $pwd = '<pwd>'

[string] $connStr = "Server=localhost;Database=master;
                     User ID=$userName;Password=$pwd;
                     Encrypt=false;TrustServerCertificate=False;
                     Connection Timeout=30;"

$connection = New-Object System.Data.SqlClient.SqlConnection
$connection.ConnectionString = $connStr
$connection.Open();

$cmd = $connection.CreateCommand()
$cmd.CommandText = 
"
  CREATE DATABASE MyDB
"
$reader = $cmd.ExecuteReader()
$reader.HasRows

$cmd.Dispose()
$connection.Close()