powershell PowerShell:按功能组获取ActiveDirectory用户<br/> #PowerShell <br/> #ActiveDirectory

PowerShell:按功能组获取ActiveDirectory用户<br/> #PowerShell <br/> #ActiveDirectory

Get-ADUsersByFunctionGroup.ps1
Import-Module activedirectory

cls

$GroupMembershipReportByPrefix = "F_"
$IgnoreGroups = "F_Lehrlingsbetreuer","F_Mitarbeiter","F_Mitarbeiter mit Arbeitsplatz","F_Mitarbeiter ohne Arbeitsplatz","F_Verantwortlicher Kostenstelle","F_Fahrdienstleiter"
$ReportInOUs = "OU=Dienste,OU=Betrieb,OU=vblusers2,DC=vbl,DC=ch"

$ReportInOUs | %{

    Get-ADOrganizationalUnit -Filter * -SearchBase $_ | %{

        Write-Host "`n### $($_.Name) ###"

        Get-ADUser -SearchBase $_.DistinguishedName  -filter * -properties Title, Manager, department, displayname | sort Name | %{

            Write-Host "`n$($_.Name)`n"

            Get-ADPrincipalGroupMembership $_ | where{$_.Name.StartsWith($GroupMembershipReportByPrefix) -and $IgnoreGroups -notcontains $_.Name} | %{

                Write-Host ("- $($_.Name)" -replace "F_","")
            }  
        }
    } 
}

powershell PowerShell:从组成员获取AD用户对象和用户对象<br/> #PowerShell <br/> #ActiveDirectory

PowerShell:从组成员获取AD用户对象和用户对象<br/> #PowerShell <br/> #ActiveDirectory

Get-ADUserObjectsAndUserGroupMemberObjects.ps1
"ADGroup", "User1" | %{

    Get-ADObject -Filter {Name -eq $_} | %{
        
        if($_.ObjectClass -eq "user"){
            
            Get-ADUser $_.DistinguishedName
            
        }elseif($_.ObjectClass -eq "group"){
        
            Get-ADGroupMember $_.DistinguishedName -Recursive | Get-ADUser 
        }
    }
}

powershell PowerShell:更新SharePoint用户警报<br/> #PowerShell <br/> #SharePoint

PowerShell:更新SharePoint用户警报<br/> #PowerShell <br/> #SharePoint

Update-SPUserAlerts.task.config.xml
<?xml version="1.0" encoding="UTF-16"?>
<Task version="1.2" xmlns="http://schemas.microsoft.com/windows/2004/02/mit/task">
  <RegistrationInfo>
    <Date>2013-03-20T14:18:21.6393172</Date>
    <Author>Janik von Rotz (http://janikvonrotz.ch)</Author>
	<Description>Update SharePoint User Alerts</Description>
  </RegistrationInfo>
  <Triggers>
    <CalendarTrigger>
      <StartBoundary>2013-01-01T03:00:00</StartBoundary>
      <Enabled>true</Enabled>
      <ScheduleByDay>
        <DaysInterval>1</DaysInterval>
      </ScheduleByDay>
    </CalendarTrigger>
  </Triggers>
  <Settings>
    <MultipleInstancesPolicy>IgnoreNew</MultipleInstancesPolicy>
    <DisallowStartIfOnBatteries>true</DisallowStartIfOnBatteries>
    <StopIfGoingOnBatteries>true</StopIfGoingOnBatteries>
    <AllowHardTerminate>true</AllowHardTerminate>
    <StartWhenAvailable>false</StartWhenAvailable>
    <RunOnlyIfNetworkAvailable>false</RunOnlyIfNetworkAvailable>
    <IdleSettings>
      <StopOnIdleEnd>true</StopOnIdleEnd>
      <RestartOnIdle>false</RestartOnIdle>
    </IdleSettings>
    <AllowStartOnDemand>true</AllowStartOnDemand>
    <Enabled>true</Enabled>
    <Hidden>false</Hidden>
    <RunOnlyIfIdle>false</RunOnlyIfIdle>
    <WakeToRun>false</WakeToRun>
    <ExecutionTimeLimit>P3D</ExecutionTimeLimit>
    <Priority>7</Priority>
  </Settings>
  <Actions Context="Author">
    <Exec>
      <Command>$PSapps.PowerShell</Command>
      <Arguments>$(Get-ChildItem -Path $PSscripts.Path -Filter "Update-SPUserAlerts.ps1" -Recurse).Fullname</Arguments>
      <WorkingDirectory>$PSProfile.Path</WorkingDirectory>
    </Exec>
  </Actions>
</Task>
Update-SPUserAlerts.ps1
<#
$Metadata = @{
	Title = "Update SharePoint User Alerts"
	Filename = "Update-SPUserAlerts.ps1"
	Description = ""
	Tags = "powershell, sharepoint, update, user, alerts"
	Project = ""
	Author = "Janik von Rotz"
	AuthorContact = "http://janikvonrotz.ch"
	CreateDate = "2014-01-02"
	LastEditDate = "2014-01-02"
	Url = ""
	Version = "1.0.0"
	License = @'
This work is licensed under the Creative Commons Attribution-ShareAlike 3.0 Switzerland License.
To view a copy of this license, visit http://creativecommons.org/licenses/by-sa/3.0/ch/ or 
send a letter to Creative Commons, 444 Castro Street, Suite 900, Mountain View, California, 94041, USA.
'@
}
#>

try{

    #--------------------------------------------------#
    # modules
    #--------------------------------------------------#
    if((Get-PSSnapin 'Microsoft.SharePoint.PowerShell' -ErrorAction SilentlyContinue) -eq $null){Add-PSSnapin 'Microsoft.SharePoint.PowerShell'}
    Import-Module ActiveDirectory
    
    #--------------------------------------------------#
    # settings
    #--------------------------------------------------#
    $Alerts = @(    
        @{    
            ID = 1
            ListUrl = "http://sharepoint.domain.ch/site/subsite/Lists/ListName/view.aspx"    
            SubscriberADUsersAndGroups = "ADGroup","ADUser"          
            Title = "`"Benachrichtigunggg `$Username`""
            AlertType = [Microsoft.SharePoint.SPAlertType]::List       
            DeliveryChannels = [Microsoft.SharePoint.SPAlertDeliveryChannels]::Email
            EventType = [Microsoft.SharePoint.SPEventType]::Add
            AlertFrequency = [Microsoft.SharePoint.SPAlertFrequency]::Immediate
            ListViewName = "View 2014"
            FilterIndex = 8
        }
    )
    
    #--------------------------------------------------#
    # function
    #--------------------------------------------------#
    function New-UnifiedAlertObject{
        
        param(
            $Title,
            $AlertType,
            $DeliveryChannels,
            $EventType,
            $AlertFrequency,
            $ListViewID,
            $FilterIndex
        )
        
        New-Object PSObject -Property @{
            Title = $Title
            AlertType = $AlertType
            DeliveryChannels = $DeliveryChannels
            EventType = $EventType
            AlertFrequency = $AlertFrequency
            ListViewID = $ListViewID
            AlertFilterIndex = $AlertFilterIndex
        }
    }

    #--------------------------------------------------#
    # main
    #--------------------------------------------------#
    
    $Alerts | %{
    
        # set vars
        $Message = "Update alerts with ID: $($_.ID)`n"
        $Alert = $_
    
        # get sp site
        $SPWeb = Get-SPWeb (Get-SPUrl $_.ListUrl).WebUrl

        # get name of the list
        $ListName = (Get-SPUrl $_.ListUrl).Url -replace ".*/",""

        # get the sp list object
        $SPList = $SPWeb.Lists[$ListName]
        
        $SPUsers = Get-SPUser -Web $SPWeb.Site.Url
        
        # get the id of the list view by name
        $SPListViewID = ($SPList.Views | where{$_.title -eq $SPListViewName -and $_.title -ne ""} | select -First 1).ID
        
        # get existing alerts
        $ExistingAlerts = $SPWeb.Alerts | where{$_.Properties["alertid"] -eq $Alert.ID}
        
        # cycle throught all users and  update, create or delete their alerts
        $UserWithAlerts = $_.SubscriberADUsersAndGroups | %{
        
            Get-ADObject -Filter {Name -eq $_} | %{
        
                if($_.ObjectClass -eq "user"){
                    
                    Get-ADUser $_.DistinguishedName
                    
                }elseif($_.ObjectClass -eq "group"){
                
                    Get-ADGroupMember $_.DistinguishedName -Recursive | Get-ADUser 
                }
            } | %{
                
                $ADUser = $_
            
                $SPUsers | where{$_.SID -eq $ADUser.SID} | %{$SPWeb.EnsureUser($_.Name)}
            }
        } | %{
        
            # create alert title
            $Username = $_.DisplayName
            $AlertTitle = Invoke-Command -ScriptBlock ([ScriptBlock]::Create($Alert.Title))
            
            # check if already alert exists with this id
            $AlertIS = $_.Alerts | where{$_.Properties["alertid"] -eq $Alert.ID} | select -First 1           
            
            # if exists update this alert
            if($AlertIS){
                
                # create alert objects to compare
                $AlertObjectIS = New-UnifiedAlertObject -Title $AlertIS.title `
                    -AlertType $AlertIS.AlertType `
                    -DeliveryChannels $AlertIS.DeliveryChannels `
                    -EventType $AlertIS.EventType `
                    -AlertFrequency $AlertIS.AlertFrequency `
                    -ListViewID $AlertIS.Properties["filterindex"] `
                    -FilterIndex $AlertIS.Properties["filterindex"]
                    
                $AlertObjectTo = New-UnifiedAlertObject -Title $AlertTitle `
                    -AlertType $Alert.AlertType `
                    -DeliveryChannels $Alert.DeliveryChannels `
                    -EventType $Alert.EventType `
                    -AlertFrequency $Alert.AlertFrequency `
                    -ListViewID $SPListViewID `
                    -FilterIndex $Alert.FilterIndex
                
                # only update changed attributes
                if(Compare-Object -ReferenceObject $AlertObjectTo -DifferenceObject $AlertObjectIS -Property Title, AlertType, DeliveryChannels, EventType, AlertFrequency, ListViewID, FilterIndex){
                    
                    $Message += "Update alert with ID: $($Alert.ID) for user: $($_.DisplayName)`n"
                    
                    if(Compare-Object -ReferenceObject $AlertObjectTo -DifferenceObject $AlertObjectIS -Property Title){$AlertIS.Title = $AlertObjectTo.Title}
                    if(Compare-Object -ReferenceObject $AlertObjectTo -DifferenceObject $AlertObjectIS -Property AlertType){$AlertIS.AlertType = $AlertObjectTo.AlertType}
                    if(Compare-Object -ReferenceObject $AlertObjectTo -DifferenceObject $AlertObjectIS -Property DeliveryChannels){$AlertIS.DeliveryChannels = $AlertObjectTo.DeliveryChannels}
                    if(Compare-Object -ReferenceObject $AlertObjectTo -DifferenceObject $AlertObjectIS -Property EventType){$AlertIS.EventType = $AlertObjectTo.EventType}
                    if(Compare-Object -ReferenceObject $AlertObjectTo -DifferenceObject $AlertObjectIS -Property AlertFrequency){$AlertIS.AlertFrequency = $AlertObjectTo.AlertFrequency}
                    if(Compare-Object -ReferenceObject $AlertObjectTo -DifferenceObject $AlertObjectIS -Property ListViewID){$AlertIS.Properties["viewid"] = $AlertObjectTo.ListViewID}
                    if(Compare-Object -ReferenceObject $AlertObjectTo -DifferenceObject $AlertObjectIS -Property FilterIndex){$AlertIS.Properties["filterindex"] = $AlertObjectTo.FilterIndex}
                    
                    # update changes
                    $AlertIS.Update()
                }
            }else{
            
                # create a new alert object  
                $Message += "Create alert with ID: $($Alert.ID) for user: $($_.DisplayName)`n"          
                $NewAlert = $_.Alerts.Add()
                
                # add attributes
                $NewAlert.Properties.Add("alertid",$Alert.ID)
                $NewAlert.Title = $AlertTitle                  
                if($SPListViewID){                
                    $NewAlert.Properties.Add("filterindex",$Alert.FilterIndex)
                    $NewAlert.Properties.Add("viewid",$SPListViewID)              
                }
                $NewAlert.AlertType = $Alert.AlertType
                $NewAlert.List = $SPList
                $NewAlert.DeliveryChannels = $Alert.DeliveryChannels
                $NewAlert.EventType = $Alert.EventType
                $NewAlert.AlertFrequency = $Alert.AlertFrequency

                # create the alert
                $NewAlert.Update()
            }
            
            # pipe the users to check alerts to delete
            $_
            
        } 
        
        # username array
        $UserWithAlerts = $UserWithAlerts | %{"$($_.UserLogin)"}
        
        # delete alerts
        $ExistingAlerts | where{$UserWithAlerts -notcontains $_.User} | %{
        
            $Message += "Delete alert with ID: $($Alert.ID) for user: $($_.User)`n"
            $SPWeb.Alerts.Delete($_.ID)        
        }
        
        Write-PPEventLog -Message $Message -Source "Update SharePoint User Alerts" -WriteMessage
    }
}catch{

    Write-PPErrorEventLog -Source "Update SharePoint User Alerts" -ClearErrorVariable    
}






powershell Sitecore网站部署脚本

Sitecore网站部署脚本

deploy.ps1
<#
.SYNOPSIS
Deployments made easy.  Calls webdeploy, to automate deployments.  It also calls the sitecore deserialization methods (via a page in your project)  to update content, and then publishes (optional)
Parameters: 
-packageFile        <required> Full path to package file 
-targetServer       <required> Webdeploy service url 
-userName           <optional> Username for remote server
-password           <optional> Password for remore user
-parametersFile     <required> Full path to environment settings file
-publishServerUrl   <optional> Base url of CM instance - required if publish is enabled
-noPublish          <optional> Supress call to publish content after deploy
-whatif             <optional> Run webdeploy test - shows which files will be affected, publishing is also supressed

.DESCRIPTION
Simply deployments for sitecore.  Deploys via web deploy to remote servers.  Deployments depending on configuration can be administrator or non-administrator deploys. 

Once package is deployed, the serialization methods to deserialize from files is run.  Typically this will be $serverUrl/sitecore/admin/deserialize.aspx and also a call to publish the updated content.

.PARAMETER packageFile
The web deploy package file - created with msbuild with the package option setup.

.PARAMETER targetServer

The web deploy service url - if you are using admin deployment url is typically <host>:8172/msdeploy.axd
If using a non admin account name for deployment, you need to include the IIS name - <host>:8172/msdeploy.axd?site='Default Website'

.PARAMETER parametersFile

SetParameters.xml customised for your specific environment. See webdeploy/msbuild for details to create these file(s).

.PARAMETER userName

The user name for the remote deploy

.PARAMETER password

The password for the remote deploy user.

.PARAMETER publishServerUrl

This should be the base url to the home page of your CM instance - eg http(s)://test.think.eu/

.PARAMETER noPublish
If publish is not required (eg need to deploy to multiple servers before publish) specify this.  Eg deployment to CD servers (Web1&web2) may not need publish until you run this package against the CM instance

.PARAMETER whatif
Run webdeploy in it's test mode - check output for what WILL be deployed.  If not supplied changes will be applied to destination server.

.EXAMPLE

.\deploy.ps1 -packageFile "c:\deploy\project.zip" -targetServer "https://server1:8172/msdeploy.axd?site='default website'" -userName nonAdminDeploy -password Pa$$w0rd -publishServerUrl "http://cms.server/" -whatif

Run to verify which files will be updated/added/removed on destination server, files are not actually modified.  No publishing or  deserializing will be done.

.EXAMPLE

.\deploy.ps1 -packageFile "c:\deploy\project.zip" -targetServer "https://server1:8172/msdeploy.axd?site='default website'" -userName nonAdminDeploy -password Pa$$w0rd -publishServerUrl "http://cms.server/" -noPublish

Update, add, remove files on destination server.  No publishing or deserializing will be done.

.EXAMPLE

.\deploy.ps1 -packageFile "c:\deploy\project.zip" -targetServer "https://cms.server:8172/msdeploy.axd?site='default website'" -userName nonAdminDeploy -password Pa$$w0rd -publishServerUrl "http://cms.server/"

Update, add, remove files on destination server.  Deserialization and publishing will be done
#>
param(
	[Parameter(Position=1)]
	[string] $packageFile,

	[Parameter(Position=2)]
	[string] $targetServer,
	
	[Parameter(Position=3)]
	[string] $parametersFile,
	
	[Parameter(Position=4)]
	[string] $userName,
	
	[Parameter(Position=5)]
	[string] $password,
	
	[Parameter(Position=6)]
	[string] $publishServerUrl,
	
	[switch] $noPublish,

	[switch] $whatif,
	
	[switch] $help
)
# Functions
function VerboseMessage([string]$message)
{
	Write-verbose $message
}

function WebDeploy
{
	Write-host "Web deploy"
	$msdeployPath = (Get-ItemProperty -path 'HKLM:\SOFTWARE\Microsoft\IIS Extensions\MSDeploy\*\' -name "InstallPath").InstallPath
	if($msdeployPath -eq ""){
		Write-error "MSdeploy is not installed on this machine."
		exit
	}
	
	VerboseMessage "msdeploy found at $msdeployPath"

	$whatifparam = ""
	if($whatif -eq $true)
	{
		VerboseMessage "Adding -whatif"
		$whatifparam = " -whatif"
	}
	
	$verbose = ""
	if($VerbosePreference)
	{
		VerboseMessage "Adding -verbose"
		$verbose = "-verbose"
	}
		

	$msdeployCommand=$msdeployPath +"msdeploy.exe" 
	VerboseMessage "MSDEPLOY: $msdeployCommand"
	$msdeployArgs = "-source:package='$packageFile' -dest:auto,wmsvc='$targetServer',userName='$userName',password='$password',authtype='basic',includeAcls='$false' -verb:sync -disableLink:AppPoolExtension  -disableLink:ContentExtension -disableLink:CertificateExtension -skip:skipaction='Delete',objectname='dirPath',absolutepath='Layouts' -skip:skipaction='Delete',objectname='dirPath',absolutepath='App_Data' -skip:skipaction='Delete',objectname='dirPath',absolutepath='Temp' -skip:skipaction='Delete',objectname='filePath',absolutepath='Temp' -skip:skipaction='Delete',objectname='dirPath',absolutepath='sitecore' -skip:skipaction='Delete',objectname='filePath',absolutepath='sitecore' -skip:skipaction='Delete',objectname='dirPath',absolutepath='sitecore modules' -skip:skipaction='Delete',objectname='dirPath',absolutepath='upload' -skip:skipaction='Delete',objectname='filePath',absolutepath='upload' -allowuntrusted  -skip:skipaction='Delete',objectname='dirPath',absolutepath='sitecore_files' -setParamFile:$parametersFile $whatifParam $verbose" 

	VerboseMessage "Full command: $msdeployCommand" 
	VerboseMessage "Full arguments: $msdeployArgs" 
	write-host "---- Webdeploy begin -----" -foregroundcolor Green
	write-host ""

	$process = (Start-Process -wait -passthru -nonewwindow -FilePath $msdeployCommand $msdeployArgs)
	write-host ""

	VerboseMessage("Webdeploy exit code " + $process.ExitCode)
	if($process.ExitCode -ne 0)
	{
		write-error -Message "Web deploy did not complete successfully.  Please review and rectify the problem." 
		exit
	}
	
	write-host "---- Webdeploy done -----"  -foregroundcolor Green
}

function Deserialize {
	if(($whatif -eq $true) -or ($noPublish -eq $true))
	{
		write-host "Skipping deseralize and publish due to whatif/noPublish detected" -foregroundcolor:yellow
		exit
	}

	Write-host "Deserialis(z)e All."
	$deserialise = "$publishServerUrl/deployment/DeserializeAll"
	VerboseMessage $deserialise
	Get-WebPage $deserialise

	Write-host "Publishing"
	$publish = "$publishServerUrl/deployment/Publish"

	VerboseMessage $publish
	Get-WebPage $publish

	write-host "All Done"
}

function CheckParams ($helpPath) {
	$showHelp = $false
	
	if (([string]::IsNullOrEmpty($packageFile)) -or ([string]::IsNullOrEmpty($targetServer)))
	{
		$showHelp = $true
	}

	#if not set to publish publishServerUrl is optional.
	if(($noPublish -eq $true) -or ($whatif -eq $true) )
	{
		#nothing to display
	}
	elseif([string]::IsNullOrEmpty($publishServerUrl))
	{
		$showHelp = $true;
	}
	if($showHelp -eq $true)
	{
		write-host ""
		write-host "Incorrect usage/missing parameters.  See below for further details." -foregroundcolor Red
		write-host ""
		get-help $helpPath -examples
		exit
	}
	
}

# END Functions

if($help)
{
	get-help $myInvocation.MyCommand.Path
	exit
}

CheckParams $myInvocation.MyCommand.Path

# Framework initialization
$scriptRoot = Split-Path (Resolve-Path $myInvocation.MyCommand.Path)
$env:PSModulePath = $env:PSModulePath + ";$scriptRoot\Framework"

# Import the webutils powercore cmdlet
Import-Module WebUtils\WebUtils

WebDeploy
Deserialize
DeployEnvironment.ps1
<#
.SYNOPSIS
Quick deploy to various environments.

.DESCRIPTION
Calls deploy.ps1 with relevant arguments for repeatable deployments.

.PARAMETER deployTo

Specify the environment to deploy to.  Currently supports "Dev-CMS" and "Dev-CD"

.PARAMETER TestDeploy

Test the deploy will work, and which files may be affected

.PARAMETER noPublish

Do a deploy, but will skip the final step of deserializing and publishing


#>
param(
	[Parameter(Position=1)]
	[string] $deployTo = "UKB_Dev_CMS",
	[switch] $TestDeploy,
	[switch] $noPublish,
	[Parameter(Mandatory=$true)][string]$username,
	[Parameter(Mandatory=$true)][string]$password
)

# Web Deploy Username and Password
#$username = "Deploy"
#$password = "Udish.Quaft7"

$devdatabase = "{databaseIP/name}"
$devdatabaseUsername = "{databaseusername}"
$devdatabasePassword = "{databasepassword}"

$siteID = "{EnvironmentSite}"

$targetHost = ""
$paramsFile = ""
if($deployTo -eq "CMS")
{
	$paramsFile = "{ParameterFile}.SetParameters.xml"
	$targetHost = "10.1.0.211"
	 
}
elseif($deployTo -eq "CDS")
{
	$paramsFile = "{ParameterFile}.SetParameters.xml"
	$targetHost = ""
	$noPublish = $True # It should be disabled via IIS permissions anyway
}


$path = split-path $MyInvocation.MyCommand.Path
write-host "Path: $path" 

$deployParams = "-packageFile $path\Think.UKB.Portal.Web.zip -targetServer https://"+ $targetHost +":8172/msdeploy.axd?site=$siteID -parametersFile $path\$paramsFile -userName $username -password $password -publishServerUrl http://$targetHost -verbose"

if($TestDeploy -eq $true){
	$deployParams = "$deployParams -whatif"
}
if($noPublish -eq $true){
	$deployParams = "$deployParams -noPublish"
}

write-host $deployParams -foregroundcolor yellow

invoke-expression "$path\deploy.ps1 $deployParams"

write-host "Migrating DB" -foregroundcolor yellow

invoke-expression "$path\Migrations\migrate.ps1 -Server $devdatabase -Database UKB -Username $devdatabaseUsername -Password $devdatabasePassword -MigrationsDir ApplicationMigrations -Maximum"

powershell PowerShell:使用KeePass打开TrueCrypt容器<br/> #Powershell <br/> #TrueCrypt <br/> #KeePass

PowerShell:使用KeePass打开TrueCrypt容器<br/> #Powershell <br/> #TrueCrypt <br/> #KeePass

Open-TrueCryptwithKeePass.ps1
& KeePass (Get-Path "$($PSconfigs.Path)..\..\..\..\..\Data\keepass\KeepassData.kdbx") -preselect:((Mount-TrueCyptContainer -Name pc1).Drive + ":\KeePass\keepass_data.key")
Read-Host "`nPress any key to dismount the TrueCrypt drive"
Dismount-TrueCyptContainer -Name pc1

powershell PowerShell:备份到外部驱动器<br/> #PowerShell

PowerShell:备份到外部驱动器<br/> #PowerShell

BackupTo-ExternalDrive.ps1
$Metadata = @{
	Title = "Backup To External Drive"
	Filename = "BackpTo-ExternalDrive.ps1"
	Description = ""
	Tags = ""
	Project = ""
	Author = "Janik von Rotz"
	AuthorContact = "http://janikvonrotz.ch"
	CreateDate = "2013-01-20"
	LastEditDate = "2014-09-25"
	Version = "2.0.0"
	License = @'
This work is licensed under the Creative Commons Attribution-NonCommercial-NoDerivs 3.0 Unported License.
To view a copy of this license, visit http://creativecommons.org/licenses/by-nc-nd/3.0/ or
send a letter to Creative Commons, 444 Castro Street, Suite 900, Mountain View, California, 94041, USA.
'@

}

$FilterFolder = "lwc"
$SourcePath = @("C:\OneDrive","C:\Local")
$SourceDrive = "C:\\"

get-PSDrive | %{
	if(Test-Path ($_.Root + $FilterFolder)){
		$DestPath = $(Join-Path $_.Root $FilterFolder)
	}
}

$Null = Read-Host "Copy from $SourcePath to $DestPath"

$SourcePath | %{
	$Destination = Join-Path $DestPath ($_ -replace $SourceDrive, "")	
	Write-host "Copy from $_ to $Destination"	
	& Robocopy $_ $Destination /MIR /R:1 /W:0
}

powershell PowerShell:获取所有成本中心和部门名称<br/> #PowerShell <br/> #ActiveDirectory

PowerShell:获取所有成本中心和部门名称<br/> #PowerShell <br/> #ActiveDirectory

Get-AllCostCentersAndDepartmentName.ps1
# extensionattribute2 ist cost center number
Get-ADUser -Filter * -Properties extensionattribute2, department | where{$_.extensionattribute2 -and $_.department} | select extensionattribute2, department -Unique | sort extensionattribute2 | out-gridview

powershell 分割逗号分隔字符串和使用PowerShell修剪项目的三种不同方法

分割逗号分隔字符串和使用PowerShell修剪项目的三种不同方法

csv-split-trim.ps1
$CSVData = @("One       ,   Two ,   Three    ")

#just split
$Data = $CSVData -split (",")

#first way of split and trim
$Data = $CSVData -split ',' | foreach {$_.Trim()}

#second way of split and trim
$CSVData.Split(",").Trim()

#third way of split and trim using regular expression
$Data = $CSVData -split '\s*,\s*'

powershell PowerShell:自定义Active Directory密码策略<br/> #PowerShell <br/> #ActiveDirectory

PowerShell:自定义Active Directory密码策略<br/> #PowerShell <br/> #ActiveDirectory

Disable-UsersWithPasswordNeverExpires.task.config.xml
<?xml version="1.0" encoding="UTF-16"?>
<Task version="1.2" xmlns="http://schemas.microsoft.com/windows/2004/02/mit/task">
  <RegistrationInfo>
    <Date>2013-03-20T14:18:21.6393172</Date>
    <Author>Janik von Rotz (http://janikvonrotz.ch)</Author>
	<Description>Disabe Users With Password Never Expires</Description>
  </RegistrationInfo>
  <Triggers>
    <CalendarTrigger>
      <StartBoundary>2013-01-01T03:30:00</StartBoundary>
      <Enabled>true</Enabled>
      <ScheduleByDay>
        <DaysInterval>1</DaysInterval>
      </ScheduleByDay>
    </CalendarTrigger>
  </Triggers>
  <Settings>
    <MultipleInstancesPolicy>IgnoreNew</MultipleInstancesPolicy>
    <DisallowStartIfOnBatteries>true</DisallowStartIfOnBatteries>
    <StopIfGoingOnBatteries>true</StopIfGoingOnBatteries>
    <AllowHardTerminate>true</AllowHardTerminate>
    <StartWhenAvailable>false</StartWhenAvailable>
    <RunOnlyIfNetworkAvailable>false</RunOnlyIfNetworkAvailable>
    <IdleSettings>
      <StopOnIdleEnd>true</StopOnIdleEnd>
      <RestartOnIdle>false</RestartOnIdle>
    </IdleSettings>
    <AllowStartOnDemand>true</AllowStartOnDemand>
    <Enabled>true</Enabled>
    <Hidden>false</Hidden>
    <RunOnlyIfIdle>false</RunOnlyIfIdle>
    <WakeToRun>false</WakeToRun>
    <ExecutionTimeLimit>P3D</ExecutionTimeLimit>
    <Priority>7</Priority>
  </Settings>
  <Actions Context="Author">
    <Exec>
      <Command>$PSapps.PowerShell</Command>
      <Arguments>$(Get-ChildItem -Path $PSscripts.Path -Filter "Disable-UsersWithPasswordNeverExpires.ps1" -Recurse).Fullname</Arguments>
      <WorkingDirectory>$PSProfile.Path</WorkingDirectory>
    </Exec>
  </Actions>
</Task>
Disable-UsersWithPasswordNeverExpires.ps1
<#
$Metadata = @{
	Title = "Disabe Users With Password Never Expires"
	Filename = "Disable-UsersWithPasswordNeverExpires.ps1"
	Description = ""
	Tags = "powershell, script, jobs"
	Project = ""
	Author = "Janik von Rotz"
	AuthorContact = "http://.janikvonrotz.ch"
	CreateDate = "2013-12-13"
	LastEditDate = "2013-12-13"
	Version = "1.0.0"
	License = @'
This work is licensed under the Creative Commons Attribution-NonCommercial-NoDerivs 3.0 Unported License.
To view a copy of this license, visit http://creativecommons.org/licenses/by-nc-nd/3.0/ or
send a letter to Creative Commons, 444 Castro Street, Suite 900, Mountain View, California, 94041, USA.
'@
}
#>

try{

    #--------------------------------------------------#
    # modules
    #--------------------------------------------------#    
    Import-Module ActiveDirectory
	
    #--------------------------------------------------#
    # settings
    #--------------------------------------------------#   
	$DaysBeforeDisablingUsersWithPasswordNeverExpires = 180
	$ADGroupWithUsersPasswordNeverExpires = "S-1-5-21-1744926098-708661255-2033415169-36648" # Memberof GroupName should be "SPO_PasswordNotification"      
    
    #--------------------------------------------------#
    # main
    #--------------------------------------------------#
             
    Get-ADGroupMember $ADGroupWithUsersPasswordNeverExpires -Recursive | 
    Get-ADUser -Properties Enabled, PasswordNeverExpires, PasswordLastSet |
    Select *, @{L = "PasswordExpires";E = {((Get-Date) - ($_.PasswordLastSet)).Days}} |
    where{($_.Enabled -eq $true) -and ($_.PasswordNeverExpires -eq $true) -and ($_.PasswordExpires -eq $DaysBeforeDisablingUsersWithPasswordNeverExpires)} | %{ 
         
       Write-PPEventLog "Enabled Passwort Expiration for: $($_.UserPrincipalName)." -WriteMessage -Source "Disabe Users With Password Never Expires"                  
       Set-ADUser -Identity $_.DistinguishedName -PasswordNeverExpires $false        
    }   
}catch{

	Write-PPErrorEventLog -Source "Disabe Users With Password Never Expires" -ClearErrorVariable
}

powershell 在当前服务器场中安装/删除SharePoint帮助网站集文件。

在当前服务器场中安装/删除SharePoint帮助网站集文件。

InstallHelpFiles.ps1
Get-SPHelpCollection

Install-SPHelpCollection -LiteralPath

Uninstall-SPHelpCollection