Powershell Script to Update Central PolicyDefintions Store against the local machine
Hi all,
i've created a powershell script to update my central policydefinitions store against a local machine for example the newest domaincontroller or member server. It can be started with the parameters -source (for the source directory e.g. C:\Windows\PolicyDefinitions)
and -destination (for the target directory e.g. C:\Windows\SYSVOL_DFSR\sysvol\domain.local\Policies\PolicyDefinitions).
It checks the source directory for language folders and admx files. Compares the Fileage with the files in the target directory and allows you to replace them. Maybe this script is helpful for one of you and maybe someone can check it and give me some feedback
to make this script better.
Please be very careful with this and try it on your own risk. You should try it in a testenvironment first. Or e.g. against an empty target directory. In the first version the script asks for confirmation for every single change against the target directory.
You can find it here: http://pastebin.com/dwJytWck
Regards
Hi,
You may also want to add this script to the script repository:
https://gallery.technet.microsoft.com/scriptcenter
That'll make it easier for more people to find.
Don't retire TechNet! -
(Don't give up yet - 13,085+ strong and growing)
Similar Messages
-
Just got a new MacMini. Migrated files using Time Machine. However, now, on Launchpad, I see several Firmware updates that were relevant for the old machine, but not for the new one. How do I get rid of these updates? They won't delete!
Only thing I can think of is trying this Lion trick...
http://www.cultofmac.com/106030/how-to-nuke-lions-launchpad-and-start-over/10603 0/ -
Store documents in local machine of file system not in sap dms
Hi,
Can i store documents in local machine not in sap Database . Client will not use content server for storing document.
so how to store document in local file system n how to configure ?
please help.
Dipak.Hello Sir,
When I try to check in in storage as 'VAULT' it send error 'Attempt to set up connection to failed'
attaching screen shot of error
I customize in DC20 for Vault:
For: "Define data carrier type "vault""
Data carr. type = ZD
For: "Define vault"
Data carr.name = ZDC_TEST
Data carr. type= ZD
Desprition = Test
Vault path = \\10.181.210.10\_SAP Practice\SAP DMS\DMS_Data_carrier -> this is the network path.
For: "Define data carrier type "server, front end"
Type (data carr. type) = DC
Description = Frontend test
Path = c:\temp\
For: "Define mount ponts/logical drive"
Data carr. = Default/ZDC
Prefix for access path = c:\temp\
Please tell me if have configured any wrong configuration or need to add any additional configuration
Thanks.
Dipak. -
Powershell script to update mailbox search
I am trying to update a mailbox search using a powershell script:
Stop-MailboxSearch -Identity "LitHolds" -confirm:$false
$members = (import-csv -Path "Path"| ForEach-Object{$_.SamAccountName})
foreach ($user in $members)
Set-MailboxSearch -Identity "LitHolds" -SourceMailboxes $user.samaccountname
Start-MailboxSearch -Identity "LitHolds" -confirm:$false
I essentially have our sysadmins populating a csv file and then they run this script manually every night with the latest updates. They are telling me that the mailbox search is empty.
When I run the script I am getting a watson error immediately after with the following:
WARNING: An unexpected error has occurred and a Watson dump is being generated: Value cannot be null.
Parameter name: legacyDN
Value cannot be null.
Parameter name: legacyDN
+ CategoryInfo : NotSpecified: (:) [Stop-MailboxSearch], ArgumentNullException
+ FullyQualifiedErrorId : System.ArgumentNullException,Microsoft.Exchange.Management.Tasks.StopMailboxSearch
+ PSComputerName : Exchange Server Name
What I don't understand is why it's looking for a legacyDN??
Anyone able to do something similar?
ChuckHi Chuck,
I would like to verify if you have a legacy Exchange.
The LegacyDN property indicates the legacyDN of the mailbox and matches the legacyExchangeDN attribute of the user object in Microsoft Active Directory.
If there is any update, please feel free to let me know.
Best regards,
Amy
Amy Wang
TechNet Community Support -
PowerShell script to update quick launch navigation.
Hi,
We recently did some reorganization, which involved nesting some sites within others. Some of these sites were based on a custom template, and as a consequence, the quick launch URLs, although relative, did not update. I found some potentially
useful PowerShell script, from
here.
function Repair-SPLeftNavigation {
[CmdletBinding()]
Param(
[Parameter(Mandatory=$true)][System.String]$Web,
[Parameter(Mandatory=$true)][System.String]$FindString,
[Parameter(Mandatory=$true)][System.String]$ReplaceString
Add-PSSnapin Microsoft.SharePoint.PowerShell -ErrorAction SilentlyContinue
$SPWeb = Get-SPWeb $Web
$SPWeb.Navigation.QuickLaunch | ForEach-Object {
if($_.Url -match $FindString){
$linkUrl = $_.Url
Write-Host "Updating $linkUrl with new URL"
$_.Url = $_.Url.Replace($FindString,$ReplaceString)
$_.Update()
$_.Children | ForEach-Object {
if($_.Url -match $FindString){
$linkUrl = $_.Url
Write-Host "Updating $linkUrl with new URL"
$_.Url = $_.Url.Replace($FindString,$ReplaceString)
$_.Update()
$SPWeb.Dispose()
The problem I see is that the original URL string is '/data/studysites/site' and the replacement URL is '/researchers/data/studysites/site', and it looks like this script would go through and repair the incorrect links while
breaking the correct ones.
I'm trying to use the -like operator instead of the -match operators to match the $FindString based on a URL that
begins with '/data/studysites/site' rather than contains it, which should (I'm thinking) exclude correct links (which already start with '/researchers.'). This isn't going well though. I am guessing I don't understand how to use the -like
operator with wilodcard variables. Here's what I came up with.
function Repair-SPLeftNavigation {
[CmdletBinding()]
Param(
[Parameter(Mandatory=$true)][System.String]$Web,
[Parameter(Mandatory=$true)][System.String]$FindString,
[Parameter(Mandatory=$true)][System.String]$ReplaceString
Add-PSSnapin Microsoft.SharePoint.PowerShell -ErrorAction SilentlyContinue
$SPWeb = Get-SPWeb $Web
$SPWeb.Navigation.QuickLaunch | ForEach-Object {
if($_.Url -like '$FindString*'){
$linkUrl = $_.Url
Write-Host "Updating $linkUrl with new URL"
$_.Url = $_.Url.Replace($FindString,$ReplaceString)
$_.Update()
$_.Children | ForEach-Object {
if($_.Url -like '$FindString*'){
$linkUrl = $_.Url
Write-Host "Updating $linkUrl with new URL"
$_.Url = $_.Url.Replace($FindString,$ReplaceString)
$_.Update()
$SPWeb.Dispose()
}#endFunction
Help much appreciated!Hi Mike,
Tried that, and in that case, it didn't seem to do anything.
function Repair-SPLeftNavigation {
[CmdletBinding()]
Param(
[Parameter(Mandatory=$true)][System.String]$Web,
[Parameter(Mandatory=$true)][System.String]$FindString,
[Parameter(Mandatory=$true)][System.String]$ReplaceString
Add-PSSnapin Microsoft.SharePoint.PowerShell -ErrorAction SilentlyContinue
$SPWeb = Get-SPWeb $Web
$SPWeb.Navigation.QuickLaunch | ForEach-Object {
if($_.IsExternal -AND $_.Url -like "$FindString*"){
$linkUrl = $_.Url
Write-Host "Updating $linkUrl with new URL"
$_.Url = $_.Url.Replace($FindString,$ReplaceString)
$_.Update()
$_.Children | ForEach-Object {
if($_.IsExternal -AND $_.Url -like "$FindString*"){
$linkUrl = $_.Url
Write-Host "Updating $linkUrl with new URL"
$_.Url = $_.Url.Replace($FindString,$ReplaceString)
$_.Update()
$SPWeb.Dispose()
I ran the script, adding the -verbose flag, and got this:
PS C:\Scripts> Repair-SPLeftNavigation -Web http://loki/researchers/data/WHIStudies/StudySites/ -FindString "/data/WHIStudies/StudySites" -ReplaceString "/researchers/data/WHIStudies/StudySites" -Verbose
VERBOSE: Leaving BeginProcessing Method of Get-SPWeb.
VERBOSE: Leaving ProcessRecord Method of Get-SPWeb.
VERBOSE: Leaving EndProcessing Method of Get-SPWeb.
PS C:\Scripts>
I then tried expanding the quotes to include the whole IF statement:
function Repair-SPLeftNavigation {
[CmdletBinding()]
Param(
[Parameter(Mandatory=$true)][System.String]$Web,
[Parameter(Mandatory=$true)][System.String]$FindString,
[Parameter(Mandatory=$true)][System.String]$ReplaceString
Add-PSSnapin Microsoft.SharePoint.PowerShell -ErrorAction SilentlyContinue
$SPWeb = Get-SPWeb $Web
$SPWeb.Navigation.QuickLaunch | ForEach-Object {
if("$_.IsExternal -AND $_.Url -like '$FindString*'"){
$linkUrl = $_.Url
Write-Host "Updating $linkUrl with new URL"
$_.Url = $_.Url.Replace($FindString,$ReplaceString)
$_.Update()
$_.Children | ForEach-Object {
if("$_.IsExternal -AND $_.Url -like '$FindString*'"){
$linkUrl = $_.Url
Write-Host "Updating $linkUrl with new URL"
$_.Url = $_.Url.Replace($FindString,$ReplaceString)
$_.Update()
$SPWeb.Dispose()
This got me the following error. It seems it is trying to "fix" some URLs that don't need fixing, but not fixing those that do. :)
Updating /researchers/data/WHIStudies/StudySites/AS297 with new URL
Exception calling "Update" with "0" argument(s): "Cannot open "/researchers/researchers/data/WHIStudies/StudySites/AS297": no such file or folder."
At C:\Scripts\Repair-SPLeftNavigation.ps1:15 char:9
+ $_.Update()
+ ~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : SPException
Thanks!
Josh -
PowerShell script to update ContentType of existing records in Document Library
we are using Document Library in SharePoint 2010 environment. there are about 200 document
present in the document library which have been identified (based on location - England and employee type - FT) and now i have to change the content type of these 200 documents to a new content type 'New FT'. I'm using the below power shell code for the purpose
$webUrl = "http://www.site.com/sites/Library/"
$web = Get-SPWeb -Identity $webUrl
$list = $web.Lists["CURRENT FTE"]
$spQuery = New-Object Microsoft.SharePoint.SPQuery
$spQuery.ViewAttributes = "Scope='Recursive'";
$spQuery.ListItemCollectionPosition = $listItems.ListItemCollectionPosition
foreach($item in $listItems)
$lookup = [Microsoft.SharePoint.SPFieldLookupValue]$item["ROLE"];
$role = $lookup.LookupValue;
$EMPTYPE = $item["EMP TYPE"]
$lookup4 = [Microsoft.SharePoint.SPFieldLookupValue]$item["Location"];
$LOCATION = $lookup4.LookupValue;
$ContentTypeName = $item.ContentType.Name
$ContentTypeID = $item.ContentType.Id
if ($LOCATION -eq "England")
if($EMPTYPE -eq "FT")
#CheckList - 1
Write-Output "ID - $($item.id) "
Write-Output "Name - $($item.name)"
Write-Output "Role - $($role) "
Write-Output "emptype - $($EMPTYPE) "
Write-Output "location - $($LOCATION) "
Write-Output "Content Type Name - $($ContentTypeName) "
Write-Output "Content Type ID - $($ContentTypeID) "
Write-Output " "
$newct = $list.ContentTypes["New FT"]
$newctid = $newct.ID
If (($newct -ne $null) -and ($newctid -ne $null))
$item["ContentTypeId"] = $newctid
$item.Update()
$newContentTypeName = $item.ContentType.Name
$newContentTypeID = $item.ContentType.Id
#CheckList - 2
Write-Output "ID - $($item.id) "
Write-Output "Name - $($item.name)"
Write-Output "Role - $($role) "
Write-Output "emptype - $($EMPTYPE) "
Write-Output "location - $($LOCATION) "
Write-Output "Content Type Name - $($newContentTypeName) "
Write-Output "Content Type ID - $($newContentTypeID) "
Write-Output " "
Now the code identifies each document/record and then prints the details as listed on CheckList - 1, then i do an update and try to print the new updated values in CheckList
- 2 - but the problem is the CheckList -2 doesn't print the updated content type and updated content type ID ($newContentTypeName, $newContentTypeID).
Am i doing some thing wrong here , Please advise ! (feel free to update the code if necessary)Hi,
I suggest you consider the Check Out status of these documents before change the content type.
You can take the code from the link below for a test in your environment:
http://get-spscripts.com/2010/10/change-content-type-set-on-files-in.html
Best regards
Patrick Liang
TechNet Community Support -
Can't download or update through app store since the new version
For a couple of weeks now since the new itunes update i have no longer been able to update or download apps through the appstore on my iphone4. When i go to purchase and i go to enter my password, after one or 2 digits it disappears. I have credit in the system so there is not problem there. Seems to be the update. Not happy, please fix this!!
Having the exact same problem, help!
-
need to run through a list of old to new data (.csv) file and change them in a sharepoint list - can not make it work
here is my base attempt.
$web = Get-SPWeb site url
$list = $web.lists["List Name"]
$item = $list.items.getitembyid(select from the items.csv old)
$modifiedBy = $item["Editor"]
#Editor is the internal name of the Modified By column
$item["old"] = "new from the .csv file parsed by power sehll
$ite.Syste,Update($false);
$web.Dispose()Hi,
According to your description, my understanding is that you want to update SharePoint field value from a CSV file recursively.
We can import CSV file using the Import-CSV –path command, then update the field value in the foreach loop.
Here is a code snippet for your reference:
Add-PSSnapin Microsoft.SharePoint.PowerShell -ErrorAction SilentlyContinue
$csvVariable= Import-CSV -path "http://sp2010.contoso.com/finance/"
# Destination site collection
$WebURL = "http://sp2010.contoso.com/sites/Utility/"
# Destination list name
$listName = "Inventory"
#Get the SPWeb object and save it to a variable
$web = Get-SPWeb -identity $WebURL
#Get the SPList object to retrieve the list
$list = $web.Lists[$listName]
#Get all items in this list and save them to a variable
$items = $list.items
#loop through csv file
foreach($row in $csvVariable)
#loop through SharePoint list
foreach($item in $items)
$item["ID #"]=$row."ID #"
$item.Update()
$web.Dispose()
Here are some detailed articles for your reference:
http://blogs.technet.com/b/stuffstevesays/archive/2013/06/07/populating-a-sharepoint-list-using-powershell.aspx
http://social.technet.microsoft.com/wiki/contents/articles/25125.sharepoint-2013-powershell-to-copy-or-update-list-items-across-sharepoint-sites-and-farms.aspx
Thanks
Best Regards
Jerry Guo
TechNet Community Support -
PowerShell Script for updating accounts in CSV
Hi Experts...!!!!
I need to have a power shell script that can update the status(Enable/disable) accounts given in a .csv file with DNs of the user accounts in it....
Any suggestions...
Thank You...
TechSpec90I recommend that you start by searching for answers:
This comes up as the first item in a search:
https://technet.microsoft.com/en-us/library/ee617200.aspx
\_(ツ)_/ -
Update a filed value with powershell script with ordery by and where condition
Hi
I have below powershell script to update list columns but how i update a field value with ordery by a column and where condition
below is the part of my script
$list = $web.Lists[$listName]
$items = $list.items
$internal_counter = 1
#Go through all items
foreach($item in $items)
if($item["CourtNO"] -eq $null)
#if($item["CourtNo"] -eq '1')
$item["CaseNo"] = $internal_counter
#how to add a column ordery by Title
# and where Title field value from 1 to 10
$internal_counter++
adilHi,
You mean that you only need to update all items with Title field value in range 1..10 and order by them before run the loop statement update?
If so, use CAML query to get the items only match the condition.
#Build Query
$spQuery = New-Object Microsoft.SharePoint.SPQuery
$query = '<Where><And><Gte><FieldRef Name="Title" /><Value Type="Text">0</Value></Gte><Lte><FieldRef Name="Title" /><Value Type="Text">10</Value></Lte></And></Where><OrderBy><FieldRef
Name="Title"/></OrderBy>'
$spQuery.Query = $query
$spQuery.RowLimit = $list.ItemCount
$items = $list.GetItems($spQuery)
Hope this help!
/Hai
Visit my blog: My Blog | Visit my forum:
SharePoint Community for Vietnamese |
Bamboo Solution Corporation -
Please help me to get this done!....Thanks in Advance
This is current script I use to update AD record but its taking user id to pick the user in AD, which is some time give error not update properly..
# UpdateUsers.ps1
# PowerShell program to update Active Directory users from the information in a
# Microsoft Excel spreadsheet. Only single-valued string attributes supported.
# Author: Richard Mueller
# PowerShell Version 1.0
# September 12, 2011
Trap
If ("$_".StartsWith("Cannot load COM type Excel.Application"))
"Excel application not found, program aborted"
Add-Content -Path $LogFile -Value "## Excel application not found"
Add-Content -Path $LogFile -Value " $_"
Add-Content -Path $LogFile -Value $("Program aborted: " + (Get-Date).ToString())
Break
If (("$_".StartsWith("Exception has been thrown")) -and ($Step -eq "4"))
"Excel spreadsheet not found, program aborted"
Add-Content -Path $LogFile -Value "## Excel spreadsheet not found: $ExcelPath"
Add-Content -Path $LogFile -Value " $_"
Add-Content -Path $LogFile -Value $("Program aborted: " + (Get-Date).ToString())
Break
If ("$_".StartsWith("The server is not operational"))
"Domain Controller not found, program aborted"
Add-Content -Path $LogFile -Value "## Domain Controller not found"
Add-Content -Path $LogFile -Value " $_"
Add-Content -Path $LogFile -Value $("Program aborted: " + (Get-Date).ToString())
Break
If ("$_".StartsWith("The directory service is unavailable"))
"Active Directory not found, program aborted"
Add-Content -Path $LogFile -Value "## Active Directory not found"
Add-Content -Path $LogFile -Value " $_"
Add-Content -Path $LogFile -Value $("Program aborted: " + (Get-Date).ToString())
Break
If ("$_".StartsWith("The specified domain"))
"Domain not found, program aborted"
Add-Content -Path $LogFile -Value "## Domain not found"
Add-Content -Path $LogFile -Value " $_"
Add-Content -Path $LogFile -Value $("Program aborted: " + (Get-Date).ToString())
Break
"Unexpected error: $_"
Add-Content -Path $LogFile -Value "## Unexpected error: $_"
Add-Content -Path $LogFile -Value " Step: $Step"
Break
Function CleanUp
Trap
"Error during cleanup: $_"
Add-Content -Path $LogFile -Value "## Error during cleanup: $_"
$Script:Errors = $Script:Errors + 1
Continue
# Function to release Excel objects from memory.
Do {$x = [System.Runtime.InteropServices.Marshal]::ReleaseComObject($Columns)} While ($x -gt -1)
Do {$x = [System.Runtime.InteropServices.Marshal]::ReleaseComObject($Rows)} While ($x -gt -1)
Do {$x = [System.Runtime.InteropServices.Marshal]::ReleaseComObject($Range)} While ($x -gt -1)
Do {$x = [System.Runtime.InteropServices.Marshal]::ReleaseComObject($Sheet)} While ($x -gt -1)
Do {$x = [System.Runtime.InteropServices.Marshal]::ReleaseComObject($Worksheets)} While ($x -gt -1)
$Workbook.Close($False)
Do {$x = [System.Runtime.InteropServices.Marshal]::ReleaseComObject($Workbook)} While ($x -gt -1)
Do {$x = [System.Runtime.InteropServices.Marshal]::ReleaseComObject($Workbooks)} While ($x -gt -1)
$Excel.Quit()
Do {$x = [System.Runtime.InteropServices.Marshal]::ReleaseComObject($Excel)} While ($x -gt -1)
# Specify paths to spreadsheet and log file.
$Script:Errors = 0
$Step = "1"
$ExcelPath = "c:\scripts\UpdateUsers.xls"
$LogFile = "c:\scripts\UpdateUsers.log"
Write-Host "Please Standby..."
# Add to the log file.
$Step = "2"
Add-Content -Path $LogFile -Value "------------------------------------------------" -ErrorAction Stop
Add-Content -Path $LogFile -Value "UpdateUsers.ps1 Version 1.0 (September 12, 2011)"
Add-Content -Path $LogFile -Value $("Started: " + (Get-Date).ToString())
Add-Content -Path $LogFile -Value "Spreadsheet: $ExcelPath"
Add-Content -Path $LogFile -Value "Log file: $LogFile"
$Step = "3"
# Open specified Excel spreadsheet.
$Excel = New-Object -ComObject "Excel.Application"
$Workbooks = $Excel.Workbooks
$Step = "4"
$Workbook = $Workbooks.Open($ExcelPath)
$Worksheets = $Workbook.Worksheets
$Sheet = $Worksheets.Item(1)
$Range = $Sheet.UsedRange
$Rows = $Range.Rows
$Columns = $Range.Columns
$Step = "5"
# Hash table of attribute syntaxes.
# The LDAP display names will be read from the spreadsheet.
# The corresponding syntaxes will be read from the Schema container.
$Attributes = @{}
# Array of spreadsheet column headings.
$Cols = @()
$Step = "6"
# Read attribute LDAP Display Names from the first row of the spreadsheet.
$ID = 0
For ($k = 1; $k -le $Columns.Count; $k = $k + 1)
# Retrieve column heading, the lDAPDisplayName of an attribute.
$Value = $Sheet.Cells.Item(1, $k).Text
# Keep track of all column headings.
$Cols += $Value
# Skip duplicates in hash table.
If ($Attributes.ContainsKey($Value) -eq $False)
# Default is "NotFound", until found in the AD Schema.
$Attributes.Add($Value, "NotFound")
# Keep track of which column uniquely identifies users.
If ($Value.ToLower() -eq "distinguishedname") {$ID = $k}
If (($Value.ToLower() -eq "samaccountname") -and ($ID -eq 0)) {$ID = $k}
# This script cannot be used to rename users.
If ($value.ToLower() -eq "cn")
Add-Content -Path $LogFile -Value "## This script cannot be used to rename users"
Add-Content -Path $LogFile -Value " Do not specify the cn attribute in the spreadsheet"
Add-Content -Path $LogFile -Value $("Program aborted: " + (Get-Date).ToString())
CleanUp
Return "Program aborted: cn attribute found in spreadsheet" `
+ "`nSee log file: $LogFile"
$Step = "7"
If ($ID -eq 0)
Add-Content -Path $LogFile -Value "## No column found to identify users"
Add-Content -Path $LogFile -Value " One column must be distinguishedName or sAMAccountName"
Add-Content -Path $LogFile -Value $("Program aborted: " + (Get-Date).ToString())
CleanUp
Return "Program aborted: No column found in spreadsheet to identify users" `
+ "`nSee log file: $LogFile"
# Create filter to query for attributes in the schema.
$Attrs = $Attributes.Keys
$Filter = "(&(objectCategory=AttributeSchema)(|"
ForEach ($Attr In $Attrs)
$Filter = $Filter + "(lDAPDisplayName=$Attr)"
$Filter = $Filter + "))"
$Step = "8"
$RootDSE = [System.DirectoryServices.DirectoryEntry]([ADSI]"LDAP://RootDSE")
$Domain = $RootDSE.Get("defaultNamingContext")
$Schema = $RootDSE.Get("schemaNamingContext")
$Step = "9"
# Use the NameTranslate object.
$objTrans = New-Object -comObject "NameTranslate"
$objNT = $objTrans.GetType()
# Initialize NameTranslate by locating the Global Catalog.
$objNT.InvokeMember("Init", "InvokeMethod", $Null, $objTrans, (3, $Null))
$Step = "10"
# Retrieve NetBIOS name of the current domain.
$objNT.InvokeMember("Set", "InvokeMethod", $Null, $objTrans, (1, "$Domain"))
$NetBIOSDomain = $objNT.InvokeMember("Get", "InvokeMethod", $Null, $objTrans, 3)
Add-Content -Path $LogFile -Value "NetBIOS name of domain: $NetBIOSDomain"
$Step = "11"
$Searcher = New-Object System.DirectoryServices.DirectorySearcher
$Searcher.SearchRoot = [ADSI]"LDAP://$Schema"
$Searcher.PageSize = 200
$Searcher.SearchScope = "subtree"
$Searcher.PropertiesToLoad.Add("lDAPDisplayName") > $Null
$Searcher.PropertiesToLoad.Add("attributeSyntax") > $Null
$Searcher.PropertiesToLoad.Add("isSingleValued") > $Null
$Searcher.PropertiesToLoad.Add("systemFlags") > $Null
# Filter on specified attributes.
$Searcher.Filter = $Filter
$Step = "12"
# Query Active Directory.
$Results = $Searcher.FindAll()
# Enumerate recordset.
ForEach ($Result In $Results)
# Retrieve properties of attributes.
$Name = $Result.Properties.Item("lDAPDisplayName")[0]
$SysFlags = $Result.Properties.Item("systemFlags")[0]
$SyntaxNum = $Result.Properties.Item("attributeSyntax")[0]
$SingleValued = $Result.Properties.Item("isSingleValued")[0]
# Only single-valued string attributes supported by this version of the program.
Switch ($SyntaxNum)
"2.5.5.12" {$Syntax = "String"}
Default {$Syntax = "NotSupported"}
If ($Name.ToLower() -eq "distinguishedname") {$Syntax = "DN"}
If (($SysFlags -band 4) -ne 0)
$Attributes[$Name] = "Constructed"
Else
If ($SingleValued -eq $True)
$Attributes[$Name] = $Syntax
Else
$Attributes[$Name] = "NotSupported"
$Step = "13"
# Check if any attributes not found or have unsupported syntax.
$Found = $True
ForEach ($Attr In $Attrs)
$Syntax = $Attributes[$Attr]
If ($Syntax -eq "NotFound")
Add-Content -Path $LogFile -Value "## Attribute $Attr not found in schema"
"Attribute $Attr not found in schema"
$Found = $False
If ($Syntax -eq "NotSupported")
Add-Content -Path $LogFile -Value "## Attribute $Attr has a syntax that is not supported"
"Attribute $Attr has a syntax that is not supported"
$Found = $False
If ($Syntax -eq "Constructed")
Add-Content -Path $LogFile -Value "## Attribute $Attr is operational, so is not supported"
"Attribute $Attr is operational, so is not supported"
$Found = $False
$Step = "14"
If ($Found -eq $False)
Add-Content -Path $LogFile -Value $("Program aborted: " + (Get-Date).ToString())
CleanUp
Return "Program aborted" `
+ "`nSee log file: $LogFile"
# Read remaining rows of the spreadsheet, until the first blank value is found
# in the column that identifies users.
$Step = "15"
$Script:Updated = 0
$Script:Unchanged = 0
$j = 2
Do {
# Retieve ID value for the user first.
$Value = $Sheet.Cells.Item($J, $ID).Text
$Found = $False
$Step = "16"
If ($Cols[$ID - 1] -eq "distinguishedname")
# Any forward slash characters must be escaped.
$DN = $Value.Replace("/", "\/")
# Bind to the user object.
# If user not found, $User.Name will be $Null.
$User = [ADSI]"LDAP://$DN"
If ($User.Name -ne $Null)
$Found = $True
$Step = "17"
If ($Cols[$ID - 1] -eq "samaccountname")
Trap
Write-Host ""
"Error translating name: $_"
Add-Content -Path $LogFile -Value "## Error translating name $Value"
Add-Content -Path $LogFile -Value " Description: $_"
$Script:Errors = $Script:Errors + 1
Continue
# Convert sAMAccountName to distinguishedName.
$DN = ""
$Step = "18"
$objNT.InvokeMember("Set", "InvokeMethod", $Null, $objTrans, (3, "$NetBIOSDomain$Value"))
$DN = $objNT.InvokeMember("Get", "InvokeMethod", $Null, $objTrans, 1)
$Step = "19"
If ($DN -ne "")
$Step = "20"
# Any forward slash characters must be escaped.
$DN = $DN.Replace("/", "\/")
# Bind to the user object.
$User = [ADSI]"LDAP://$DN"
$Found = $True
If ($Found -eq $True)
$Step = "21"
# Read remaining values for this user.
$Changed = $False
For ($k = 1; $k -le $Columns.Count; $k = $k + 1)
# Skip the identifying column.
If ($k -ne $ID)
$Step = "22"
# Retrieve attribute name for this column from array.
$AttrName = $Cols[$k - 1]
# Retrieve attribute syntax from hash table.
$Syntax = $Attributes[$AttrName]
$Step = "23"
# Retrieve attribute value for this user.
$Value = $Sheet.Cells.Item($j, $k).Text
# Skip blank values.
If ($Value -ne "")
If ($Syntax -eq "String")
Trap
If ("$_".StartsWith("The directory property cannot be found"))
Continue
Else
Write-Host ""
"Error retrieving value from Active Directory: $_"
Add-Content -Path $LogFile -Value "## Error retrieving $AttrName for user $DN"
Add-Content -Path $LogFile -Value " Description: $_"
$Script:Errors = $Script:Errors + 1
Continue
$Step = "24"
# Single-valued string attribute.
# Retrieve existing value.
$OldValue = ""
$OldValue = $User.Get($AttrName)
# Check if existing value to be deleted.
If ($Value.ToLower() -eq ".delete")
If ($OldValue -ne "")
If ($AttrName.ToLower -eq "samaccountname")
Add-Content -Path $LogFile -Value `
"## Mandatory attribute sAMAccountName cannot be cleared for user: $DN"
$Script:Errors = $Script:Errors + 1
Else
Trap
Write-Host ""
"Error deleting value from Active Directory: $_"
Add-Content -Path $LogFile -Value "## Error deleting $AttrName for user $DN"
Add-Content -Path $LogFile -Value " Description: $_"
$Script:Errors = $Script:Errors + 1
Continue
$Step = "25"
# Make the attribute value "not set".
$User.PutEx(1, $AttrName, 0)
$Changed = $True
Else
$Step = "26"
# Check if new value from spreadsheet different.
If ($Value -ne $OldValue)
Trap
Write-Host ""
"Error assigning value from Active Directory: $_"
Add-Content -Path $LogFile -Value "## Error assigning $AttrName for user $DN"
Add-Content -Path $LogFile -Value " Description: $_"
$Script:Errors = $Script:Errors + 1
Continue
# Assign the new value to the attribute.
$User.Put($AttrName, $Value)
$Changed = $True
Else
# Unexpected error.
Add-Content -Path $LogFile -Value `
"## Unexpected syntax: $Syntax for attribute $AttrName for user $DN"
$Script:Errors = $Script:Errors + 1
If ($Changed -eq $True)
Trap
Write-Host ""
"Error saving to Active Directory: $_"
Add-Content -Path $LogFile -Value "## Error saving to AD for user $DN"
Add-Content -Path $LogFile -Value " Description: $_"
$Script:Errors = $Script:Errors + 1
$Script:Updated = $Script:Updated - 1
Continue
$User.SetInfo()
Add-Content -Path $LogFile -Value "Update user: $DN"
Write-Host "." -NoNewLine
$Script:Updated = $Script:Updated + 1
Else
Add-Content -Path $LogFile -Value "User unchanged: $DN"
Write-Host "." -NoNewLine
$Script:Unchanged = $Script:Unchanged + 1
Else
Add-Content -Path $LogFile -Value "## User not found: $Value"
Write-Host "." -NoNewLine
$Script:Errors = $Script:Errors + 1
$j = $J + 1
} Until ($Sheet.Cells.Item($j, $ID).Text -eq "")
$Step = "27"
CleanUp
Add-Content -Path $LogFile -Value $("Finished: " + (Get-Date).ToString())
Add-Content -Path $LogFile -Value "Number of users updated: $Script:Updated"
Add-Content -Path $LogFile -Value "Number of users unchanged: $Script:Unchanged"
Add-Content -Path $LogFile -Value "Number of errors: $Script:Errors"
Write-Host ""
"Done"
"Number of errors: $Script:Errors"
"See log file: $LogFile"Actually scripts run fine with excel file, currently we are using user-id to pick to update AD. Now we want to update AD use employee id. You can say to identify the record in AD through employee ID instead of user-id.
I do not think you will get anyone here to fix that for you. You need to find someone who knows PowerShell to help you or learn PowerShell your self.
I would fix it for you but not for free. It is too oddly designed and has too many dependencies. Any small change is likely to break it.
¯\_(ツ)_/¯ -
Migration to lync 2013 select central management store - what name should be there?
hello
trying to migration from lync 2010 to lync 2013. populated the topogoly builder and was going to publish.
the name in select central management store has the name of the lync 2010 environment, but if I hit next it has my new sql server.
should the new lync 2013 CMS be listed there?Did you move the Central Management Store via the Powershell yet? If not, check this article:
http://technet.microsoft.com/en-us/library/jj688013.aspx
If you have moved it, you're most likely seeing an old topology, download it again before making changes and publishing. If you download again and still see the old server even though it's moved, I'd re-run through the steps in the article again.
Please remember, if you see a post that helped you please click "Vote As Helpful" and if it answered your question please click "Mark As Answer".
SWC Unified Communications -
Help modifying a powershell script
Hello,
I have recently been given a task to write/find a script that is capable of performing Full and Incremental backups. I found a script that does exactly what I need, however, it requires user input. I need this to be a scheduled task and therefore I need
the input to be a static path. Here is the script I am talking about:
#region Params
param(
[Parameter(Position=0, Mandatory=$true,ValueFromPipeline=$true)]
[ValidateScript({Test-Path -LiteralPath $_ -PathType 'Container'})]
[System.String]
$SourceDir,
[Parameter(Position=1, Mandatory=$true,ValueFromPipeline=$false)]
[ValidateScript({Test-Path -LiteralPath $_ -PathType 'Container'})]
[System.String]
$DestDir,
[Parameter(Position=2, Mandatory=$false,ValueFromPipeline=$false)]
[ValidateScript({Test-Path -LiteralPath $_ -PathType 'Container'})]
[System.String]
$HashPath,
[Parameter(Position=3, Mandatory=$false,ValueFromPipeline=$false)]
[ValidateSet("Full","Incremental","Differential")]
[System.String]
$BackupType="Full",
[Parameter(Position=4, Mandatory=$false,ValueFromPipeline=$false)]
[ValidateNotNullOrEmpty()]
[System.String]
$LogFile=".\Backup-Files.log",
[Parameter(Position=5, Mandatory=$false,ValueFromPipeline=$false)]
[System.Management.Automation.SwitchParameter]
$SwitchToFull
#endregion
begin{
function Write-Log
#region Params
[CmdletBinding()]
[OutputType([System.String])]
param(
[Parameter(Position=0, Mandatory=$true,ValueFromPipeline=$true)]
[ValidateNotNullOrEmpty()]
[System.String]
$Message,
[Parameter(Position=1, Mandatory=$true,ValueFromPipeline=$true)]
[ValidateNotNullOrEmpty()]
[System.String]
$LogFile
#endregion
try{
Write-Host $Message
Out-File -InputObject $Message -Append $LogFile
catch {throw $_}
function Get-Hash
#region Params
[CmdletBinding()]
[OutputType([System.String])]
param(
[Parameter(Position=0, Mandatory=$true,ValueFromPipeline=$true)]
[ValidateNotNullOrEmpty()]
[System.String]
$HashTarget,
[Parameter(Position=1, Mandatory=$true,ValueFromPipeline=$false)]
[ValidateSet("File","String")]
[System.String]
$HashType
#endregion
begin{
try{ $objGetHashMD5 = New-Object -TypeName System.Security.Cryptography.MD5CryptoServiceProvider }
catch {throw $_ }
process{
try {
#Checking hash target is file or just string
switch($HashType){
"String" {
$objGetHashUtf8 = New-Object -TypeName System.Text.UTF8Encoding
$arrayGetHashHash = $objGetHashMD5.ComputeHash($objGetHashUtf8.GetBytes($HashTarget.ToUpper()))
break
"File" {
$arrayGetHashHash = $objGetHashMD5.ComputeHash([System.IO.File]::ReadAllBytes($HashTarget))
break
#Return hash
Write-Output $([System.Convert]::ToBase64String($arrayGetHashHash))
catch { throw $_ }
function Copy-File
#region Params
[CmdletBinding()]
[OutputType([System.String])]
param(
[Parameter(Position=0, Mandatory=$true,ValueFromPipeline=$false)]
[ValidateScript({Test-Path -LiteralPath $_ -PathType 'Any'})]
[System.String]
$SourceFile,
[Parameter(Position=1, Mandatory=$true,ValueFromPipeline=$false)]
[ValidateNotNullOrEmpty()]
[System.String]
$DestFile
#endregion
try{
#The script fails when folder being copied to file. So the item will be removed to avoid the error.
if(Test-Path -LiteralPath $DestFile -PathType Any){
Remove-Item -LiteralPath $DestFile -Force -Recurse
#Creating destination if doesn't exist. It's required because Copy-Item doesn't create destination folder
if(Test-Path -LiteralPath $SourceFile -PathType Leaf){
New-Item -ItemType "File" -Path $DestFile -Force
#Copying file to destination directory
Copy-Item -LiteralPath $SourceFile -Destination $DestFile -Force
catch{ throw $_ }
function Backup-Files
#region Params
[CmdletBinding()]
[OutputType([System.String])]
param(
[Parameter(Position=0, Mandatory=$true,ValueFromPipeline=$false)]
[ValidateScript({Test-Path -LiteralPath $_ -PathType 'Container'})]
[System.String]
$SourceDir,
[Parameter(Position=1, Mandatory=$true,ValueFromPipeline=$false)]
[ValidateNotNullOrEmpty()]
[System.String]
$DestDir,
[Parameter(Position=2, Mandatory=$true,ValueFromPipeline=$false)]
[ValidateNotNull()]
[System.Collections.Hashtable]
$HashTable
#endregion
try{
$xmlBackupFilesHashFile = $HashTable
Write-Host "Backup started"
Get-ChildItem -Recurse -Path $SourceDir|ForEach-Object{
$currentBackupFilesItem = $_
#Full path to source and destination item
$strBackupFilesSourceFullPath = $currentBackupFilesItem.FullName
$strBackupFilesDestFullPath = $currentBackupFilesItem.FullName.Replace($SourceDir,$DestDir)
#Checking that the current item is file and not directory. True - the item is file.
$bBackupFilesFile = $($($currentBackupFilesItem.Attributes -band [System.IO.FileAttributes]::Directory) -ne [System.IO.FileAttributes]::Directory)
Write-Host -NoNewline ">>>Processing item $strBackupFilesSourceFullPath..."
#Generating path hash
$hashBackupFilesPath = $(Get-Hash -HashTarget $strBackupFilesSourceFullPath -HashType "String")
$hashBackupFilesFile = "d"
#If the item is file then generate hash for file content
if($bBackupFilesFile){
$hashBackupFilesFile = $(Get-Hash -HashTarget $strBackupFilesSourceFullPath -HashType "File")
#Checking that the file has been copied
if($xmlBackupFilesHashFile[$hashBackupFilesPath] -ne $hashBackupFilesFile){
Write-Host -NoNewline $("hash changed=>$hashBackupFilesFile...")
Copy-File -SourceFile $strBackupFilesSourceFullPath $strBackupFilesDestFullPath|Out-Null
#Returning result
Write-Output @{$hashBackupFilesPath=$hashBackupFilesFile}
else{
Write-Host -NoNewline "not changed..."
Write-Host "done"
Write-Host "Backup completed"
catch { throw $_ }
function Backup-Full
[CmdletBinding()]
[OutputType([System.String])]
#region Params
param(
[Parameter(Position=0, Mandatory=$true,ValueFromPipeline=$false)]
[ValidateScript({Test-Path -LiteralPath $_ -PathType 'Container'})]
[System.String]
$SourceDir,
[Parameter(Position=1, Mandatory=$true,ValueFromPipeline=$false)]
[ValidateNotNullOrEmpty()]
[System.String]
$DestDir,
[Parameter(Position=2, Mandatory=$true,ValueFromPipeline=$false)]
[ValidateNotNullOrEmpty()]
[System.String]
$HashFile,
[Parameter(Position=3, Mandatory=$true,ValueFromPipeline=$false)]
[ValidateNotNullOrEmpty()]
[System.String]
$ChainKey
#endregion
try{
#Creating an empty hash table
$xmlBackupFullHashFile = @{}
#Starting directory lookup
$uintBackupFullCount = 0
Backup-Files -SourceDir $SourceDir -DestDir $("$DestDir\$ChainKey\Full_" + $(Get-Date -Format "ddMMyyyy")) -HashTable $xmlBackupFullHashFile|`
ForEach-Object{
$xmlBackupFullHashFile.Add([string]$_.Keys,[string]$_.Values)
$uintBackupFullCount++
#Saving chain key.
$xmlBackupFullHashFile.Add("ChainKey",$ChainKey)
Write-Host -NoNewline "Saving XML file to $HashFile..."
Export-Clixml -Path $HashFile -InputObject $xmlBackupFullHashFile -Force
Write-Host "done"
Write-Output $uintBackupFullCount
catch { throw $_ }
function Backup-Diff
#region Params
[CmdletBinding()]
[OutputType([System.String])]
param(
[Parameter(Position=0, Mandatory=$true,ValueFromPipeline=$false)]
[ValidateScript({Test-Path -LiteralPath $_ -PathType 'Container'})]
[System.String]
$SourceDir,
[Parameter(Position=1, Mandatory=$true,ValueFromPipeline=$false)]
[ValidateNotNullOrEmpty()]
[System.String]
$DestDir,
[Parameter(Position=2, Mandatory=$true,ValueFromPipeline=$false)]
[ValidateScript({Test-Path -LiteralPath $_ -PathType 'leaf'})]
[System.String]
$HashFile
#endregion
try{
#Loading hash table
$xmlBackupDiffHashFile = Import-Clixml $HashFile
$chainKeyBackupDiffDifferential = $xmlBackupDiffHashFile["ChainKey"]
$uintBackupDiffCount = 0
#Starting directory lookup
Backup-Files -SourceDir $SourceDir -DestDir $("$DestDir\$chainKeyBackupDiffDifferential\Differential_" + $(Get-Date -Format "ddMMyyyy.HHmm")) -HashTable $xmlBackupDiffHashFile|`
ForEach-Object{ $uintBackupDiffCount++ }
Write-Output $uintBackupDiffCount
catch { throw $_ }
function Backup-Inc
#region Params
[CmdletBinding()]
[OutputType([System.String])]
param(
[Parameter(Position=0, Mandatory=$true,ValueFromPipeline=$false)]
[ValidateScript({Test-Path -LiteralPath $_ -PathType 'Container'})]
[System.String]
$SourceDir,
[Parameter(Position=1, Mandatory=$true,ValueFromPipeline=$false)]
[ValidateNotNullOrEmpty()]
[System.String]
$DestDir,
[Parameter(Position=2, Mandatory=$true,ValueFromPipeline=$false)]
[ValidateScript({Test-Path -LiteralPath $_ -PathType 'leaf'})]
[System.String]
$HashFile
#endregion
try{
#Loading hash table
$xmlBackupIncHashFile = Import-Clixml $HashFile
$chainKeyBackupIncIncremental = $xmlBackupIncHashFile["ChainKey"]
$uintBackupIncCount = 0
#Starting directory lookup
Backup-Files -SourceDir $SourceDir -DestDir $("$DestDir\$chainKeyBackupIncIncremental\Incremental_" + $(Get-Date -Format "ddMMyyyy.HHmm")) -HashTable $xmlBackupIncHashFile|`
ForEach-Object{
$xmlBackupIncHashFile[[string]$_.Keys]=[string]$_.Values
$uintBackupIncCount++
Write-Host -NoNewline "Saving XML file to $HashFile..."
Export-Clixml -Path $HashFile -InputObject $xmlBackupIncHashFile -Force
Write-Host "Done"
Write-Output $uintBackupIncCount
catch { throw $_ }
#0 - is OK. 1 - some error
$exitValue=0
process{
try{
$filesCopied=0
$strSourceFolderName = $(Get-Item $SourceDir).Name
$strHasFile = $("$HashPath\Hash_$strSourceFolderName.xml")
$strMessage = $($(Get-Date -Format "HH:mm_dd.MM.yyyy;") + "$BackupType backup of $SourceDir started")
#Automatically switch to full backup
$bSwitch = $(!$(Test-Path -LiteralPath $strHasFile -PathType "Leaf") -and $SwitchToFull)
Write-Log -Message $strMessage -LogFile $LogFile
switch($true){
$($BackupType -eq "Full" -or $bSwitch) {
$filesCopied = Backup-Full -SourceDir $SourceDir -DestDir $DestDir -HashFile $strHasFile -ChainKey $("Backup_$strSourceFolderName" + "_" + $(Get-Date -Format "ddMMyyyy"))
break
$($BackupType -eq "Incremental") {
$filesCopied = Backup-Inc -SourceDir $SourceDir -DestDir $DestDir -HashFile $strHasFile
break
$($BackupType -eq "Differential") {
$filesCopied = Backup-Diff -SourceDir $SourceDir -DestDir $DestDir -HashFile $strHasFile
break
$strMessage = $($(Get-Date -Format "HH:mm_dd.MM.yyyy;") + "$BackupType backup of $SourceDir completed successfully. $filesCopied items were copied.")
Write-Log -Message $strMessage -LogFile $LogFile
Write-Output $filesCopied
catch {
$strMessage = $($(Get-Date -Format "HH:mm_dd.MM.yyyy;") + "$BackupType backup of $SourceDir failed:" + $_)
Write-Log -Message $strMessage -LogFile $LogFile
$exitValue = 1
end{exit $exitValue}
I have some experience writing Powershell scripts,but I am lost at how this script prompts for Source and Destination paths. I tried modifying the Param section, but this didnt work and up until now I thought the only way you could get a prompt was with
"read-host". Any and all education on this matter would be greatly appreciated. (Side note: I have posted this question on the forum in which I found it and have not got an answer yet).
param(
[Parameter(Position=0, Mandatory=$true,ValueFromPipeline=$true)]
[ValidateScript({Test-Path -LiteralPath $_ -PathType 'Container'})]
[System.String]
$SourceDir,
[Parameter(Position=1, Mandatory=$true,ValueFromPipeline=$false)]
[ValidateScript({Test-Path -LiteralPath $_ -PathType 'Container'})]
[System.String]
$DestDir,
[Parameter(Position=2, Mandatory=$false,ValueFromPipeline=$false)]
[ValidateScript({Test-Path -LiteralPath $_ -PathType 'Container'})]
[System.String]
$HashPath,
[Parameter(Position=3, Mandatory=$false,ValueFromPipeline=$false)]
[ValidateSet("Full","Incremental","Differential")]
[System.String]
$BackupType="Full",
[Parameter(Position=4, Mandatory=$false,ValueFromPipeline=$false)]
[ValidateNotNullOrEmpty()]
[System.String]
$LogFile=".\Backup-Files.log",
[Parameter(Position=5, Mandatory=$false,ValueFromPipeline=$false)]
[System.Management.Automation.SwitchParameter]
$SwitchToFull
#endregion
begin{
function Write-Log
#region Params
[CmdletBinding()]
[OutputType([System.String])]
param(
[Parameter(Position=0, Mandatory=$true,ValueFromPipeline=$true)]
[ValidateNotNullOrEmpty()]
[System.String]
$Message,
[Parameter(Position=1, Mandatory=$true,ValueFromPipeline=$true)]
[ValidateNotNullOrEmpty()]
[System.String]
$LogFile
#endregion
try{
Write-Host $Message
Out-File -InputObject $Message -Append $LogFile
catch {throw $_}
function Get-Hash
#region Params
[CmdletBinding()]
[OutputType([System.String])]
param(
[Parameter(Position=0, Mandatory=$true,ValueFromPipeline=$true)]
[ValidateNotNullOrEmpty()]
[System.String]
$HashTarget,
[Parameter(Position=1, Mandatory=$true,ValueFromPipeline=$false)]
[ValidateSet("File","String")]
[System.String]
$HashType
#endregion
begin{
try{ $objGetHashMD5 = New-Object -TypeName System.Security.Cryptography.MD5CryptoServiceProvider }
catch {throw $_ }
process{
try {
#Checking hash target is file or just string
switch($HashType){
"String" {
$objGetHashUtf8 = New-Object -TypeName System.Text.UTF8Encoding
$arrayGetHashHash = $objGetHashMD5.ComputeHash($objGetHashUtf8.GetBytes($HashTarget.ToUpper()))
break
"File" {
$arrayGetHashHash = $objGetHashMD5.ComputeHash([System.IO.File]::ReadAllBytes($HashTarget))
break
#Return hash
Write-Output $([System.Convert]::ToBase64String($arrayGetHashHash))
catch { throw $_ }
function Copy-File
#region Params
[CmdletBinding()]
[OutputType([System.String])]
param(
[Parameter(Position=0, Mandatory=$true,ValueFromPipeline=$false)]
[ValidateScript({Test-Path -LiteralPath $_ -PathType 'Any'})]
[System.String]
$SourceFile,
[Parameter(Position=1, Mandatory=$true,ValueFromPipeline=$false)]
[ValidateNotNullOrEmpty()]
[System.String]
$DestFile
#endregion
try{
#The script fails when folder being copied to file. So the item will be removed to avoid the error.
if(Test-Path -LiteralPath $DestFile -PathType Any){
Remove-Item -LiteralPath $DestFile -Force -Recurse
#Creating destination if doesn't exist. It's required because Copy-Item doesn't create destination folder
if(Test-Path -LiteralPath $SourceFile -PathType Leaf){
New-Item -ItemType "File" -Path $DestFile -Force
#Copying file to destination directory
Copy-Item -LiteralPath $SourceFile -Destination $DestFile -Force
catch{ throw $_ }
function Backup-Files
#region Params
[CmdletBinding()]
[OutputType([System.String])]
param(
[Parameter(Position=0, Mandatory=$true,ValueFromPipeline=$false)]
[ValidateScript({Test-Path -LiteralPath $_ -PathType 'Container'})]
[System.String]
$SourceDir,
[Parameter(Position=1, Mandatory=$true,ValueFromPipeline=$false)]
[ValidateNotNullOrEmpty()]
[System.String]
$DestDir,
[Parameter(Position=2, Mandatory=$true,ValueFromPipeline=$false)]
[ValidateNotNull()]
[System.Collections.Hashtable]
$HashTable
#endregion
try{
$xmlBackupFilesHashFile = $HashTable
Write-Host "Backup started"
Get-ChildItem -Recurse -Path $SourceDir|ForEach-Object{
$currentBackupFilesItem = $_
#Full path to source and destination item
$strBackupFilesSourceFullPath = $currentBackupFilesItem.FullName
$strBackupFilesDestFullPath = $currentBackupFilesItem.FullName.Replace($SourceDir,$DestDir)
#Checking that the current item is file and not directory. True - the item is file.
$bBackupFilesFile = $($($currentBackupFilesItem.Attributes -band [System.IO.FileAttributes]::Directory) -ne [System.IO.FileAttributes]::Directory)
Write-Host -NoNewline ">>>Processing item $strBackupFilesSourceFullPath..."
#Generating path hash
$hashBackupFilesPath = $(Get-Hash -HashTarget $strBackupFilesSourceFullPath -HashType "String")
$hashBackupFilesFile = "d"
#If the item is file then generate hash for file content
if($bBackupFilesFile){
$hashBackupFilesFile = $(Get-Hash -HashTarget $strBackupFilesSourceFullPath -HashType "File")
#Checking that the file has been copied
if($xmlBackupFilesHashFile[$hashBackupFilesPath] -ne $hashBackupFilesFile){
Write-Host -NoNewline $("hash changed=>$hashBackupFilesFile...")
Copy-File -SourceFile $strBackupFilesSourceFullPath $strBackupFilesDestFullPath|Out-Null
#Returning result
Write-Output @{$hashBackupFilesPath=$hashBackupFilesFile}
else{
Write-Host -NoNewline "not changed..."
Write-Host "done"
Write-Host "Backup completed"
catch { throw $_ }
function Backup-Full
[CmdletBinding()]
[OutputType([System.String])]
#region Params
param(
[Parameter(Position=0, Mandatory=$true,ValueFromPipeline=$false)]
[ValidateScript({Test-Path -LiteralPath $_ -PathType 'Container'})]
[System.String]
$SourceDir,
[Parameter(Position=1, Mandatory=$true,ValueFromPipeline=$false)]
[ValidateNotNullOrEmpty()]
[System.String]
$DestDir,
[Parameter(Position=2, Mandatory=$true,ValueFromPipeline=$false)]
[ValidateNotNullOrEmpty()]
[System.String]
$HashFile,
[Parameter(Position=3, Mandatory=$true,ValueFromPipeline=$false)]
[ValidateNotNullOrEmpty()]
[System.String]
$ChainKey
#endregion
try{
#Creating an empty hash table
$xmlBackupFullHashFile = @{}
#Starting directory lookup
$uintBackupFullCount = 0
Backup-Files -SourceDir $SourceDir -DestDir $("$DestDir\$ChainKey\Full_" + $(Get-Date -Format "ddMMyyyy")) -HashTable $xmlBackupFullHashFile|`
ForEach-Object{
$xmlBackupFullHashFile.Add([string]$_.Keys,[string]$_.Values)
$uintBackupFullCount++
#Saving chain key.
$xmlBackupFullHashFile.Add("ChainKey",$ChainKey)
Write-Host -NoNewline "Saving XML file to $HashFile..."
Export-Clixml -Path $HashFile -InputObject $xmlBackupFullHashFile -Force
Write-Host "done"
Write-Output $uintBackupFullCount
catch { throw $_ }
function Backup-Diff
#region Params
[CmdletBinding()]
[OutputType([System.String])]
param(
[Parameter(Position=0, Mandatory=$true,ValueFromPipeline=$false)]
[ValidateScript({Test-Path -LiteralPath $_ -PathType 'Container'})]
[System.String]
$SourceDir,
[Parameter(Position=1, Mandatory=$true,ValueFromPipeline=$false)]
[ValidateNotNullOrEmpty()]
[System.String]
$DestDir,
[Parameter(Position=2, Mandatory=$true,ValueFromPipeline=$false)]
[ValidateScript({Test-Path -LiteralPath $_ -PathType 'leaf'})]
[System.String]
$HashFile
#endregion
try{
#Loading hash table
$xmlBackupDiffHashFile = Import-Clixml $HashFile
$chainKeyBackupDiffDifferential = $xmlBackupDiffHashFile["ChainKey"]
$uintBackupDiffCount = 0
#Starting directory lookup
Backup-Files -SourceDir $SourceDir -DestDir $("$DestDir\$chainKeyBackupDiffDifferential\Differential_" + $(Get-Date -Format "ddMMyyyy.HHmm")) -HashTable $xmlBackupDiffHashFile|`
ForEach-Object{ $uintBackupDiffCount++ }
Write-Output $uintBackupDiffCount
catch { throw $_ }
function Backup-Inc
#region Params
[CmdletBinding()]
[OutputType([System.String])]
param(
[Parameter(Position=0, Mandatory=$true,ValueFromPipeline=$false)]
[ValidateScript({Test-Path -LiteralPath $_ -PathType 'Container'})]
[System.String]
$SourceDir,
[Parameter(Position=1, Mandatory=$true,ValueFromPipeline=$false)]
[ValidateNotNullOrEmpty()]
[System.String]
$DestDir,
[Parameter(Position=2, Mandatory=$true,ValueFromPipeline=$false)]
[ValidateScript({Test-Path -LiteralPath $_ -PathType 'leaf'})]
[System.String]
$HashFile
#endregion
try{
#Loading hash table
$xmlBackupIncHashFile = Import-Clixml $HashFile
$chainKeyBackupIncIncremental = $xmlBackupIncHashFile["ChainKey"]
$uintBackupIncCount = 0
#Starting directory lookup
Backup-Files -SourceDir $SourceDir -DestDir $("$DestDir\$chainKeyBackupIncIncremental\Incremental_" + $(Get-Date -Format "ddMMyyyy.HHmm")) -HashTable $xmlBackupIncHashFile|`
ForEach-Object{
$xmlBackupIncHashFile[[string]$_.Keys]=[string]$_.Values
$uintBackupIncCount++
Write-Host -NoNewline "Saving XML file to $HashFile..."
Export-Clixml -Path $HashFile -InputObject $xmlBackupIncHashFile -Force
Write-Host "Done"
Write-Output $uintBackupIncCount
catch { throw $_ }
#0 - is OK. 1 - some error
$exitValue=0
process{
try{
$filesCopied=0
$strSourceFolderName = $(Get-Item $SourceDir).Name
$strHasFile = $("$HashPath\Hash_$strSourceFolderName.xml")
$strMessage = $($(Get-Date -Format "HH:mm_dd.MM.yyyy;") + "$BackupType backup of $SourceDir started")
#Automatically switch to full backup
$bSwitch = $(!$(Test-Path -LiteralPath $strHasFile -PathType "Leaf") -and $SwitchToFull)
Write-Log -Message $strMessage -LogFile $LogFile
switch($true){
$($BackupType -eq "Full" -or $bSwitch) {
$filesCopied = Backup-Full -SourceDir $SourceDir -DestDir $DestDir -HashFile $strHasFile -ChainKey $("Backup_$strSourceFolderName" + "_" + $(Get-Date -Format "ddMMyyyy"))
break
$($BackupType -eq "Incremental") {
$filesCopied = Backup-Inc -SourceDir $SourceDir -DestDir $DestDir -HashFile $strHasFile
break
$($BackupType -eq "Differential") {
$filesCopied = Backup-Diff -SourceDir $SourceDir -DestDir $DestDir -HashFile $strHasFile
break
$strMessage = $($(Get-Date -Format "HH:mm_dd.MM.yyyy;") + "$BackupType backup of $SourceDir completed successfully. $filesCopied items were copied.")
Write-Log -Message $strMessage -LogFile $LogFile
Write-Output $filesCopied
catch {
$strMessage = $($(Get-Date -Format "HH:mm_dd.MM.yyyy;") + "$BackupType backup of $SourceDir failed:" + $_)
Write-Log -Message $strMessage -LogFile $LogFile
$exitValue = 1
end{exit $exitValue}Hi Ryan Blaeholder,
Thanks for your posting.
To schedule a powershell script with input value, instead of modifying the script above, you can also try to add the input during creating a scheduled task like this:(save the script above as D:\backup.ps1)
-command "& 'D:\backup.ps1' 'input1' 'input2'"
For more detailed information, please refer to this article to complete:
Schedule PowerShell Scripts that Require Input Values:
http://blogs.technet.com/b/heyscriptingguy/archive/2011/01/12/schedule-powershell-scripts-that-require-input-values.aspx
I hope this helps.
We
are trying to better understand customer views on social support experience, so your participation in this
interview project would be greatly appreciated if you have time.
Thanks for helping make community forums a great place. -
HI
Now there is an issue while iam running powershell script for BDC service.
Below is the script i am using to configure BDC service.
Param(
[Parameter(Mandatory=$true,ValueFromPipeline=$true)]
[string]$ServiceName = $null,
[Parameter(Mandatory=$true)]
[string]$ServiceProxyName = $null,
[Parameter(Mandatory=$true)]
[string]$AppPoolAccount = $null,
[Parameter(Mandatory=$true)]
[string]$AppPoolName = $null,
[Parameter(Mandatory=$true)]
[string]$DatabaseServer = $null,
[Parameter(Mandatory=$true)]
[string]$DatabaseName = $null
# check to ensure Microsoft.SharePoint.PowerShell is loaded if not using the SharePoint Management Shell
$snapin = Get-PSSnapin | Where-Object {$_.Name -eq 'Microsoft.SharePoint.Powershell'}
if ($snapin -eq $null) {
Write-Host "Loading SharePoint Powershell Snapin"
Add-PSSnapin "Microsoft.SharePoint.Powershell"
Write-Host "Successfully Sharepoint Powershell snapin Loaded"
Write-Host "Started executing Powershell script for configuring Business Data Connectivity Service in sharepoint farm ..."
Write-Host -ForegroundColor Yellow "Checking if Application Pool Accounts exists"
$AppPoolAccount = Get-SPManagedAccount -Identity $AppPoolAccount -EA 0
if($AppPoolAccount -eq $null)
Write-Host "Please supply the password for the Service Account..."
$AppPoolCred = Get-Credential $AppPoolAccount
$AppPoolAccount = New-SPManagedAccount -Credential $AppPoolCred -EA 0
Write-Host -ForegroundColor Yellow "Checking wether the Application Pool exists"
$AppPool = Get-SPServiceApplicationPool -Identity $AppPoolName -ErrorAction SilentlyContinue
if (!$AppPool)
Write-Host -ForegroundColor Green "Creating Application Pool"
$AppPool = New-SPServiceApplicationPool -Name $AppPoolName -Account $AppPoolAccount -Verbose
Write-Host -ForegroundColor Yellow "Checking if BDC Service Application exists"
$ServiceApplication = Get-SPServiceApplication -Name $ServiceName -ErrorAction SilentlyContinue
if (!$ServiceApplication)
Write-Host -ForegroundColor Green "Creating BDC Service Application"
$ServiceApplication = New-SPBusinessDataCatalogServiceApplication –ApplicationPool $AppPool –DatabaseName $DatabaseName –DatabaseServer $DatabaseServer –Name $ServiceName
Write-Host -ForegroundColor Yellow "Starting the BDC Service"
#$ServiceInstance = Get-SPServiceInstance | Where-Object { $_.TypeName -like "BDC Service*" }
#Start-SPServiceInstance $ServiceInstance
Get-SPServiceInstance | where-object {$_.DisplayName -eq $ServiceName} | Start-SPServiceInstance > $null
Write-Host -ForegroundColor Green "Done - BDC Service is up and running."
Error i am getting ->
Started executing Powershell script for configuring Business Data Connectivity S
ervice in sharepoint farm ...
Checking if Application Pool Accounts exists
Checking wether the Application Pool exists
Creating Application Pool
VERBOSE: Leaving BeginProcessing Method of New-SPServiceApplicationPool.
New-SPServiceApplicationPool : The trust relationship between the primary
domain and the trusted domain failed.
At C:\SP2013Service\BDC1.ps1:67 char:12
+ $AppPool = New-SPServiceApplicationPool -Name $AppPoolName -Account
$AppPoolAcco ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
~~~
+ CategoryInfo : InvalidData: (Microsoft.Share...ApplicationPool:
SPCmdletNewIisWebServiceApplicationPool) [New-SPServiceApplicationPool], S
ystemException
+ FullyQualifiedErrorId : Microsoft.SharePoint.PowerShell.SPCmdletNewIisWe
bServiceApplicationPool
VERBOSE: Leaving ProcessRecord Method of New-SPServiceApplicationPool.
VERBOSE: Leaving EndProcessing Method of New-SPServiceApplicationPool.
Checking if BDC Service Application exists
Creating BDC Service Application
New-SPBusinessDataCatalogServiceApplication : Cannot bind argument to
parameter 'ApplicationPool' because it is null.
At C:\SP2013Service\BDC1.ps1:75 char:84
+ ... pplicationPool $AppPool –DatabaseName $DatabaseName –DatabaseServer
$DatabaseSer ...
+ ~~~~~~~~
+ CategoryInfo : InvalidData: (:) [New-SPBusinessD...viceApplicat
ion], ParameterBindingValidationException
+ FullyQualifiedErrorId : ParameterArgumentValidationErrorNullNotAllowed,M
icrosoft.SharePoint.BusinessData.SharedService.SPNewBusinessDataCatalogSer
viceApplicationhi guys,
same script i have modified with parametes,in below script i have hard corded values for parameters,and it is executing without errors.
Below is script executing without error->
Add-PsSnapin Microsoft.SharePoint.PowerShell -ErrorAction SilentlyContinue
#Settings
$ServiceName = "BDC Service"
$ServiceProxyName = "BDC Proxy"
$AppPoolAccount = "DOMAIN\USERNAME"
$AppPoolName = "BDC SP Ser App Pool"
$DatabaseServer = "SPSQL"
$DatabaseName = "SP2013 BDC"
Write-Host -ForegroundColor Yellow "Checking if Application Pool Accounts exists"
$AppPoolAccount = Get-SPManagedAccount -Identity $AppPoolAccount -EA 0
if($AppPoolAccount -eq $null)
Write-Host "Please supply the password for the Service Account..."
$AppPoolCred = Get-Credential $AppPoolAccount
$AppPoolAccount = New-SPManagedAccount -Credential $AppPoolCred -EA 0
Write-Host -ForegroundColor Yellow "Checking wether the Application Pool exists"
$AppPool = Get-SPServiceApplicationPool -Identity $AppPoolName -ErrorAction SilentlyContinue
if (!$AppPool)
Write-Host -ForegroundColor Green "Creating Application Pool"
$AppPool = New-SPServiceApplicationPool -Name $AppPoolName -Account $AppPoolAccount -Verbose
Write-Host -ForegroundColor Yellow "Checking if BDC Service Application exists"
$ServiceApplication = Get-SPServiceApplication -Name $ServiceName -ErrorAction SilentlyContinue
if (!$ServiceApplication)
Write-Host -ForegroundColor Green "Creating BDC Service Application"
$ServiceApplication = New-SPBusinessDataCatalogServiceApplication –ApplicationPool $AppPool –DatabaseName $DatabaseName –DatabaseServer $DatabaseServer –Name $ServiceName
Write-Host -ForegroundColor Yellow "Starting the BDC Service"
#$ServiceInstance = Get-SPServiceInstance | Where-Object { $_.TypeName -like "BDC Service*" }
#Start-SPServiceInstance $ServiceInstance
Get-SPServiceInstance | where-object {$_.DisplayName -eq $ServiceName} | Start-SPServiceInstance > $null
Write-Host -ForegroundColor Green "Done - BDC Service is up and running."
if any body want need more information please can u respond me to
Email id:[email protected] -
Monitor SQL Database mirroring using powershell script
I am trying use the below powershell script to monitor SQL Database mirroring. The motive here is to determine if there are databases which are in "Disconnected" or "Suspended" mode.
I am running the script on the Principal Server:
$returnStateOK = 0
$returnStateWarning = 1
$returnStateCritical = 2
$returnStateUnknown = 3
$NagiosStatus = ""
# Load SMO extension
[System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SqlServer.Smo") | Out-Null;
# Servers to check
$sqlservers = @("$env:computername");
foreach($server in $sqlservers)
$srv = New-Object "Microsoft.SqlServer.Management.Smo.Server" $server;
# Get mirrored databases
$databases = $srv.Databases | Where-Object {$_.IsMirroringEnabled -eq $true -and $_.MirroringStatus -eq "Suspended" -or $_.MirroringStatus -eq "Synchronizing" -or $_.MirroringStatus -eq "Disconnected"
-or $_.MirroringStatus -eq "None" -and $_.Name -ne "Master" -and $_.Name -ne "model" -and $_.Name -ne "msdb" -and $_.Name -ne "tempdb"};
if ($databases -ne $null)
$databases | Select-Object -Property Name, MirroringStatus | Format-Table -AutoSize;
exit $returnStateCritical
} Else {
Write-Host "All Databaes are Mirrored"
exit $returnStateOK
I have Suspended few databases for testing purpose but when I run the above script the output says "All Databaes are Mirrored"
If I make changes to $database and use it below i.e. I am changing the AND operator to OR after "$_.IsMirroringEnabled -eq $true"
$databases = $srv.Databases | Where-Object {$_.IsMirroringEnabled -eq $true -or $_.MirroringStatus -eq "Suspended" -or $_.MirroringStatus -eq "Synchronizing" -or $_.MirroringStatus
-eq "Disconnected" -or $_.MirroringStatus -eq "None" -and $_.Name -ne "Master" -and $_.Name -ne "model" -and $_.Name -ne "msdb" -and $_.Name -ne "tempdb"};
I get the below output:
Name
MirroringStatus
DB1
Synchronized
DB2
Synchronized
DB3 Synchronized
DB4
Suspended
DB5 Suspended
DB6
Suspended
DB7
Synchronized
DB8
Synchronized
I only want the databases which are Suspended or Disconnected to be listed.I only want the databases which are Suspended or Disconnected to be listed.
Hi raul-133,
Based on your description, to list the databases which are Suspended or Disconnected ,I recommend you execute the following Transact-SQL statements in SQL Server firstly. If you can get the expected results from this query, then use the SQL Server query
in powershell script. For more details, please review this similar blog:
Monitor database mirroring.
Use master
go
select d.name, m.mirroring_state_desc
from sys.database_mirroring m,
sys.databases d
where m.database_id = d.database_id and (m.mirroring_state in (0,1))
For more details about mirroring state, you can review this article:
sys.database_mirroring (Transact-SQL).
Thanks,
Lydia Zhang
Maybe you are looking for
-
How-To Find the R/3 Table Name for a BW Data Source
Hi there, Please advice how can I find the respective table name in R/3 for a particular BW DataSource ? P/S : I would like a technical how-to instead of referring the table names at HELP.SAP.COM For instance, for my Standard Business Content I
-
I dropped my cracked iPod touch 4th generation in water and now it's just done. The touch doesn't work anymore (by that I mean I cant touch it anymore, I cant slide it open or slide it to turn it off). It wouldn't really be a big problem cause I plug
-
Ibook will not boot into OS or off disc
I have a G3/500 ibook, it turns on and the display seems fine, but it won't boot into the OS on the HD or off a disc. I replaced the HD with one which i know works, still nothing, so i booted with volume select from a firewire dvd drive (the cd drive
-
I have a Zire 21 which is working fine and I hot sync on a Windows XP home edition computer. I would be lost without my Palm - I am in need of a new computer and have been told in order to hot sync and use my old friend I will have to upgrade to Win
-
Horizontal scrolling with mouse wheel?
I have built a website for a client that scrolls only horizontally. Is it possible to scroll with the mouse wheel horizontally? Is there certain HTML I need to add? Thank you