Copy owners with robocopy using powershell.

Hi Friends..
I have created script to copy folder from one location to another location in PS. using Robocopy..
but By this script cannot copy the owner of the source location folder to destination.. 
below is the script..
please help me to add some points to update this script with copy owners of the folders as well..
Import-Csv "D:\script\file.csv" | ForEach-Object {
                $Source = $_.Sourceserver
                $Target = $_.Destinantionserver
                robocopy.exe $Source $Target /b /e /copyall

Hi Mr.Raj,
Sorry for the delay.
Is there any error message on the cmd prompt when separately running command " robocopy.exe $Source $Target /b /e /copyall " ?
Also you can make a screenshot and post it here .
Best Regards
Elton Ji
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.

Similar Messages

  • Starting SMA runbook with parameteres using powershell via REST

    Hello!
    I am trying to start SMA runbook using powershell via REST. I can do that normally for simple runbook without parameters using REST web service (for example
    https://my.server.com:9090/00000000-0000-0000-0000-000000000000/Runbooks%28guid%27bd55d199-c261-4c50-9cef-a83d5c976ce2%27%29/Start
    However, I do not understand how to start a runbook which has parameters? For example I have 2 runbooks - 1 with single parameter and second with 3 parameters, how can I pass parameters value? I would really appreciate any help!

    Hello
    Does this Link answer your question?
    http://msdn.microsoft.com/en-us/library/hh921685.aspx
    Thanks
    Josh
    Code from that URL in case the link ever dies:
    # Details of the runbook we are going to run
    $rbid = "00000000-0000-0000-00000000000000001"
    $rbParameters = @{"00000000-0000-0000-00000000000000002" = "This is the value for Param1.";" 00000000-0000-0000-00000000000000003" = " This is the value for Param2."}
    # Create the request object
    $request = [System.Net.HttpWebRequest]::Create("http:// server01.contoso.com:81/Orchestrator2012/Orchestrator.svc/Jobs")
    # Set the credentials to default or prompt for credentials
    $request.UseDefaultCredentials = $true
    # $request.Credentials = Get-Credential
    # Build the request header
    $request.Method = "POST"
    $request.UserAgent = "Microsoft ADO.NET Data Services"
    $request.Accept = "application/atom+xml,application/xml"
    $request.ContentType = "application/atom+xml"
    $request.KeepAlive = $true
    $request.Headers.Add("Accept-Encoding","identity")
    $request.Headers.Add("Accept-Language","en-US")
    $request.Headers.Add("DataServiceVersion","1.0;NetFx")
    $request.Headers.Add("MaxDataServiceVersion","2.0;NetFx")
    $request.Headers.Add("Pragma","no-cache")
    # If runbook servers are specified, format the string
    $rbServerString = ""
    if (-not [string]::IsNullOrEmpty($RunbookServers)) {
    $rbServerString = -join ("<d:RunbookServers>",$RunbookServers,"</d:RunbookServers>")
    # Format the Runbook parameters, if any
    $rbParamString = ""
    if ($rbParameters -ne $null) {
    # Format the param string from the Parameters hashtable
    $rbParamString = "<d:Parameters><![CDATA[<Data>"
    foreach ($p in $rbParameters.GetEnumerator())
    #$rbParamString = -join ($rbParamString,"&lt;Parameter&gt;&lt;ID&gt;{",$p.key,"}&lt;/ID&gt;&lt;Value&gt;",$p.value,"&lt;/Value&gt;&lt;/Parameter&gt;")
    $rbParamString = -join ($rbParamString,"<Parameter><ID>{",$p.key,"}</ID><Value>",$p.value,"</Value></Parameter>")
    $rbParamString += "</Data>]]></d:Parameters>"
    # Build the request body
    $requestBody = @"
    <?xml version="1.0" encoding="utf-8" standalone="yes"?>
    <entry xmlns:d="http://schemas.microsoft.com/ado/2007/08/dataservices" xmlns:m="http://schemas.microsoft.com/ado/2007/08/dataservices/metadata" xmlns="http://www.w3.org/2005/Atom">
    <content type="application/xml">
    <m:properties>
    <d:RunbookId m:type="Edm.Guid">$rbid</d:RunbookId>
    $rbserverstring
    $rbparamstring
    </m:properties>
    </content>
    </entry>
    # Create a request stream from the request
    $requestStream = new-object System.IO.StreamWriter $Request.GetRequestStream()
    # Sends the request to the service
    $requestStream.Write($RequestBody)
    $requestStream.Flush()
    $requestStream.Close()
    # Get the response from the request
    [System.Net.HttpWebResponse] $response = [System.Net.HttpWebResponse] $Request.GetResponse()
    # Write the HttpWebResponse to String
    $responseStream = $Response.GetResponseStream()
    $readStream = new-object System.IO.StreamReader $responseStream
    $responseString = $readStream.ReadToEnd()
    # Close the streams
    $readStream.Close()
    $responseStream.Close()
    # Get the ID of the resulting job
    if ($response.StatusCode -eq 'Created')
    $xmlDoc = [xml]$responseString
    $jobId = $xmlDoc.entry.content.properties.Id.InnerText
    Write-Host "Successfully started runbook. Job ID: " $jobId
    else
    Write-Host "Could not start runbook. Status: " $response.StatusCode

  • How to give readonly Permission rights to 1000 users with button using powershell script?

    $site = Get-SPSite
    -Identity "http://mysite/"
    $user = Get-SPUser
    -Identity "mydomain\myuser"
    -Web $site.RootWeb
    $assignment = New-Object
    Microsoft.SharePoint.SPRoleAssignment($user)
    $role = $site.RootWeb.RoleDefinitions[[Microsoft.SharePoint.SPRoleType]::Reader]
    $assignment.RoleDefinitionBindings.Add($role);
    foreach ($web in $site.AllWebs)
        if ($web.HasUniquePerm)
            $web.RoleAssignments.Add($assignment)
    With above script I can give Readonly permission to the users...but at a time I can give permission to only one user...Actually 1000 users requires these permissionMy requirement is I will have a textbox and a button.I will enter username in textbox
    and when i clicked button the required permission should be assigned to the user given in the textbox...can you please tell how can i achieve this........how make to run powershell script when button is clicked.

    Hello,
    Instead of applying security to user level, it'll be better to create a SharePoint group where you will add the users. and use the outof the box interface to give permissions.
    and for your button, just add the direct link to add user
    http://serverurl/_layouts/15/aclinv.aspx?GroupId=7&IsDlg=1 
    replacing the group ID by the id of your new group (you can see it in the url when your are in the group)
    Best regards, Christopher.
    Blog |
    Mail
    Please remember to click "Mark As Answer" if a post solves your problem or
    "Vote As Helpful" if it was useful.
    Why mark as answer?

  • Uploading document using Powershell is throwing error- There is no file with URL

    Hi.
    I am trying to upload multiple documents to a sub folder in a library using powershell.
    I am getting the error as : ForEach-Object : Exception calling "Add" with "3" argument(s):
    "<nativehr>0x80070003</nativehr><nativestack></nativestack>There is no file
    with URL 'server/TestLibrary/User_image/ab_3f_wht_ist_small_gif.gif' in this Web."
    I have used the below code:
    function UploadImages($weburl)
    $docLibraryName = "TestLibrary"
    $localFolderPath = "C:\Users\Imgs\user_image"
    Add-PsSnapin Microsoft.SharePoint.PowerShell -erroraction silentlycontinue
    $web = Get-SPWeb -Identity $webUrl
    $docLibrary = $web.Lists[$docLibraryName]
    $subFolderName="user_image"
    Add-PsSnapin Microsoft.SharePoint.PowerShell -erroraction silentlycontinue
    $web = Get-SPWeb -Identity $webUrl
    $docLibrary = $web.Lists[$docLibraryName]
    #Attach to local folder and enumerate through all files
    $files = ([System.IO.DirectoryInfo] (Get-Item $localFolderPath)).GetFiles() | ForEach-Object {
    #Create file stream object from file
    $fileStream = ([System.IO.FileInfo] (Get-Item $_.FullName)).OpenRead()
    $contents = new-object byte[] $fileStream.Length
    $fileStream.Read($contents, 0, [int]$fileStream.Length);
    $fileStream.Close();
    write-host "Copying" $_.Name "to" $docLibrary.Title "in" $web.Title "..."
    #Add file
    $folder = $web.getfolder($docLibrary.Title + "/" + $subFolderName)
    write-host "folder is " $folder
    $spFile = $folder.Files.Add($folder.Url + "/" + $_.Name, $contents, $true)
    $spItem = $spFile.Item
    Write-Host -f Green "Added Images to Library !!!"
    $web.Dispose()
    How to fix this?
    Thanks

    HI,
    Is the name of the image or the sub folder name the issue?
    I have the images with the name as "ab_3f_wht_ist_small_gif.gif".  folder name "User_image"
    There are underscores on the file name, but there is no space. When I add the file from the library (using the UI), the image is getting added.
    But adding through the powershell is giving the issue.
    I have checked this:
    http://social.msdn.microsoft.com/Forums/sharepoint/en-US/e810ad03-81ef-4fa6-aab8-ddc896a13ebf/getting-error-during-uploading-a-document-using-powershell?forum=sharepointdevelopmentprevious
    but did not help.
    Thanks

  • How to create sharepoint Group with read only permissions using powershell for entire site ?

    How to create sharepoint Group with read only permissions using powershell for entire site (including subsites and top level site)

    Hi
    using (SPSite site = new SPSite(url))
    using (SPWeb web = site.OpenWeb())
    SPUserCollection users = Web.AllUsers;
    SPUser owner = users[string.Format("{0}{1}", "Domain", "Owner Username")];
    SPMember member = users[string.Format("{0}{1}", "Domain", "Default Member Username")];
    SPGroupCollection groups = Web.SiteGroups;
    string GroupName = “Super Exclusive”;//your group name
    string GroupDescription = “Super exclusive group description.”;
    groups.Add(GroupName, owner, member, GroupDescription);
    SPGroup NewSPGroup = groups[GroupName];
    SPRoleDefinition role = Web.RoleDefinitions["Read"];
    SPRoleAssignment roleAssignment = new SPRoleAssignment(NewSPGroup);
    roleAssignment.RoleDefinitionBindings.Add(role);
    Web.RoleAssignments.Add(roleAssignment);
    Web.Update();
    Please 'propose
    as answer' if it helped you, also 'vote
    helpful' if you like this reply.

  • HT1539 can i add my digital copy to itunes with out using the disk? my netbook does not have a disk drive and i want to add my movie to my ipod can i do it with out the use of the disk and just the code?

    Can I add my digital copy movie to my iTunes with out using the disk, my gateway laptop/netbook does not have a disk drive I have the unused code and everything, I just can't stuck the movie into the computer itself and my desktop computer has no internet on it. Is there a way to add my movie to my iPod touch 2nd generation tuning 4.2.1

    Hiya!
    It depends on what kind of digital copy you have.  This article goes ino details regarding the two types, and depending on the type you have, you may or may not need the DVD to redeem the code.
    Transferring video from DVDs with iTunes digital content
    http://support.apple.com/kb/HT1539
    I hope this helps!  Best wishes and good luck!

  • Use Powershell to replace text with image in Word document

    I have a powershell script that uses a Word document as a template to create signatures that I am pushing out to my organization.
    The document is populated with text formatted the way I want the signature to look, that I then do a FindText and ReplaceText on.  This works fine for replacing text with text, but I can't figure out how to properly replace some of the holder text with
    an image and a link.  I found a few posts about adding images to word documents, but none that seem to work properly in this scenario.
    Any insight would be greatly appreciated, thanks!

    Dear BOFH,
    You are correct that method I outlined is not for inserting an image into a signature block (which would be in Outlook, not Word).  The links you post do certainly deal with outlook signatures, well done... Except that the question was about how to
    use a Powershell script to replace text in a Word document with an image.  Sure it was framed in the context of creating signatures, but the poster expressed that they already had a method of generating and replacing text, and just needed to know, as
    I did, how to do the thing they actually asked.
    Please BOFH... Please forgive my audacity in hoping to find a reference (any reference) to how to replace Word text with images via Powershell in a thread titled "Use Powershell to replace text with image in Word document".
    This is certainly a scripting question, and even something as simple as "You will need to call the .NET methods for the Word find/replace functionality.  Please ask in the Word forums for the correct method to use. 
    If you need help on calling .NET methods look HTTP ://here"support you offered combined with the contempt you offer in response to my actual substantive help to the actual question asked.
    BOFH, you are not better than us, just more arrogant.
    Can you please start your own question as this one has been closed.  Please see scripting guidelines.
    We cannot guarantee you satisfaction as this is a user supported forum.  The is no SLA for community support.  Perhaps if you posted a better worded question as a new topic someone might be able to help you resolve your issue.
    The topic you are posting on is closed and answered.
    ¯\_(ツ)_/¯

  • Need to create Meeting Request using Powershell with Outlook 2010 / 2013

    We will be creating around 100 meeting request based on data from excel, so planning to migrate it to SQL & using powershell we need to speed-up the progress.
    Script tried :
    http://social.technet.microsoft.com/Forums/scriptcenter/en-US/e88ca51c-62dd-493b-a0d1-ffe6a8696fdf/create-view-in-outlook-2013-using-powershell?forum=ITCG
    http://en.community.dell.com/techcenter/powergui/f/4833/t/19576698.aspx
    http://www.amandhally.net/2013/08/30/powershell-and-outlook-create-and-send-a-new-email-using-powershell-outlooktools-module/
    Do we have any working scripts, i tried few scripts it fails throwing error as below:
    New-Object : Exception calling ".ctor" with "0" argument(s): "Retrieving the COM class factory for component with CLSID 
    {0006F03A-0000-0000-C000-000000000046} failed due to the following error: 80080005 Server execution failed (Exception from HRESULT: 
    0x80080005 (CO_E_SERVER_EXEC_FAILURE))."
    At line:2 char:6
    + $o = New-Object Microsoft.Office.Interop.Outlook.ApplicationClass
    +      ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
        + CategoryInfo          : InvalidOperation: (:) [New-Object], MethodInvocationException
        + FullyQualifiedErrorId : ConstructorInvokedThrowException,Microsoft.PowerShell.Commands.NewObjectCommand
    You cannot call a method on a null-valued expression.
    At line:4 char:1
    + $a = $o.CreateItem($olAppointmentItem)
    + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
        + CategoryInfo          : InvalidOperation: (:) [], RuntimeException
        + FullyQualifiedErrorId : InvokeMethodOnNull
    Ganapathy

    Hi Ganapathys,
    For the error "failed due to the following error: 80080005", please Make sure that Outlook and Powershell are either both running as a standard user (not elevated) or that they are both running elevated as Administrator. They need to be running at the same
    integrity level to avoid that error.
    Please try to run powershell as standard user without "run as admin".
    If you have any feedback on our support, please click here.
    Best Regards,
    Anna Wang
    TechNet Community Support

  • Using Powershell to set Multiple timed.servers with variables

    Having an issue using PowerShell to set 3 timed.servers which are defined in a variable. Running the commands: $TimeServers = "IPaddress1,IPaddress2,IPaddress3"Set-NaOption -OptionName timed.servers -OptionValue $TimeServers Thanks in advance!

    Hi, The Set-NaOption CmdLet -optionvalue parameter expects a string and it shouldn't matter if that's a comma delimited string containing multiple IP Addresses. I noticed that whilst the cmdlet thows an error it does actually set the option value for all servers so this seems like it could be a bug (IMO). It might be possible to invoke the API using "Invoke-NaSystemApi" but I checked the ZAPI and noticed this also fails using ZExplore from the SDK: ZAPI Request: <?xml version="1.0" encoding="UTF-8"?>
    <netapp  xmlns="http://www.netapp.com/filer/admin" version="1.21">
      <options-set>
        <name>timed.servers</name>
        <value>192.168.100.10,192.168.100.11,192.168.100.12</value>
      </options-set>
    </netapp> ZAPI Results: <?xml version='1.0' encoding='UTF-8' ?>
    <netapp version='1.1' xmlns='http://www.netapp.com/filer/admin'>
        <!-- Output of options-set [Execution Time: 8610 ms] -->
        <results reason='Unable to set option: timed.servers' errno='13001' status='failed'>
            <cluster-constraint>same_preferred</cluster-constraint>
            <cluster_constraint>same_preferred</cluster_constraint>
            <message>1 entry was deleted.
    </message>
        </results>
    </netapp> So i think the options are either using the "Set-NaOption" cmdlet with the -SilentlyContinue parameter or the "Invoke-NaSsh" cmdlet with -ErrorAction stop.As a work around i'd recommend something like: [String]$servers = "192.168.100.10,192.168.100.11,192.168.100.12"
    [String]$command = "options timed.servers $servers"
    Try{
       Invoke-NaSsh -Command $command -ErrorAction Stop
       Write-Host "Executed Command: $command"   
    }Catch{
       Write-Warning -Message $("Failed Executing Command: $command. Error " + $_.Exception.Message)
    } Hope that helps /matt

  • Using PowerShell 1.0 copy-item GroupPolicy Folder(C:\WINDOWS\system32\GroupPolicy)

    Hello everybody,
    This is my first time posting in this forum and i have encounted an issue i hope you can help i'm trying to create a powershell 1.0 script as this is for Windows XP to copy default policy back to their original folder then do a gpupdate on the copmuter so
    that the Local policy are returned to their default but i'm having access denied as this is user account and needed a way to make it run as an administrator but without success as i'm new powershell. 
    Copy-Item 'C:\WINDOWS\system32\GroupPolicy\Original Group Policy for User and Machine\Machine\*' 'C:\WINDOWS\system32\GroupPolicy\Machine\'
    Copy-Item 'C:\WINDOWS\system32\GroupPolicy\Original Group Policy for User and Machine\User\*' 'C:\WINDOWS\system32\GroupPolicy\User\'
    Your help is much appreciated.

    Hi mniceguy81,
    Did you try to enable "run as" in XP ?
    Please refer to following link :
    http://support.microsoft.com/kb/294676
    And please try to use powershell command :
    $cred = New-Object Management.Automation.PSCredential("$UserName", $securePassword)
    copy-item xxxx xxxx -credential $cred
    Best Regards
    Elton Ji
    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.

  • Error Using New-WebServiceProxy cmdlet with SQL Agent Powershell Subsystem

    I created a powershell script to connect to SSRS via web service so I can cache reports in the database and expose them directly through our application. The script works fine when I run it through Powershell directly, but when I try running it through the
    SQL Agent Powershell subsystem I am getting a strange error:
    "A job step received an error at line 61 in a PowerShell script. The corresponding line is '$RS = New-WebServiceProxy -Class 'RS' -Namespace 'RS' -Uri $reportServerURI -UseDefaultCredential  '. Correct the script and reschedule the job. The error
    information returned by PowerShell is: 'Could not load file or assembly 'file:///C:\WINDOWS\TEMP\yfqiivtg.dll' or one of its dependencies. The system cannot find the file specified.  '.  Process Exit Code -1.  The step failed."
    I am using SQL Server 2014, SSRS 2014, Windows 8.1. The only difference I can think of is that when I run Powershell from the OS, I am using v 4.0 whereas when I run it from SQL Agent it loads v 2.0. My understanding is that v 2.0 supports the New-WebServiceProxy
    cmdlet, so I'm not convinced the version discrepancy is the culprit. Any ideas what might be causing this?
    On a side note, is there a way to have SQL Agent use Powershell 4.0 for the subsystem? v 2.0 feels a little dated for SQL Server 2014.

    Hi WilliamW,
    When creating a PowerShell job step, there is only one security context available, which is the "SQL Server Agent Service Account." That means that if you intend to execute PowerShell scripts from SQL Agent Job steps, the SQL Server Agent
    service account must have appropriate permissions.
    According to your error message, I recommend to check if the SQL Server Agent service account has access to the folder where the scripts live, as well as the folder C:\WINDOWS\TEMP.
    In addition, when we execute a PowerShell job step in SQL Server, SQL Server Agent subsystem run the sqlps utility, and the sqlps utility launches PowerShell 2.0 and imports the sqlps module. If you need to run a PowerShell v4.0 script from a SQL Server
    Agent job, you can create a proxy account to run the agent job which contains PowerShell script. For more details, please review this similar blog:
    Run a PowerShell v3 Script From a SQL Server Agent Job.
    Thanks,
    Lydia Zhang

  • How to add multiple users permissions to a calendar using powershell?

    I have an organization that was recently setup in Exchange Online and they have unique circumstances in that every user in the organization needs "reviewer"
    access to every other users calendars.  I cannot change the default permission since new users added after this should not be able to see these calendars details.  There are a few I will go back to run a Set command on to change an individual permission
    here and there for specific needs, but the main need is below.
    I have basic experience with powershell commands and have found how to manually add a single users permissions to a calendar using the command below:
    Add-MailboxFolderPermission -Identity alias:\calendar -user alias -AccessRights reviewer
    Since it's not realistic to run this command thousands of times changing the user aliases each time, I was hoping someone could help me build a command to run on a single mailbox's calendar that would add every current user in the organization with certain
    permissions such as "reviewer" or "availabilityonly".
    Thanks for the help!

    Hi,
    A possible solution is to do this via Security Groups.
    Add-MailboxFolderPermission -Identity [email protected]:\Calendar -User [email protected] -AccessRights Owner
    This way, you simply add users that require access to the CalendarOwnerAccessGroup
    You still have to run this on every mailbox that should have this feature, but that could be solved using powershell piping.
    http://technet.microsoft.com/en-us/library/ee176927.aspx
    /Anders Eide

  • Using powershell to deploy provider-hosted app and specify remote Url instead of using appinv.aspx page

    Hello all,
    Could you possibly help me with provider-hosted app development/deployment process.
    We developed SharePoint provider-hosted app that works just fine in development environment. Now we need to automate it's installation in test environment via powershell.
    In AppManifest.xml that we are deploying we have key instead of explicit URL:
    <App xmlns="http://schemas.microsoft.com/sharepoint/2012/app/manifest" Name="ShowAllRoomsApp" ProductID="{922a18aa-5592-b59a-4da9-4791baef02e7}" Version="1.0.0.0"
    SharePointMinVersion="15.0.0.0">
      <Properties>
        <Title>SomeTitle</Title>
        <StartPage>~remoteAppUrl/Pages/Default.aspx?{StandardTokens}</StartPage>
    If we use as
    https://technet.microsoft.com/en-us/library/jj655398.aspx recommends, we cannot specify Redirect Url as we can do this on
    /_layouts/appinv.aspx
    So now it seems like the only way to deploy this kind of solution is using appinv.aspx page.Or must we apply this URL in AppManifest on developing stage in Visual Studio?
    What did I miss?
    P. S. Even if I use /_layouts/appinv.aspx after powershell commandlets, I get error.

    hi,
    to deploy provider hosted app you need 2 things
    1. Client ID
    2. Redirect URL.
    What you can do you can generate app from visual studio using clientID and URL from developer enviornment.
    Now a app file is just a simple compressed zip file if you rename it as .zip and extract you will find AppManifest
    inside it. So to create an app for Testing enviornment what you have to to Get the CLient ID (from AppRegNew.aspx) in testing enviornment. Unzip .App file change the AppManifest with testing client ID and URL than again zip file and rename as .app.
    Now if you upload this file it will work.
    To automate this scenerio i have created a simple windows Application in which i Pass the Client ID and StartURl and an App File it unzips the app file make changes to app and again zip it.
    public static class AppPackageHelper
    public const string StartUrlExpression = "{0}?{1}";
    public const string StandardToken = "{StandardTokens}";
    public static string Publish(string appPath, string ClientId,string StartUrl)
    string tempDir = string.Empty;
    string outPutFile = string.Empty;
    try
    string parentDir = System.IO.Path.GetDirectoryName(appPath);
    outPutFile = System.IO.Path.Combine(parentDir, ClientId + "-Winshuttle.app");
    tempDir = System.IO.Path.Combine(parentDir, ClientId.ToString());
    Directory.CreateDirectory(tempDir);
    int lastInd = appPath.LastIndexOf('.');
    string tempPath = string.Empty;
    string targetFilePath = string.Empty;
    string cabPath = System.IO.Path.Combine(tempDir, System.IO.Path.GetFileNameWithoutExtension(appPath) + ".cab");
    FileInfo fInfo = new FileInfo(appPath) { IsReadOnly = false };
    File.Copy(appPath, cabPath);
    XDocument doc = null;
    string appManifest = string.Empty;
    using (ZipArchive zipArch = ZipFile.Open(cabPath, ZipArchiveMode.Update))
    appManifest = string.Format(@"{0}\AppManifest.xml", Directory.GetParent(cabPath).FullName);
    ZipArchiveEntry manifestEntry = zipArch.Entries.LastOrDefault(e => e.Name.ToLower() == "appmanifest.xml");
    manifestEntry.ExtractToFile(appManifest);
    doc = XDocument.Load(appManifest);
    XNamespace ns = doc.Root.GetDefaultNamespace();
    string defaultUrl = string.Format(StartUrlExpression, StartUrl.TrimEnd('/'), StandardToken);
    doc.Descendants(XName.Get("StartPage", ns.NamespaceName)).First().Value = defaultUrl;
    doc.Descendants(XName.Get("RemoteWebApplication", ns.NamespaceName)).First().Attribute(XName.Get("ClientId")).Value = setupInfo.ClientId.ToString();
    doc.Save(appManifest);
    if (manifestEntry != null)
    manifestEntry.Delete();
    zipArch.CreateEntryFromFile(appManifest, "AppManifest.xml");
    int totEnt = zipArch.Entries.Count;
    for (int e = 0; e < totEnt; e++)
    if (zipArch.Entries[e].Open().Length == 0)
    //if (zipArch.Entries.Count > totEnt && e >= totEnt) break;
    //zipArch.CreateEntry(zipArch.Entries[e].FullName);
    File.Delete(appManifest);
    if (File.Exists(outPutFile))
    File.Delete(outPutFile);
    File.Move(cabPath, outPutFile);
    return outPutFile;
    catch
    throw;
    finally
    if (System.IO.Directory.Exists(tempDir))
    System.IO.Directory.Delete(tempDir, true);
    return outPutFile;
    using System.IO.Compression.FileSystem.dll.
    Also if you want to do it using powershell You need to do the same thing unzip-> changes values-> zip
    So basic thing is You need to ahve only valid AppManifest file which contains 2 valid values Client Id and StartUrl
    if you changes it inside appmanifest manuall than it will also work. Using above code you can create a console Application to do it. You can use powershell it just that i dont know how to zip unzip in powershell but i am pretty sure you can easily find it
    on searching.
    Whenever you see a reply and if you think is helpful,Vote As Helpful! And whenever you see a reply being an answer to the question of the thread, click Mark As Answer

  • How to add calendar enries to all users in organization using powershell and EWS.

    I am one of the exchange admins for our organization.  Every year, we publish academic calendar data to all faculty and staff calendars.  We recently updated and migrated from Exchange 2003 to Exchange 2010 which, of course, desupported MAPI and
    ADO.  The processes we previously used had to be re-written using Exchange Web Services API (EWS).  Because I find that powershell is easy to work with, I wanted to integrate the calendar dispersal using powershell.
    Having not found much help online using the EWS .NET library in powershell for this purpose, I decided to share my code:
    # Bulk load calendar entries script
    # Description:
    # Script used to deploy Academic Calendar entries to all Exchange account calendars
    # Prerequisites:
    # Service account must have ApplicationImpersonation ManagementRoleAddisgnment
    # New-ManagementRoleAssignment -Name:impersonationRole -Role:ApplicationImpersonation -User:<srv_account>
    # Usage:
    # .\academicCalendar.ps1 calEntries.csv
    # Where calEntries.csv = list of calendar entries to add
    Param ([string]$calInputFile = $(throw "Please provide calendar input file parameter..."))
    $startTime = Get-Date
    $strFileName = "<path to log file>"
    if(Test-Path $strFileName)
    $logOutFile = Get-Item -path $strFileName
    else
    $logOutFile = New-Item -type file $strFileName
    # Load EWS Managed API library
    Import-Module -Name "C:\Program Files\Microsoft\Exchange\Web Services\1.0\Microsoft.Exchange.WebServices.dll"
    # Load all Mailboxes
    $exchangeUsers = Get-Mailbox -ResultSize Unlimited | Select PrimarySmtpAddress
    # Load all calendar Entries
    # Input file is in the following format
    # StartDate,EndDate,Subject
    # 8/29/2011,8/30/2011,First Day of Fall Classes
    $calEntries = Import-Csv $calInputFile
    # Setup the service for connection
    $service = new-object Microsoft.Exchange.WebServices.Data.ExchangeService([Microsoft.Exchange.WebServices.Data.ExchangeVersion]::Exchange2010)
    $service.Url = new-object System.Uri("https://<CAS_server_URL>/ews/exchange.asmx")
    $service.Credentials = new-object Microsoft.Exchange.WebServices.Data.WebCredentials("<service_account>","<password>","<domain>")
    $totalCount = $exchangeUsers.Count
    $currentCount = 0
    Write-Output "Exchange Version: $service.RequestedServerVersion"
    Write-Output "Mailbox Count: $totalCount"
    # Add message to log file
    $timeStamp = Get-Date -Format "MM/dd/yyyy hh:mm:ss"
    $message = "$timeStamp -- Begin Calendar Deployment `n"
    $message += "Total Exchange Accounts: $totalCount"
    Add-Content $logOutFile $message
    # Perform for each Mailbox
    $error.clear()
    foreach($mailbox in $exchangeUsers)
    $currentCount++
    if($mailbox.PrimarySmtpAddress -ne "")
    # Output update to screen
    $percentComplete = $currentCount/$totalCount
    Write-Output $mailbox.PrimarySmtpAddress
    "{0:P0}" -f $percentComplete
    # Setup mailbox parameters for impersonation
    $MailboxName = $mailbox.PrimarySmtpAddress
    $iUserID = new-object Microsoft.Exchange.WebServices.Data.ImpersonatedUserId([Microsoft.Exchange.WebServices.Data.ConnectingIdType]::SmtpAddress,$MailboxName)
    $service.ImpersonatedUserId = $iUserID
    # Indicate which folder to work with
    $folderid = new-object Microsoft.Exchange.WebServices.Data.FolderId([Microsoft.Exchange.WebServices.Data.WellKnownFolderName]::Calendar)
    $CalendarFolder = [Microsoft.Exchange.WebServices.Data.CalendarFolder]::Bind($service,$folderid)
    # For each entry in the input file
    $error.clear()
    foreach($entry in $calEntries)
    # First check to make sure the entry is not already in the calendar
    # use a calendarview object to pull the entries for the given date and make sure an entry with the same subject line doesnt already exist
    $cvCalendarview = new-object Microsoft.Exchange.WebServices.Data.CalendarView([System.DateTime]($entry.StartDate),[System.DateTime]($entry.EndDate))
    $cvCalendarview.PropertySet = new-object Microsoft.Exchange.WebServices.Data.PropertySet([Microsoft.Exchange.WebServices.Data.BasePropertySet]::FirstClassProperties)
    $frCalendarResult = $CalendarFolder.FindAppointments($cvCalendarview)
    $entryFound = $False
    foreach ($appointment in $frCalendarResult.Items)
    if($appointment.Subject -eq $entry.Subject)
    $entryFound = $True
    # If entry was found, then skip this entry
    if($entryFound)
    $entryFound = $False
    else # Create the appointment object and save it to the users calendar
    $appt = New-Object Microsoft.Exchange.WebServices.Data.Appointment($service)
    $appt.Subject = $entry.Subject
    $appt.Start = [System.DateTime]($entry.StartDate)
    $appt.End = [System.DateTime]($entry.EndDate) #For AllDayEvent, end date must be after start date
    $appt.IsAllDayEvent = $True #Set event as "All Day Event"
    $appt.LegacyFreeBusyStatus = "Free" #Make sure free/busy info shows user as "free" rather than "busy"
    $appt.IsReminderSet = $False #Make sure reminder is not set to remind the user of the event
    $appt.Save([Microsoft.Exchange.WebServices.Data.SendInvitationsMode]::SendToNone)
    if($error)
    $timeStamp = Get-Date -Format "MM/dd/yyyy hh:mm:ss"
    $message = $timeStamp + "...Exception Occurred while processing Save for: `n"
    $message += " Account: " + $MailboxName + "`n"
    $message += " Subject: " + $entry.Subject + "`n"
    $message += " Exception: " + $error[0].Exception + "`n"
    Add-Content $logOutFile $message
    $error.clear()
    if($error)
    $error.clear()
    else
    $message = "" + $MailboxName + "`t Success! `n"
    Add-Content $logOutFile $message
    Write-Output $currentCount
    $endTime = Get-Date
    $duration = New-TimeSpan $startTime $endTime
    $totalMin = $duration.TotalMinutes
    # Build and send email notification upon completion
    $body = "The Calendar deployment has completed. `n `n "
    $body += "Start Timestamp: $startTime `n "
    $body += "End Timestamp: $endTime `n "
    $body += "Duration: $totalMin min `n "
    $body += "Exchange accounts affected: $currentCount `n"
    $smtpServer = "<mysmtpserver>"
    $smtp = new-object Net.Mail.SmtpClient($smtpServer)
    $msg = new-object Net.Mail.MailMessage
    $msg.From = "<from_email_address>"
    $msg.To.Add("<to_email_address>")
    $msg.Subject = "Calendar Deployment"
    $msg.Body = $body
    $smtp.Send($msg)
    # Add closing message to log file
    $timeStamp = Get-Date -Format "MM/dd/yyyy hh:mm:ss"
    $message = "Accounts affected: $currentCount"
    Add-Content $logOutFile $message
    $message = "$timeStamp -- Completed in $totalMin min."
    Add-Content $logOutFile $message
    Please let me know if you think I can make any performance modifications.
    Daniel
    --Edit-- I have updated the script for Exchange 2010 SP1, also added logging, error checking and email notifications.  This new script also checks first to make sure the appointment doesn't already exist before adding it.  (To prevent multiple
    entries of the same event... Note: This check, although necessary in my opinion, is very time consuming.)

    Hi Daniel
    I am trying to add addition propertires like TV, Copier etc. to Room Mailbox in Exchange 2010 using following commands:-
    [PS] C:\Windows\system32>$ResourceConfiguration = Get-ResourceConfig
    [PS] C:\Windows\system32>$ResourceConfiguration.ResourcePropertySchema+=("Room/Whiteboard")
    Upper two commands run fine but following command gives error:-
    [PS] C:\Windows\system32>Set-ResourceConfig -ResourcePropertySchema $ResourceConfiguration.ResourcePropertySchema
    The term 'Set-ResourceConfig' is not recognized as the name of a cmdlet, function, script file, or operable program. Ch
    eck the spelling of the name, or if a path was included, verify that the path is correct and try again.
    At line:1 char:19
    + Set-ResourceConfig <<<<  -ResourcePropertySchema $ResourceConfiguration.ResourcePropertySchema
        + CategoryInfo          : ObjectNotFound: (Set-ResourceConfig:String) [], CommandNotFoundException
        + FullyQualifiedErrorId : CommandNotFoundException
    I also tried with space after set but still getting error:
    [PS] C:\Windows\system32>Set -ResourceConfig -ResourcePropertySchema $ResourceConfiguration.ResourcePropertySchema
    Set-Variable : A parameter cannot be found that matches parameter name 'ResourceConfig'.
    At line:1 char:20
    + Set -ResourceConfig <<<<  -ResourcePropertySchema $ResourceConfiguration.ResourcePropertySchema
        + CategoryInfo          : InvalidArgument: (:) [Set-Variable], ParameterBindingException
        + FullyQualifiedErrorId : NamedParameterNotFound,Microsoft.PowerShell.Commands.SetVariableCommand
    Pl advise the solution at [email protected] . I got this help from
    http://zbutler.wordpress.com/2010/03/17/adding-additional-properties-to-resource-mailboxes-exchange-2010/

  • How to set security group as primary site collection admin and secondary site collection admin using powershell in sharepoint online site - office 365?

    How to set security group as primary site collection admin and secondary site collection admin using powershell in sharepoint online site - office 365?

    Hi,
    According to your description, my understanding is that you want to set security group as admin of primary and secondary site collection using PowerShell command in office 365.
    I suggest you can use the command below to set the group to site owner, then it will have the site collection admin permission.
    Set-SPOSite -Identity https://contoso.sharepoint.com/sites/site1 -Owner [email protected] -NoWait
    Here are some detailed articles for your reference:
    https://technet.microsoft.com/en-us/library/fp161394(v=office.15)
    http://blogs.realdolmen.com/experts/2013/08/16/managing-sharepoint-online-with-powershell/
    Thanks
    Best Regards
    Jerry Guo
    TechNet Community Support

Maybe you are looking for