powershell 拆分大文件

快速拆分大文件而不将内容写入内存

SplitLargeFile.ps1
$from = "C:\CodeFiles\temp\temp.log"
$rootName = "C:\CodeFiles\temp\large_log_chunk"
$ext = "txt"
$upperBound = 500MB


$fromFile = [io.file]::OpenRead($from)
$buff = new-object byte[] $upperBound
$count = $idx = 0
try {
    do {
        "Reading $upperBound"
        $count = $fromFile.Read($buff, 0, $buff.Length)
        if ($count -gt 0) {
            $to = "{0}.{1}.{2}" -f ($rootName, $idx, $ext)
            $toFile = [io.file]::OpenWrite($to)
            try {
                "Writing $count to $to"
                $tofile.Write($buff, 0, $count)
            } finally {
                $tofile.Close()
            }
        }
        $idx ++
    } while ($count -gt 0)
}
finally {
    $fromFile.Close()
}

powershell 设置日志级别

SetSPLogLevel.ps1
Set-SPLogLevel -TraceSeverity Verbose -EventSeverity Verbose

#Set-SPLogLevel -TraceSeverity High -EventSeverity Error

powershell 运行工作流程

RunWorkflow.ps1
Add-PSSnapin Microsoft.SharePoint.PowerShell  -erroraction silentlycontinue

$listName = "WorkflowExamples"
$workflowName = "WorkflowEmail"
$url = "https://xxxx/dept/109/109.14/BO/SS/DavidJWilliams"

$startDate = Get-Date
Set-SPLogLevel -TraceSeverity Verbose -EventSeverity Verbose

$web = Get-SPWeb -Identity $url

$path = "f:\temp\WorkflowRun.txt"
If (Test-Path $path){
	Remove-Item $path
}

$manager = $web.Site.WorkFlowManager
 
# Name of the list
$list = $web.Lists[$listName]
 
# Name of the Workflow
$assoc = $list.WorkflowAssociations.GetAssociationByName($workflowName,"en-US")
 
$data = $assoc.AssociationData
$items = $list.Items
$assoc.AllowAsyncManualStart = $true
$assoc.AllowManual = $true

$item = $items[0]

$runningWorkflows = $item.Workflows | Where-Object {($_.InternalState -eq "Running, HasNewEvents")}

if($runningWorkflows -eq $null)
{
	write-host "No workflows running..starting the workflow...." -BackgroundColor Yellow -ForegroundColor Black
	$wf = $manager.StartWorkFlow($item,$assoc,$data,$true)
}

$runningWorkflows = $item.Workflows | Where-Object {($_.InternalState -eq "Running, HasNewEvents")}

$runCount = 0
while($runningWorkflows -ne $null)
{
	$runCount = $runCount + 1
	write-host "workflow is still running..$runCount..on item id: $($item.ID)" -BackgroundColor Green -ForegroundColor Black
	$testItem = $list.GetItemById($item.ID)
	$runningWorkflows = $testItem.Workflows | Where-Object {($_.InternalState -eq "Running, HasNewEvents")}

	Start-Sleep -s 10
	
	if($runCount -eq 6 -or $runCount -eq 12 -or $runCount -eq 18 -or $runCount -eq 24)
	{
		#[Microsoft.SharePoint.Workflow.SPWorkflowManager]::CancelWorkflow($runningWorkflows);
		$totalTime = $runCount * 10
		write-host "Workflow on item with ID $($item.id) has been running for $totalTime seconds" -BackgroundColor Blue -ForegroundColor White
		#$runningWorkflows = $null
	}
	
}#end while			
 
$manager.Dispose()
$web.Dispose()

Set-SPLogLevel -TraceSeverity High -EventSeverity Error
$endDate = Get-Date

Start-Sleep -s 15

$path = "F:\temp\temp.log"
If (Test-Path $path){
	Remove-Item $path
}

try
{
	Merge-SPLogFile -path $path -Overwrite -StartTime $startDate -EndTime $endDate
}
catch
{
    write-host "Error occured: $_"
}
#-Category "Information Policy Management"
notepad $path

powershell 运行Caml查询

这通过PowerShell对列表运行caml查询

RunCaml.ps1
#Definition of the function that allows to do the CAML query 
function DoCAMLQuery 
{ 
    param ($url,$listName) 
    try 
    { 
        $web = Get-SPWeb $url        
        $list = $web.Lists.TryGetList($listName)  
        if ($list)  
        {  
            $spqQuery = New-Object Microsoft.SharePoint.SPQuery 
            #$spqQuery.Query =  "<Where><And><And><Eq><FieldRef Name='ApprovedByDepartment'></FieldRef><Value Type='Text'>109</Value></Eq><Eq><FieldRef Name='AwardFY'></FieldRef><Value Type='Text'>19</Value></Eq></And><Neq><FieldRef Name='AwardStatus' /><Value Type='Choice'>Cancelled</Value></Neq></And></Where>" 
            $spqQuery.Query =  "<Where><Eq><FieldRef Name='AwardFY'></FieldRef><Value Type='Number'>19</Value></Eq></Where>"
            #$spqQuery.ViewFields = "<FieldRef Name='FileLeafRef' /><FieldRef Name='Title' />" 
            #$spqQuery.ViewFieldsOnly = $true 
            $splListItems = $list.GetItems($spqQuery) 
 
            $iNumber=1 
            foreach ($splListItem in $splListItems) 
            { 
                write-host "Item # $iNumber - Name: " $splListItem.Name " ," "Title:" $splListItem["Title"] -ForegroundColor Green 
                $iNumber+=1 
            } 
        }      
        $web.Dispose() 
    } 
    catch [System.Exception] 
    { 
        write-host -f red $_.Exception.ToString() 
    } 
} 

Start-SPAssignment -Global 
#Calling the function 
$url="https://xxxx/dept/1100/CMDAWARDS/PDQStore" 
$listName="Award" 
DoCamlQuery -url $url -listName $listName 
Stop-SPAssignment -Global 

powershell 快速编辑列表修复

这会将clienttemplates.js添加到列表定义中,从而启用快速编辑按钮

QuickViewFixForView.ps1
Add-PSSnapin Microsoft.SharePoint.PowerShell -ErrorAction SilentlyContinue

cls
#set the variables
$url = "https://xxxx/dept/1100/CMDAWARDS/PDQStore"
$listName = "Department"
$viewName = "Active Only"

#get the web, list, view
$web = Get-SPWeb $url
$list = $web.Lists[$listName]
$view = $list.Views | ?{$_.Title -eq $viewName}

#add JSLink
$view.JSLink = "clienttemplates.js"
$view.Update()
$view

powershell 获取用户UPN

从用户配置文件服务获取用户的UPN

GetUserUPN.ps1
$userID='domain\username'

#$ca = Get-spwebapplication -includecentraladministration | where {$_.IsAdministrationWebApplication}
$site = New-Object Microsoft.SharePoint.SPSite "https://homeportnwtest.psns.navy.mil"
#$spsite = $ca.url 
#$site = Get-SPSite $spsite
$context = Get-SPServiceContext $site
$upsa = New-Object Microsoft.Office.Server.UserProfiles.UserProfileManager($context)
$profile = $upsa.GetEnumerator() |Where-Object {$_.AccountName -eq $userID}
$profile["SPS-UserPrincipalName"].Value
#$profile.SipAddress
#$profile.SID()

powershell 取消所有SahrePoint工作流程

CancelAllWorkflows.ps1
$url = "https://xxx/dept/1100/CMDAWARDS/PDQStore"
$web = Get-SPWeb -Identity $url

$path = "f:\temp\CancelWorkflows.txt"
If (Test-Path $path){
	Remove-Item $path
}

foreach($item in $items)
{
    write-host "Item ID: $($item.ID)"
	$runningWorkflows = $item.Workflows | Where-Object {($_.InternalState -eq "Running, HasNewEvents" -or $_.InternalState -eq "Starting")}
	if($runningWorkflows -ne $null)
	{
		write-host "Workflows running on item ID: $($item.ID)....Cancelling" -BackgroundColor Yellow -ForegroundColor Black
        "Workflows running on item ID: $($item.ID)....Cancelling" | Out-File $path -Append
		[Microsoft.SharePoint.Workflow.SPWorkflowManager]::CancelWorkflow($runningWorkflows);
	}
}

powershell 复制配置管理器客户端日志。

将配置管理器客户端日志复制到指定的路径。

Copy-CMClientLogs.ps1
<#
.SYNOPSIS
    Copies the configuration manager client logs.
.DESCRIPTION
    Copies the configuration manager client logs to a specified path.
.PARAMETER Path
    Specifies the path to copy the log files to.
.EXAMPLE
    Copy-CMClientLogs.ps1 -Share '\\SomePath'
.INPUTS
    System.String.
.OUTPUTS
    System.String.
.NOTES
    Created by Ioan Popovici
.LINK
    https://SCCM.Zone/Copy-CMClientLogs
.LINK
    https://SCCM.Zone/Copy-CMClientLogs-CHANGELOG
.LINK
    https://SCCM.Zone/Copy-CMClientLogs-GIT
.LINK
    https://SCCM.Zone/Issues
.COMPONENT
    Configuration Manager Client
.FUNCTIONALITY
    Copy Client Logs
#>

## Set script requirements
#Requires -Version 3.0

##*=============================================
##* VARIABLE DECLARATION
##*=============================================
#region VariableDeclaration

## Get script parameters
Param (
    [Parameter(Mandatory=$true,HelpMessage="You need to input a share",Position=0)]
    [ValidateNotNullorEmpty()]
    [Alias('pt')]
    [string]$Path
)

#endregion
##*=============================================
##* END VARIABLE DECLARATION
##*=============================================

##*=============================================
##* FUNCTION LISTINGS
##*=============================================
#region FunctionListings

#region Function Copy-CMClientLogs
Function Copy-CMClientLogs {
<#
.SYNOPSIS
    Copies the configuration manager client logs.
.DESCRIPTION
    Copies the configuration manager client logs to a specified path.
.PARAMETER Path
    Specifies the path to copy the log files to.
.EXAMPLE
    Copy-CMClientLogs -Path '\\SomePath'
.INPUTS
    System.String.
.OUTPUTS
    System.String.
.NOTES
    This is an internal script function and should typically not be called directly.
.LINK
    https://SCCM.Zone
.LINK
    https://SCCM.Zone/Git
.COMPONENT
    Configuration Manager Client
.FUNCTIONALITY
    Copy Client Logs
#>
    [CmdletBinding()]
    Param (
        [Parameter(Mandatory=$true,HelpMessage='You need to input path',Position=0)]
        [ValidateNotNullorEmpty()]
        [Alias('pt')]
        [string]$Path
    )

    Begin {

        ## Set script to fail on any error
        $ErrorActionPreference = 'Stop'

        ## Import BITS transfer module
        Import-Module -Name 'BitsTransfer' -Force
    }
    Process {
        Try {

            ## Check if share exists
            [boolean]$PathExists = Test-Path -Path $Path
            If (-not $PathExists ) { Throw "Path [$Path] does not exist." }

            ## Get path for CM client log files
            [string]$LogPath = (Get-ItemProperty -Path 'HKLM:\Software\Microsoft\CCM\Logging\@Global').LogDirectory

            ## Copy logs to temporary folder to remove  any locks
            #  Assemble temp log path
            [string]$LogPathTemp = Join-Path -Path $env:Temp -ChildPath 'CMLogs'
            #  Delete temp folder if it already exists
            [boolean]$TempFolderExist = Test-Path $LogPathTemp
            If ($TempFolderExist) { Remove-Item $LogPathTemp -Recurse -Force }
            #  Create temp folder
            $null = New-Item -Path $LogPathTemp -ItemType 'Directory' -Force
            #  Copy logs to temporary folder
            $null = Copy-Item -Path "$LogPath\*" -Destination $LogPathTemp -Force

            ## Compress the logs
            #  Set archive name
            [string]$LogArchivePath = $env:Temp + '\' + $env:ComputerName + '_CMCLogs.zip'
            Add-Type -assembly "system.io.compression.filesystem"
            $null = [IO.Compression.ZipFile]::CreateFromDirectory($LogPathTemp, $LogArchivePath)

            ## Copy zipped logs to share
            $LogPathDestination = Join-Path $Path -ChildPath $env:ComputerName
            #  Create destination folder
            $null = New-Item -Path $LogPathDestination -ItemType 'Directory' -Force
            #  Copy files to destination
            Start-BitsTransfer -Source $LogArchivePath -Destination $LogPathDestination -Description 'Copy client logs...' -DisplayName 'Copy'

            Write-Output -InputObject "Successfuly copied [$env:ComputerName\\$LogPath] to path [$Path]."
        }
        Catch {
            Write-Output -InputObject "Could not copy logs [$env:ComputerName\\$LogPath] to path [$Path]. `n $_"
        }
        Finally {

            ## Cleanup temporary files and folders from CM client
            Remove-Item $LogPathTemp -Recurse -Force -ErrorAction 'SilentlyContinue'
            Remove-Item -Path $LogArchivePath -Force -ErrorAction 'SilentlyContinue'
        }
    }
    End {
    }
}
#endregion

#endregion
##*=============================================
##* END FUNCTION LISTINGS
##*=============================================

##*=============================================
##* SCRIPT BODY
##*=============================================
#region ScriptBody

Copy-CMClientLogs -Path $Path

#endregion
##*=============================================
##* END SCRIPT BODY
##*=============================================

powershell 将AMP优先级设置为指定值。

通过根据需要增加或减少优先级,将AMP优先级设置为指定值。

Set-AMPPriority.ps1
#region Function Set-AMPPriority
Function Set-AMPPriority {
<#
.SYNOPSIS
    Sets AMP priority to a specified value.
.DESCRIPTION
    Sets AMP priority to a specified value by increasing or decreasing the priority as required.
.PARAMETER Name
    Specifies the AMP name.
.PARAMETER Priority
    Specifies required priority.
.EXAMPLE
    Set-AMPPriority -Name 'SomeAMPName' -Priority '2'
.INPUTS
    System.String.
.OUTPUTS
    None.
.NOTES
    This is an internal script function and should typically not be called directly.
.LINK
    https://SCCM.Zone
.LINK
    https://SCCM.Zone/Git
.COMPONENT
    Configuration Manager Client
.FUNCTIONALITY
    Set AMP Priority
#>
    [CmdletBinding()]
    Param (
        [Parameter(Mandatory=$true,Position=0)]
        [ValidateNotNullorEmpty()]
        [Alias('na')]
        [string]$Name,
        [Parameter(Mandatory=$true,Position=0)]
        [ValidateNotNullorEmpty()]
        [Alias('pr')]
        [string]$Priority
    )

    Begin {

        ## Set script to fail on any error
        $ErrorActionPreference = 'Stop'

        ## Import SCCM PSH module and changing context
        Try {
            Import-Module -Name $env:SMS_ADMIN_UI_PATH.Replace('\bin\i386','\bin\configurationmanager.psd1')
        }
        Catch {
            Throw "Could not Import CM PSH module. `n $_"
        }

        Try {
            #  Get the CMSITE SiteCode and change connection context
            $SiteCode = Get-PSDrive -PSProvider 'CMSITE'

            #  Change the connection context
            Set-Location "$($SiteCode.Name):\"
        }
        Catch {
            Throw "Could not set connection context. `n $_"
        }
    }
    Process {
        Try {

            ## Get AMP current priority
            [string]$CurrentPriority = (Get-CMAntimalwarePolicy -Name $Name).Priority

            ## Set AMP priority
            While ($CurrentPriority -ne $Priority) {
                If ($CurrentPriority -lt $Priority) {
                    Set-CMAntimalwarePolicy -Name $Name -Priority 'Decrease'
                }
                Else {
                    Set-CMAntimalwarePolicy -Name $Name -Priority 'Increase'
                }
                #  Get AMP current priority
                $CurrentPriority = (Get-CMAntimalwarePolicy -Name $Name).Priority
            }
        }
        Catch {
            Throw "Could not change priority [$Priority] for AMP [$Name]. `n $_"
            Break
        }
        Finally {
            Write-Output -InputObject "Priority for AMP [$Name] is [$CurrentPriority]."
        }
    }
    End {
    }
}
#endregion

powershell ACL

フォルダやファイルのアクセス権设定

acl
$userName = "domain\name"
$acl = Get-Acl $folderPath

# FileSystemRights: 権限
## Modify: 変更
# InheritanceFlags 継承のセマンティクスを指定
## ObjectInherit: ACE は、子コンテナー オブジェクトによって継承
## ObjectInherit: ACE は、子リーフ オブジェクトによって継承
# PropagationFlags 子オブジェクトに反映させる方法を指定
## None: 継承フラグが設定されていないことを指定
# AccessControlType: アクセスの許可または拒否
## Allow アクセスを許可
$permission = ($userName`
    , [System.Security.AccessControl.FileSystemRights]::Modify`
    , ([System.Security.AccessControl.InheritanceFlags]::ObjectInherit -bor [System.Security.AccessControl.InheritanceFlags]::ContainerInherit),`
    , [System.Security.AccessControl.PropagationFlags]::None`
    , [System.Security.AccessControl.AccessControlType]::Allow)

# 引数:ユーザー名,アクセス権,下位フォルダへ継承,下位オブジェクトへ継承,継承の制限,アクセス許可
$accessRule = New-Object System.Security.AccessControl.FileSystemAccessRule $permission
$acl.SetAccessRule($accessRule)
$acl | Set-Acl $folderPath