Listing Windows Updates by a Specific date using PowerShell

Create/update trouble tickets for updating servers.  I want to user PowerShell to get a list of the updates for a specific day.  
I've found some things that were close and came up with this:
$date = "1/21/2014"
$Session = New-Object -ComObject "Microsoft.Update.Session"
$Searcher = $Session.CreateUpdateSearcher()
$historyCount = $Searcher.GetTotalHistoryCount()
$Searcher.QueryHistory(0, $historyCount) | Where-Object {$_.Date -gt $date}  | Select-Object Title, Date > updates.txt
It works *but* the times are in GMT.  
How do I get them to print correctly?

The times are in standard datatime.
To get6 local time use Date.ToLocalTime()
$Searcher.QueryHistory(0, $historyCount) |
      Where-Object {$_.Date -gt $date}  | 
      Select-Object Title, @{N='Date';E={$_.Date.ToLocalTIme()}}
¯\_(ツ)_/¯

Similar Messages

  • Update picture for a user using powershell

    Hi,
    Is it possible to update a update a user profile picture using powershell?
    Thanks
    nish

    Hi,
    in your case it should be : 
    $profile["PictureURL"].Value = "http://dspm07pics/Userpics/andreas_seitz.jpg";
    Mourad

  • Set restriction to get messages older than a specific date using EWS?

    Hi, I'm new working with EWS and I have found some code to set a restriction to help me filter messages "between" to dates, but I need to be able to obtain emails that are "older" than a specific date so I can delete them.  My application needs to be
    able to clean up a mailbox to only to keep up to so many days/weeks worth of emails.  The code I have to search for emails that works
    between dates is:
    public void SetDateRestriction(FindItemType findItemRequest)
    DateTime dateStart = DateTime.Now;
    DateTime dateEnd = DateTime.Today.AddDays(-180);
    PathToUnindexedFieldType dateSentPath = new PathToUnindexedFieldType();
    dateSentPath.FieldURI = UnindexedFieldURIType.itemDateTimeSent;
    IsGreaterThanOrEqualToType isGreaterThanOrEqual = new IsGreaterThanOrEqualToType();
    isGreaterThanOrEqual.Item = dateSentPath;
    FieldURIOrConstantType dateConstant = new FieldURIOrConstantType();
    ConstantValueType dateConstantValue = new ConstantValueType();
    //dateConstantValue.Value = string.Format("{0}-{1}-{2}T00:00:00Z", dateStart.Year.ToString(), dateStart.Month.ToString(), dateStart.Day.ToString());
    dateConstantValue.Value = dateStart.ToUniversalTime().ToString("yyyy-MM-ddT00:00:00Z");
    dateConstant.Item = dateConstantValue;
    isGreaterThanOrEqual.FieldURIOrConstant = dateConstant;
    // less than or equal to
    PathToUnindexedFieldType dateSentPath1 = new PathToUnindexedFieldType();
    dateSentPath1.FieldURI = UnindexedFieldURIType.itemDateTimeSent;
    IsLessThanOrEqualToType lessThanOrEqualTo = new IsLessThanOrEqualToType();
    lessThanOrEqualTo.Item = dateSentPath1;
    FieldURIOrConstantType dateConstant1 = new FieldURIOrConstantType();
    ConstantValueType dateConstantValue1 = new ConstantValueType();
    //dateConstantValue1.Value = string.Format("{0}-{1}-{2}T00:00:00Z", dateEnd.Year.ToString(), dateEnd.Month.ToString(), dateEnd.Day.ToString());
    dateConstantValue1.Value = dateEnd.ToUniversalTime().ToString("yyyy-MM-ddT00:00:00Z");
    dateConstant1.Item = dateConstantValue1;
    lessThanOrEqualTo.FieldURIOrConstant = dateConstant1;
    RestrictionType restriction = new RestrictionType();
    AndType andType = new AndType();
    andType.Items = new SearchExpressionType[] { lessThanOrEqualTo , isGreaterThanOrEqual };
    restriction.Item = andType;
    findItemRequest.Restriction = restriction;
    How can I modify this to give me emails older than a specific date?  Also any input on doing the deleting would also be greatly appreciated!
    Best Regards,
    Nelson

    Thank you very much Glen!  I can't believe it was that easy.  Works perfect.  I will work on the DeleteItemType.  I was also wondering if there was a way to detect if an email is an Out-of-Office (OOO) or Undeliverable message? 
    My app goes through all the emails and I need to skip any that are OOO or Undeliverable messages.  I've learned how to use the SearchFilter and I find that easier and more straight forward than setting the restrictions.  I'm also able to use a SearchFilter
    to get emails older than the specified date. 
    Here's my new code for reading unread emails using the SearchFilter and paging (for better efficiency). 
    1 - Is there anyway to tell the filter to get AllProperties without having to specify each one using ItemSchema or EmailMessageSchema?
    2- What is the difference between those two (any advantages over one or the other)?
    3 -Is there any reason to even be using the ExchangeServiceBinding here anymore since it seems the ExchangeService object is all I need?  In my old code, I was using the ExchangeService object to do an AutoDiscover and then using that to set the URL
    in the ExchangeServiceBinding.  What are the main to difference/uses for these to objects?  Sorry if that's a dumb question.
    private void GetUnReadEmails(string sMailboxName)
    // Create the binding to Exchange
    ExchangeServiceBinding esb = new ExchangeServiceBinding();
    esb.RequestServerVersionValue = new RequestServerVersion();
    //Console.WriteLine("Exchange version: " + esb.RequestServerVersionValue.Version);
    //esb.RequestServerVersionValue.Version = ExchangeVersionType.Exchange2007_SP1;
    ExchangeService service = GetBinding(sMailboxName);
    Console.WriteLine("Exchange version: " + service.RequestedServerVersion);
    esb.Url = service.Url.ToString();
    esb.Credentials = new NetworkCredential(Username, Password, Domain);
    Mailbox mb = new Mailbox(sMailboxName);
    FolderId fid1 = new FolderId(WellKnownFolderName.Inbox, mb); // where fid1 was WellKnownFolderName.Inbox
    //FindFoldersResults findResults = service.FindFolders(fid1, new FolderView(int.MaxValue));
    ItemView iv = new ItemView(50, 0);
    FindItemsResults<Item> findResults = null;
    PropertySet ivPropSet = new PropertySet(BasePropertySet.IdOnly);
    //SearchFilter ivSearchFilter = new SearchFilter.SearchFilterCollection(LogicalOperator.And, new SearchFilter.IsEqualTo(EmailMessageSchema.IsRead, false), new SearchFilter.ContainsSubString(ItemSchema.Subject,"MSGID:"));
    SearchFilter searchFilter = new SearchFilter.IsEqualTo(EmailMessageSchema.IsRead, false);
    iv.PropertySet = ivPropSet;
    do
    findResults = service.FindItems(fid1, searchFilter, iv);
    string sText = "";
    if(findResults.Items.Count > 0)
    //PropertySet itItemPropSet = new PropertySet(BasePropertySet.IdOnly) { EmailMessageSchema.Body };
    PropertySet itemPropSet = new PropertySet(BasePropertySet.IdOnly) {ItemSchema.Subject, ItemSchema.Body, ItemSchema.DateTimeReceived, ItemSchema.HasAttachments, ItemSchema.ItemClass};
    itemPropSet.RequestedBodyType = BodyType.Text;
    service.LoadPropertiesForItems(findResults.Items, itemPropSet);
    //service.LoadPropertiesForItems(findResults.Items, itItemPropSet);
    //service.LoadPropertiesForItems(findResults, new PropertySet(ItemSchema.Subject, ItemSchema.Body, ItemSchema.DateTimeReceived));
    Console.WriteLine("Total items: " + findResults.TotalCount);
    foreach (Item item in findResults.Items)
    Console.WriteLine("ItemID: " + item.Id.UniqueId);
    Console.WriteLine("Subject: " + item.Subject);
    Console.WriteLine("Received date: " + item.DateTimeReceived);
    Console.WriteLine("Body: " + item.Body);
    Console.WriteLine("Has attachments: " + item.HasAttachments);
    //Mark the email as read
    EmailMessage emEmail = EmailMessage.Bind(service, item.Id);
    //emEmail.Load();
    emEmail.IsRead = true;
    emEmail.Update(ConflictResolutionMode.AlwaysOverwrite);
    sText += "Subject: " + (item.Subject.Trim()) + " ";
    //sText += "DisplayTo: " + (item.DisplayTo.Trim()) + " ";
    sText += "DateTimeReceived: " + (item.DateTimeReceived.ToString()) + " ";
    sText += "ItemClass: " + (item.ItemClass.Trim()) + " ";
    sText += "\r\n";
    else
    sText = "No unread emails";
    Console.WriteLine("No unread emails");
    txtItems.Text = sText;
    iv.Offset += findResults.Items.Count;
    } while (findResults.MoreAvailable == true);
    Thanks again for your time.  I appreciate it.
    Nelson

  • Update Schedule line Delivery date using Bapi_po_Change

    Hi all,
    I am using Bapi_po_change to Update the Schedule line Delivery date(EKET-EINDT) for the PO based on the Item and the Schedule line.
    I am passing the PO number, Po header, Item structure, Schedule line Structure.
    But the Date is not getting updated in the Eket table.
    Please suggest.

    Hi Sukriti,
    Thanks for the Response, yes i have used the Bapi Transaction Commit Also .
    The point is I am able to Update the Statistical Delivery Date in the Same EKET table using BAPI_PO_Change .I have Checked all the Ways to update the EKET-EINDT(Delivery Date)but no Unable to do it.

  • T500 - Windows Update no longer works after using factory recovery disks.

    I'm running  Windows 7 32bit.  I needed to restore my T-500 hard drive because of a fatal windows registry error caused by a 3rd party registry cleaner/tuner software... Windows 7 was DOA .   
    I used the factory recovery disks I created after I first fired up the laptop in April this year, all went well, Windows 7 booted up, and I went through the "Starting Widows for the first time" setup dialog, Windows 7 sucessfully activated... also verfifed it on the Microsoft website. 
    Went into control panel to have windows update pull down all of the critical updates released after I got my Thinkpad and I got a pop up saying "windows update cannot currently check for updates because the service is not running. You may need to restart your computer." 
    I checked... the windows update service is running, so is BITS.  Following suggestions from Microsoft support, I have 1)deleted the softwaredistribution folder from C:\windows, 2) run their "fixit tool", 3) renamed the CatRoot2 folder in C:\windows'system32, all to no avail each time I tried to use windows update after each "fix". 
    I decided to check here if anyone here has gone down this path before and ask what fixed it?
    I'm waiting for Microsoft support to reply to my last email informing them the last instructions to rename the CatRoot2 folder and retry windows update failed. They now have a copy of my windowsupdate.log file sent to them.
    How about it... does this situation sound familiar to anyone?
    Thanks.   

    I run into the same problem with fresh installation of W7 Pro on T530 with 1TB samsung disk.
    This solution worked for me:
        Running check for updates will trigger this error message:
    “Windows Update cannot currently check for updates, because the service is not running. You may need to restart your computer.”  
    Solution:
    1.    Go to Administrative Tools/Services, and stop the Windows Update service.
    2.    Then go to the folder c: /Windows/SoftwareDistribution and delete all of the files and folders.
    3.    Then go back to Services and restart the Windows Update service which will recreate all of those folders again.
    4.    Then manually run the Update Service and everything should work.

  • Windows Update no longer works after using Lenovo Enhanced Recovery

    Using the system recovery backup disk I created when I first got my T500, I performed a recovery to a new larger HD that I'm upgrading to. 
    All went well, windows booted up and I got the "Starting Windows for the first time" message and then I went through the setup wizard... Did everything like I did when first got the T500.  Windows 7 activation was successful
    Now here's the rub, I tried to use Windows Update retrieve all of the updates released since April when my laptop was built.  Windows Update flat out refuses to work. I keep getting a pop-up box saying "windows Update cannot currently check for updates, because the service is not running. You may need to start your computer".
    I checked the Windows Update service, it's running.  I've gone into the windows folder and deleted the software distribution folder as instructed by Microsoft support. They wanted me to also download and install a "CheckSUR"  tool from their support website, but the install falls with a a pop-up from Windows Update Standalone Installer with an error: 0xc8000247.
    Now this is all on the new HD, when I swap the older on back in there is no problem getting the updates.
    I'm stuck,  has anyone encountered this type of thing with Windows Update?  

    I executed the "fixit" in both modes at http://support.microsoft.com/kb/971058
    Windows update still refuses to work. All pertinent services are running.
    Since this is an attempt at installing a larger hd, I swapped back to the original drive and verified that windows update has no problems when running on the original HD.
    I've now started again from scratch. 
    I put the new  larger HD in a SATA/USB HD docking station that I just bought. I formatted the new HD clean, then instead of using the factory recovery disks like I did before, I used Acronis True Image, which I downloaded from the Western Digital support webpage, to clone the original HD over to the new one. 
    I powered off the laptop, pulled the original HD out and put the new HD in , unplugged the now empty SATA/USB HD docking station, booted up, windows starts and comes up with all looking fine, except... again, windows update still refuses to work. 
    I went back to the Microsoft website above, ran the fixit action in aggressive mode, and windows updates still gets the same result... When I open windows update in control panel, Windows Update is in red.  When I check for updates, I get the pop-up saying "Windows Update cannot currently check for updates, because the service is not running.  You may need to restart your computer". 
    A check of services shows that Windows Update, Cryptographic Service and Background Intelligent Transfer Service are all started.
    This is really frustrating... this should be a simple HD upgrade.   It appears that with whatever means that is used to copy or place an image of the original HD on the new HD, Windows 7 is not going to let me use update on the new drive.

  • How to run Windows update for Win XP SP3 using Firefox

    My desktop PC is running windows XP with SP3. My spouse uses IE 8 for her browser. I use Firefox Version 24. for my browser. Previously, whenever we ran MS or Windows update it starts IE and runs fine. IE 8 has blown up and no longer works (Runtime Errors). I tried to go to the Windows update website using Firefox and it came back and told me that I had to use IE to run Win update on an XP system. Is this true? I don't want to use IE at all. Is there a way to use Firefox to run Windows or MS update on my Win XP system? Thank you.

    Thanks for your help. That is not what I wanted to hear so I will have to try to get IE 8 working again. How do other folks do updates? Does this mean that IE is absolutely necessary to maintain your windows system? Is this true for the newer versions of Windows, 7 or 8?

  • Windows update does not work after using System recovery disk

    I have a Toshiba Satellite c655 with WIndows 7 64 bit Home premium. The hard drive died on it, so I purchased a new hard drive and purchased the appropriate Recovery media from Toshiba. I followed the directions and installed the 3 disks on to the new hard drive. But Windows update does not work I get the following error: Windows update can not currently check for updates, because the service is not running. You may need to restart your PC    No matter what I try, I can not get it to work. And it will not let me install Windows Defender either. Any ideas or help would be appreciated. Thank you in advance for your time on this matter.
    Solved!
    Go to Solution.

    I get errors saying A problem is preventing the troubleshooter from starting.
    That makes two similarities to the following thread. Both Windows Update and Troubleshooters fail to work correctly.
       Trouble with reinstall of Win7 64 on a L505-ES5018
    The fix was to install a new hard disk driver.
       Intel Rapid Storage Technology
    -Jerry

  • Is update approved for specific group via powershell?

    Hello, 
    I have a script that auto approves updates based on release date for specific groups. The script checks to see if the update has already been approved (e.g. isApproved) and either skips it if it's already been approved or approves it for my specific group
    (e.g. $update.approve("install",$wsus_group)). The problem I'm running into is if I approve Update1 for GroupA, then later check Update1's isApproved to see whether or not I need to approve it for GroupB, Update1's isApproved is $true and therefor
    my script skips approving it for GroupB. I've checked the update's object and I don't see a multi-valued var for groups that its been approved for. I've started to poke around with other
    Microsoft.UpdateServices.Administration namespaces but I don't see one that has the info I'm looking for. 
    So, how can I view what updates have been approved for GroupA vs GroupB?
    Thanks! 

    Hi Joey,
    If you want to approve updates to multiple groups, and also want to check if the updates have been approved to the groups, please check the script below:
    This can examine one computerGroup and find updates not approved for one or multiple other computer groups.
    $serverName="localhost"
    $targetComputerGroup="BaselineGroup"
    $checkForMissing="MissingGroup1,MissingGroup2"
    [void][reflection.assembly]::LoadWithPartialName("Microsoft.UpdateServices.Administration")
    $wsus=[Microsoft.UpdateServices.Administration.AdminProxy]::getUpdateServer($serverName,$false)
    $computerGroup=$wsus.GetComputerTargetGroups()|ForEach-Object -Process {if ($_.Name -eq $targetComputerGroup) {$_}}
    $UpdateScope=New-Object Microsoft.UpdateServices.Administration.UpdateScope
    $UpdateScope.ApprovedStates="Any"
    $updateScope.ApprovedComputerTargetGroups.Add($computerGroup)
    $Approvals = $wsus.GetUpdateApprovals($UpdateScope)
    #At this point we have all of the updates assigned to the $targetComputerGroup
    $report= @()
    write-host "Querying for all Updates approved for $targetComputerGroup"
    foreach ($Approval in $approvals) {
    $record=""|Select-Object ComputerGroup,UpdateName, UpdateID
    $record.ComputerGroup=$wsus.GetComputerTargetGroup($Approval.ComputerTargetGroupID).Name
    $record.UpdateName=$wsus.GetUpdate($Approval.UpdateID).Title
    $record.UpdateID=$wsus.GetUpdate($Approval.UpdateID).ID.UpdateID
    $report +=$record
    #Now group the results by UpdateName
    $GR=$report|group -Property UpdateName
    $CheckForMissing=$CheckForMissing.Split(",")
    foreach ($entry in $gr) {
    $groups=@()
    foreach ($g in $entry.Group) {
    $groups += $g.ComputerGroup
    foreach ($missing in $checkForMissing) {
    if ($groups -Contains $missing) {}
    else{
    New-Object PSObject -Property @{
    Name = $entry.Name
    UpdateID = $entry.Group[0].UpdateID
    GroupMissing = $missing
    Reference from:
    WSUS report approvals for a group
    I hope this helps.

  • Want to extract the data using powershell script.

    [Jul 21 15:01:47] INFO  (Fixmethod.java:1998) - UNABLE TO CONNECT TO FIX SERVER ATTEMPT NO:3 - logConsoleMsg
    I want to retrieve [Jul 21 15:01:47] from line above  into a variable. using powershell.
    How can it be done.
    Thanks in Advance.

    I tried "a.substring(1,15)", and it is working fine. :)
    Just be aware that it may not always work the way you expect it to. What happens when you only need 14 characters instead of 15?
    [Jul 1 15:01:47] instead of [Jul 21 15:01:47].
    This, of course, assumes that the dates aren't presented like so: [Jul 01 15:01:47]. If that's the case, you can just ignore this post.
    Don't retire TechNet! -
    (Don't give up yet - 12,950+ strong and growing)

  • Retrieve entire form data using powershell

    Hi,
    I wanted to retrieve all web applications and site collections and sub sites  and lists and libraries and in that I have some broken sites also.How to achieve this using powershell script.Please help.thanks in advance.
    Regards,
    Praveen

    Try this PowerShell code:
    Get-SPSite -Limit All |
       Select -ExpandProperty AllWebs |
       Select -ExpandProperty Lists |
       Select Title
    Explanation:
    Get-SPSite -Limit All : gets all site collections in the farm.
    Select -ExpandProperty AllWebs: Gets all subsites in the site collection
    Select -ExpandProperty Lists: Gets all lists in the site
    Select Title: Displays title of the list
    Blog | SharePoint Learnings CodePlex Tools |
    Export Version History To Excel |
    Autocomplete Lookup Field

  • Issue in update of PA & PD data using same form scenario

    Hi All,
         We're in the process of implementing HCM PF.  As per the requirement the form should be able to change PA, PSA, EG, ESG and Job of a position on PD & PA(of corresponding pernr) side.  The process is started as a PA form (selection by pernr). 
         I'm able to change the PA, PSA, EG, ESG of the position attribute but whenever I change the Job it gets updated on the PD side but not the PA side (it still holds the previous job prior to effective date).
         In my form scenario I have one PA & one PD service.
         Any help will be appreciated and rewarded in resolving this issue.
    Thanks,
    Mani.
    Edited by: mramamoorthy on Mar 14, 2011 7:01 PM

    Hi,
    Please check ur ISR Scenario,:
    Goto-> Process Form Scenario for Personnel Admin. Infotypes (Service SAP_PA):
    Define Operations:
    0001->M change
    Define Assignment of Fields:
    Field Name     Number     Infotype     Subtype     Screen Structure                       Field Name     Data Index
    Job     1     0001     1     HCMT_BSP_PA_XX_R0001     Job     1
    and do Synchronizing Form Fields.
    Then Do->Check Consistency of Form Scenarios in IMG activity.
    If you get green light then all configuration are correctly update.
    Otherwise problem in configuration side.
    Thanks

  • Updating one row of data using CMP

    Hi,
    How should I update a single row mapped with a CMP persitence, should I write a differetnt method for update , pl clarify in detail.

    Hi,
    How should I update a single row mapped with a CMP
    P persitence, should I write a differetnt method for
    update , pl clarify in detail.Hi,
    You can just find that particular Row using the findByPrimaryKey method the entity.
    This method actually returns the Remote Interface for the Entity which contains taht particular row of record.
    Use The setters of the Remote interface to update your existing Row.

  • How do I update columns in a library using PowerShell during a file upload?

    I am trying to put together a script that will do a bulk upload of files along with associated metadata into a SP library. The first part of the requirement is to upload .pdf files while grabbing the metadata from the file name. Currently, my script does
    the uploads, but it it does not update the fields with the metadata it is getting from the file names. Here is what my script curently looks like
    if((Get-PSSnapin "Microsoft.SharePoint.PowerShell") -eq $null)
    Add-PSSnapin Microsoft.SharePoint.PowerShell
    #Script settings
    $webUrl = "http://llc-hdc-spfe1d:19500/sites/SampleRecordCenter/"
    $docLibraryName = "My Library"
    $docLibraryUrlName = "MyLibrary"
    $localFolderPath = get-childitem "C:\test" -recurse
    #Open web and library
    $web = Get-SPWeb $webUrl
    $docLibrary = $web.Lists[$docLibraryName]
    $files = ([System.IO.DirectoryInfo] (Get-Item $localFolderPath)).GetFiles()
    ForEach($file in $files)
    if ($localFolderPath | where {$_.extension -eq ".pdf"})
    #Open file
    $fileStream = ([System.IO.FileInfo] (Get-Item $file.FullName)).OpenRead()
    # Gather the file name
    $FileName = $File.Name
    #remove file extension
    $NewName = [IO.Path]::GetFileNameWithoutExtension($FileName)
    #split the file name by the "-" character
    $FileNameArray = $NewName.split("_")
    $check = $FileNameArray.Length
    $myArray = @()
    foreach ($MetaDataString in $FileNameArray)
    #Add file
    $folder = $web.getfolder($docLibraryUrlName)
    write-host "Copying file " $file.Name " to " $folder.ServerRelativeUrl "..."
    $spFile = $folder.Files.Add($folder.Url + "/" + $file.Name, [System.IO.Stream]$fileStream, $true)
    if ($FileNameArray.Length -eq 3)
    #populate columns
    $spItem = $docLibrary.AddItem()
    $spItem["FirstColumn"] = $myArray[0]
    $spItem["SecondColumn"] = $myArray[1]
    $spItem["ThirdColumn"] = $myArray[2]
    $spItem.Update()
    elseif ($myArray.Length -eq 4)
    #populate columns
    $spItem = $docLibrary.AddItem()
    $spItem["FirstColumn"] = $myArray[0]
    $spItem["SecondColumn"] = $myArray[1]
    $spItem["ThirdColumn"] = $myArray[2]
    $spItem["FourthColumn"] = $myArray[3]
    $spItem.Update()
    #Close file stream
    $fileStream.Close();
    #Dispose web
    $web.Dispose()
    The .pdf files have the same naming convention like "first_second_third.pdf" and "first_second_third_fourth.pdf"...I want to grab each part of the file name, and put that data in the associated column in the library. Right now, am getting
    my file name and storing that information in an array, but my code isn't updating each column as I hope it will. What am I doing wrong here?
    Thanks for the help.

    Just figured out what was wrong with my logic...this does the trick.
    if ($localFolderPath | where {$_.extension -eq ".pdf"})
    $fileStream = ([System.IO.FileInfo] (Get-Item $file.FullName)).OpenRead()
    $FileName = $File.Name
    $NewName = [IO.Path]::GetFileNameWithoutExtension($FileName)
    $FileNameArray = $NewName.split("_")
    $folder = $web.getfolder($docLibraryUrlName)
    $spFile = $folder.Files.Add($folder.Url + "/" + $file.Name, [System.IO.Stream]$fileStream, $true)
    $spItem = $spFile.Item
    if ($FileNameArray.Length -eq 3)
    $spItem["FirstColumn"] = $FileNameArray[0].ToString()
    $spItem["SecondColumn"] = $FileNameArray[1].ToString()
    $spItem["ThirdColumn"] = $FileNameArray[2].ToString()
    $spItem.Update()
    elseif ($FileNameArray.Length -eq 4)
    $spItem["FirstColumn"] = $FileNameArray[0]
    $spItem["SecondColumn"] = $FileNameArray[1]
    $spItem["ThirdColumn"] = $FileNameArray[2]
    $spItem["FourthColumn"] = $FileNameArray[3]
    $spItem.Update()
    $fileStream.Close();

  • Add a list and column to about 200 sites using powershell in SharePoint online

    
    I have a sitecollection with about 200 identical sites. However I need to add a new list to each site and a lookup column (referring to this list) to two other lists. I'm not a developer so I struggle a bit. I found this as a starting point:
    [System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SharePoint.Client") | Out-Null
    [System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SharePoint.Client.Runtime") | Out-Null
    $WebUrl = 'https://yourtenant.sharepoint.com/sites/somesite'
    $EmailAddress = "[email protected]"
    $Context = New-Object Microsoft.SharePoint.Client.ClientContext($WebUrl)
    $Credentials = Get-Credential -UserName $EmailAddress -Message "Please enter your Office 365 Password"
    $Context.Credentials = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($EmailAddress,$Credentials.Password)
    $List = $Context.Web.Lists.GetByTitle("YourList")
    $FieldXml = "<Field Type='Text' DisplayName='New_Field_Display_Name' />"
    $Option=[Microsoft.SharePoint.Client.AddFieldOptions]::AddFieldToDefaultView
    $List.Fields.AddFieldAsXml($fieldxml,$true,$option)
    $Context.Load($list)
    $Context.ExecuteQuery()
    $Context.Dispose()
    Can someone help me out or is there a better solution?
    Thanks.
    

    Hi,
    According to your post, my understanding is that you wanted to add a list and a lookup column in about 200 identical sites.
    Per my knowledge, there is no out of the box way to achieve it in SharePoint Server, however, I’m not sure whether it is in SharePoint online.
    As this is the forum for SharePoint Server, you can post your question in the forum for SharePoint online.
    http://community.office365.com/en-us/forums/154.aspx.
    However, as you had known, we can achieve it programmatically.
    Besides the PowerShell command, we can also use the Client Object Model to achieve your scenario.
    If all the 200 sites in one site collection, we can first retrieve all the sites in the site collection, then add the list in every site.
    To retrieve all the sites in a site collection, you can refer to the following code snippets.
    static string mainpath = "SiteURL";
    static void Main(string[] args)
    getSubWebs(mainpath);
    Console.Read();
    public static void getSubWebs(string path)
    try
    ClientContext clientContext = new ClientContext( path );
    Web oWebsite = clientContext.Web;
    clientContext.Load(oWebsite, website => website.Webs, website => website.Title);
    clientContext.ExecuteQuery();
    foreach (Web orWebsite in oWebsite.Webs)
    string newpath = mainpath + orWebsite.ServerRelativeUrl;
    getSubWebs(newpath);
    Console.WriteLine(newpath + "\n" + orWebsite.Title );
    catch (Exception ex)
    http://chennaisharepointtraining.blogspot.in/2011/11/get-all-subwebs-using-client-object.html
    To create a list, you can have a look at the following article.
    http://msdn.microsoft.com/en-us/library/office/fp179912(v=office.15).aspx
    Thanks,
    Jason
    Forum Support
    Please remember to mark the replies as answers if they help and unmark them if they provide no help. If you have feedback for TechNet Subscriber Support, contact
    [email protected].
    Jason Guo
    TechNet Community Support

Maybe you are looking for

  • How can I update a location in the Apple Maps app?

    The location across the road from my office building shows that a high school is there, but that is not the case.  The high school has not been located across the road in over 20 years.  I found this error when I was updating the location information

  • JFileChooser Network Folder Issue

    Hello all Class : javax.swing.JFileChooser (network folders) J2SE : 1.4 OS : Windows I'm in need of urgent help for JFileChooser, scenerio is, currently when I do a open or save dialog using the JFileChooser it brings up the mapped network folders al

  • Pxi 4110 and dcpower express vi

    hi everyone, I'm really new to labview and I have to use a pxi 4110 to supply dc voltage with a square wave (or whatever shape I chose). I treid using the "dcpower express vi" but I can't understand how to connect the generated signal. at now I have

  • Extracting Audio from Video

    Hi, I was wondering if there is a way to get a Java program to read a video file, and extract its audio component into a separate audio file. I tried searching around for such capabilities in the java.sound and javax.media packages, but have had no l

  • Magic Trackpad Cursor Jumps or Moves Without the Trackpad Being Touched

    Magic Trackpad Cursor Jumps or Moves Without the Trackpad Being Touched. Try turning off your Bluetooth mouse or other nearby devices, especially if you find the cursor on your screen jumps or moves without the trackpad being touched. The cursor may