Using PowerShell to add VBA to an Excel spreadsheet

I have a PowerShell script that creates an Excel spreadsheet and is able to save it.  I also have VBA code that I would like to put into that newly created spreadsheet.
Is there a way of adding the VBA code into my newly created spreadsheet using PowerShell? 
Thanks,

Thanks for the response Alex,
Where I use to work, we would commonly do this with VBScript and Excel 2003.   Below is an example from the Scripting Repository using VBScript (Add a Macro
to an Excel Spreadsheet)
Set objExcel = CreateObject("Excel.Application")
objExcel.Visible = True
objExcel.DisplayAlerts = False
Set objWorkbook = objExcel.Workbooks.Open("C:\scripts\test.xls")
Set xlmodule = objworkbook.VBProject.VBComponents.Add(1)
strCode = _
"sub test()" & vbCr & _
" msgbox ""Inside the macro"" " & vbCr & _
"end sub"
xlmodule.CodeModule.AddFromString strCode
objWorkbook.SaveAs "c:\scripts\test.xls"
objExcel.Quit
We would use a variant of this method to generate static Excel reports from spreadsheets that were linked to external data sources.
Now...  it's time for me to upgrade my code and get on the PowerShell boat :)  So I have been working on a script that does a similar thing, but there does not appear to be a method of adding a macro to an Excel spreadsheet using PowerShell.  There
appears to be no way of calling VBProject.VBComponents.Add from within PowerShell.
I have tried manipulating the data that resides within Excel by directly accessing it from PowerShell, but this has proven to be painfully slow.  What a macro can do in 3 seconds, takes PowerShell 8 hours to do :(
If it can't be done... then I'll have to revert back to my old ways.  But if it can be done, great!!!  PowerShell has alot more to offer me than VBScript did.

Similar Messages

  • SP 2013 - Use PowerShell to Add a Custom Web Part to a Page

    Hello Community,
    I need to add a custom web part to a page using PowerShell - has anyone done this and if so please provide guidance and code examples.
    Thanks!
    Tom
    Tom Molskow - Senior SharePoint Architect - Microsoft Community Contributor 2011 and 2012 Award -
    Linked-In - SharePoint Gypsy

    BTW, here is my current code:
    #$web= Get-SPWeb -Identity "http://c4968397007/sites/BRE"
    $Url = "http://c4968397007/sites/BRE"
    $pageUrl = "/SitePages/Home"
    $webpartzone = 2
    $index = 0
    $fileName = "wp_DistrictHomePage_VisualWebPart1.webpart"
    $web = Get-SPWeb $Url
    $web.AllowUnsafeUpdates=$true
     $webPartGallery = $web.Lists["Web Part Gallery"]
     Write-Host "Searching webpart $fileName in web part gallery"
      if($webPartGallery -eq $null)
       Write-Host("Unable to retrieve Webpartgallery");
     $webpart = $null;
     $webpart=$webPartGallery.Items | ? { $_.Title -eq $fileName}
      if($webpart -eq $null) {
       Write-Host("Unable to retrieve webpart: $fileName") -ForegroundColor Red
     else {
      Write-Host("----------Adding Webpart--------")-ForegroundColor Yellow
      $webpartmanager=$web.GetLimitedWebPartManager($pageUrl, [System.Web.UI.WebControls.WebParts.PersonalizationScope]::Shared)
      $errorMsg = "";
      $xmlReader = New-Object System.Xml.XmlTextReader($webpart.File.OpenBinaryStream());
      $webpart = $webpartmanager.ImportWebPart($xmlReader,[ref]"Error")
      $webpartmanager.AddWebPart($webpart, $webpartzone, $index);
      Write-Host("Webpart is added successfully") -ForegroundColor Green ;
    $SiteURL =$Url
    #---------------Test Page----------------------------
    $PageName="Test.aspx"
    $page=$web.lists["Pages"].Items | ? {$_.Name -eq $PageName}
    $page.File.CheckOut();
    Add-WebPartToPage "$SiteURL/Pages/$PageName" "Header" 0 "My Custom WebPart"
    $page.File.CheckIn("Added Web part to a page");
    $page.File.Approve("Added Web part to a page");
    Tom Molskow - Senior SharePoint Architect - Microsoft Community Contributor 2011 and 2012 Award -
    Linked-In - SharePoint Gypsy

  • Add column comments from excel spreadsheet

    Is there a way to add descriptions that are captured in excel spreadsheets into a relational model's tables and columns? Would it need to be a transformation script or is there another way? Does anyone have a sample of how to do this?

    I use excel all the time to do this since it's easy for me. basically what I do is get everything I need down. Then I use excel to build the sql. I'll add a column with comment on column and other column with the table name with a period. I assume I've got the column name in one excel column and the comment in another. So I'll put a column between the column name and the comment and put in is'. Then after the comment I'll put in ';. Once that's done I load it into a text editor drop all the unnecessary spaces save it and run it.
    Do this with a lot of things. Dump the stuff I need out of the data dictionary or where ever. save it in excel and then do the same trick

  • How to Use AccessibleObjectFromWindow API in VBA to Get Excel Application Object from Excel Instance Window Handle

    I need to get the Excel.application object from a window handle using AccessibleObjectFromWindow. I can't seem to make the code work. First, I successfully search for the XLMAIN windows. Then, when I get a handle, I execute the AccessibleObjectFromWindow
    function. It seems to return a value of -2147467262 in all cases. Therefore, I believe that it is returning an error value. I can't figure out how to determine the meaning of this value.
    If it is an error value, I believe that one or more arguments are in error. My best guess at present is that the GUID argument is incorrect. I have tried two GUID values: {00020400-0000-0000-C000-000000000046} and {90140000-0016-0409-0000-0000000FF1CE}.
    I have seen both used in conjunction with OBJID_NATIVEOM. Neither one seems to work. I really would prefer not to use the second one as it has an Excel major and minor version number. I would hate to have to change this code, if a new minor version appeared.
    The attached code has been commented to show which parts have been shown to work and which not. I'm at my wits end and really need help.
    Thanks
    'This module is located in Access 2010, but this is an Excel question.
    Option Compare Database
    Option Explicit
    ' Module-Level Declarations
    'The GetDesktopWindow function and FindWindowEx function work just fine.
    Public Declare Function GetDesktopWindow Lib "user32" () As Long
    Public Declare Function FindWindowEx Lib "user32" Alias "FindWindowExA" _
    (ByVal hWnd1 As Long, _
    ByVal hWnd2 As Long, _
    ByVal lpsz1 As String, _
    ByVal lpsz2 As String) _
    As Long
    'I'm not getting the expected output from this function (see below)
    Private Declare Function AccessibleObjectFromWindow& Lib "oleacc.dll" _
    (ByVal hwnd&, _
    ByVal dwId&, _
    riid As GUID, _
    xlwb As Object)
    Type GUID
    lData1 As Long
    iData2 As Integer
    iData3 As Integer
    aBData4(0 To 7) As Byte
    End Type
    Function ExcelInstances() As Long
    ' Procedure-Level Declarations
    ' Value of OBJID_NATIVEOM verified by checking list of Windows API constants _
    on this site: http://www.lw-tech.com/q1/base.htm
    Const OBJID_NATIVEOM = &HFFFFFFF0
    Dim hWndDesk As Long 'Desktop window
    Dim hWndXL As Long 'Child window
    Dim objExcelApp As Object 'Final result wanted: Excel application object
    'Following variable (xlapp) to be set by AccessibleObjectFromWindow function
    Dim xlapp As Object
    Dim IDispatch As GUID 'GUID used in call to AccessibleObjectFrom Window function
    'Set up GUID to be used for all instances of Excel that are found
    Dim tmp1 As Variant 'Return value from AccessibleObjectFromWindow
    ' Executable Statements
    SetIDispatch IDispatch
    IDispatch = IDispatch
    'Get a handle to the desktop
    hWndDesk = GetDesktopWindow 'This seems to work
    Do
    'Get the next Excel window
    'The following statement seems to work. We are finding and counting _
    correctly all the instances of Excel. hWndXL is non-zero for each _
    instance of Excel
    hWndXL = FindWindowEx(GetDesktopWindow, hWndXL, "XLMAIN", vbNullString)
    'If we got one, increment the count
    If hWndXL > 0 Then
    'This works. We correctly count all _
    instances of Excel
    ExcelInstances = ExcelInstances + 1
    'Here is the problem. The following statement executes and returns a value of _
    -2147467262. xlapp, which is passed by reference to AccessibleObjectFromWindow, _
    is set to nothing. It should be set to the object for Excel.application. _
    I believe that this value is not an object. I tried to reference tmp1. in the _
    immediate window. There was no Intellisense.
    'I think that the function in returning an error value, but I can't figure _
    out what it is. I believe that AccessibleObjectFromWindow returns error _
    values, but I don't know where to find their values so I can interpret the _
    function's results.
    'As best I can tell, the hWndXL parameter is correct. It is the handle for _
    an instance of Excel. OBJID_NATIVEOM is set correctly (see constant declaration _
    above). xlapp is passed by reference as a non-initialized object variable, which _
    will be set by AccessiblObjectFromWindow. IDispatch may be the problem. It is set _
    as shown below in the procedure SetIDispatch(ByRef ID As GUID). This procedure _
    appears to work. I can see that IDispatch is set as I intended and correctly _
    passed to AccessibleObjectFromWindow.
    tmp1 = AccessibleObjectFromWindow(hWndXL, OBJID_NATIVEOM, IDispatch, xlapp)
    'Need to write code to test tmp1 for error. If none, then set objExcelApp = _
    object. Also, I exect xlapp to be set to Excel.application
    End If
    'Loop until we've found them all
    Loop Until hWndXL = 0
    End Function
    Private Sub SetIDispatch(ByRef ID As GUID)
    'Defines the IDispatch variable. The interface _
    ID is {90140000-0016-0409-0000-0000000FF1CE}.
    'NOT USING {00020400-0000-0000-C000-000000000046}, _
    which could be the problem
    '9 is release version - first version shipped (initial release)
    '0 is release type - retail/oem
    '14 is major version
    '0000 is minor version
    '0016 is product ID - MS Excel 2010
    '0409 is language identifier - English
    '0 is x86 or x64 - this is x86
    '000 reserved
    '0 is debug/ship
    '000000FF1CE is office family ID
    With ID
    .lData1 = &H90140000
    .iData2 = &H16
    .iData3 = &H409
    .aBData4(0) = &H0
    .aBData4(1) = &H0
    .aBData4(2) = &H0
    .aBData4(3) = &H0
    .aBData4(4) = &H0
    .aBData4(5) = &HF
    .aBData4(6) = &HF1
    .aBData4(7) = &HCE
    End With
    End Sub
    DaveInCalabasas

    I don't think you can return a reference to Excel's main window like that as you are attempting to do.
    Ref:
    http://msdn.microsoft.com/en-us/library/windows/desktop/dd317978(v=vs.85).aspx 
    It's relatively straightforward to return any workbook's window in any given instance, and in turn it's parent Excel app. Try the following and adapt as required (and include error handling) -
    Option Explicit
    Private Declare Function FindWindowEx Lib "User32" Alias "FindWindowExA" _
    (ByVal hWnd1 As Long, ByVal hWnd2 As Long, ByVal lpsz1 As String, _
    ByVal lpsz2 As String) As Long
    Private Declare Function IIDFromString Lib "ole32" _
    (ByVal lpsz As Long, ByRef lpiid As GUID) As Long
    Private Declare Function AccessibleObjectFromWindow Lib "oleacc" _
    (ByVal hWnd As Long, ByVal dwId As Long, ByRef riid As GUID, _
    ByRef ppvObject As Object) As Long
    Private Type GUID
    Data1 As Long
    Data2 As Integer
    Data3 As Integer
    Data4(7) As Byte
    End Type
    Private Const S_OK As Long = &H0
    Private Const IID_IDispatch As String = "{00020400-0000-0000-C000-000000000046}"
    Private Const OBJID_NATIVEOM As Long = &HFFFFFFF0
    Sub test()
    Dim i As Long
    Dim hWinXL As Long
    Dim xlApp As Object ' Excel.Application
    Dim wb As Object ' Excel.Workbook
    hWinXL = FindWindowEx(0&, 0&, "XLMAIN", vbNullString)
    While hWinXL > 0
    i = i + 1
    Debug.Print "Instance_" & i; hWinXL
    If GetXLapp(hWinXL, xlApp) Then
    For Each wb In xlApp.Workbooks
    Debug.Print , wb.Name
    Next
    End If
    hWinXL = FindWindowEx(0, hWinXL, "XLMAIN", vbNullString)
    Wend
    End Sub
    'Function GetXLapp(hWinXL As Long, xlApp As Excel.Application) As Boolean
    Function GetXLapp(hWinXL As Long, xlApp As Object) As Boolean
    Dim hWinDesk As Long, hWin7 As Long
    Dim obj As Object
    Dim iid As GUID
    Call IIDFromString(StrPtr(IID_IDispatch), iid)
    hWinDesk = FindWindowEx(hWinXL, 0&, "XLDESK", vbNullString)
    hWin7 = FindWindowEx(hWinDesk, 0&, "EXCEL7", vbNullString)
    If AccessibleObjectFromWindow(hWin7, OBJID_NATIVEOM, iid, obj) = S_OK Then
    Set xlApp = obj.Application
    GetXLapp = True
    End If
    End Function
    Note as written if an instance does not have any loaded workbooks a reference will not be returned (though a workbook can be added using DDE, but convoluted!)
    FWIW there are two other very different approaches to grab all running Excel instances though something along the lines of the above is simplest.
    Peter Thornton

  • Using PowerShell to Add Columns to A CSV File

    Hello,I wonder if someone can shed some light on this. I have a PowerShell script which has been working perfectly well pulling tab-seperated text log files off individual PCs, adjusting the data within and combining them into a single CSV for processing by our reporting tools via Excel and SQL. These files are call history logs generated by Toshiba Call Manager software installed on each PC. They keep a log of every call made by the phone linked to the individual user's software. By combining them for reporting, we get a clear and accurate picture of time spent on the phone etc.The problem we have is I need two extra columns added. One is for the person's name ('Person'), taken from the log file name, the other is a column for the call duration (which is logged under 'Dur' as a unit of time, e.g. 4:12 for 4 mins 12 seconds) and we...
    This topic first appeared in the Spiceworks Community

    Hello,I wonder if someone can shed some light on this. I have a PowerShell script which has been working perfectly well pulling tab-seperated text log files off individual PCs, adjusting the data within and combining them into a single CSV for processing by our reporting tools via Excel and SQL. These files are call history logs generated by Toshiba Call Manager software installed on each PC. They keep a log of every call made by the phone linked to the individual user's software. By combining them for reporting, we get a clear and accurate picture of time spent on the phone etc.The problem we have is I need two extra columns added. One is for the person's name ('Person'), taken from the log file name, the other is a column for the call duration (which is logged under 'Dur' as a unit of time, e.g. 4:12 for 4 mins 12 seconds) and we...
    This topic first appeared in the Spiceworks Community

  • BEX query runs using parameters entered by user in an Excel spreadsheet

    I'm trying to write a macro to automate certain functions for our users.</br>
    </br>
    Essentially, the users would enter numbers (relating to clients) in column A and e-mail adresses in column B.  A set of reports would run based on the first number entered, then the workbook would be saved and e-mailed to the first address in column B.  This would be repeated for the 2nd number/address and so on...  All Bex reports are in the same workbook.  At this point, I'm having a lot of problems finding code that will fill in the Bex query parameters automatically based on inputs in the spreadsheet.  Here is what I've worked up so far for the macro:</br>
    </br>
    Option Explicit</br>
    </br>
    'Macro step 1 u2013 run workbook for client number input and continue</br>
    'EXAMPLE u2013 cell A3 = 1008, cell A4 = 1240</br>
    'All BW queries should run based on the input given in column A (beginning wth A3).</br>
    </br>
    </br>
    'Macro step 2 u2013 create directory for the new files and save the first file</br>
    '     This step will allow the user to save the new files in a new folder in an existing directory, or even to create a new directory:</br>
    </br>
    Function GetFolderPath() As String</br>
        Dim oShell As Object</br>
        Set oShell = CreateObject("Shell.Application"). _</br>
        BrowseForFolder(0, "Please select folder", 0, "c:
    ")</br>
        If Not oShell Is Nothing Then</br>
            GetFolderPath = oShell.Items.Item.Path</br>
        Else</br>
            GetFolderPath = vbNullString</br>
        End If</br>
        Set oShell = Nothing</br>
    End Function</br>
    </br>
    Sub Testxl()</br>
        Dim FName As String</br>
        Dim WbName As String</br>
        Dim Search As String</br>
        Dim Prompt As String</br>
        Dim Title As String</br>
        Dim MyDir1 As String</br>
        Dim MyDir2 As String</br>
        Dim Passed As Long</br>
         </br>
    On Error GoTo Err:</br>
         </br>
        FName = GetFolderPath</br>
        If FName <> vbNullString Then</br>
            Prompt = "Please Select a FileName"</br>
            Title = "Name"</br>
            Search = InputBox(Prompt, Title)</br>
            If Search = "" Then Exit Sub</br>
        End If</br>
        FName = FName & "\" & Search</br>
        MkDir FName</br>
        ActiveWorkbook.SaveAs FName & "\" & Search & ".xls"</br>
         </br>
         'Test for existence of new folders.files</br>
        Passed = 1</br>
        GetAttr (FName)</br>
        Passed = 2</br>
        GetAttr (FName & "\" & Search & ".xls")</br>
        Passed = 3</br>
        GetAttr (ActiveWorkbook.Path & MyDir1)</br>
        Passed = 4</br>
        GetAttr (ActiveWorkbook.Path & MyDir2)</br>
    </br>
        End</br>
         'Sheets("Sheet1").Range("B1").Value = Search **Add if you require the name to be recorded in your spreadsheet</br>
    Err:</br>
        Select Case Err</br>
        Case 53:           MsgBox "File/Folder not created. Failed at step " & Passed</br>
        Case 75:    MsgBox "Folder already exists"</br>
        End Select</br>
    End Sub</br>
    </br>
    'Macro step 3 u2013 save workbook</br>
    ActiveWorkbook.Save</br>
    </br>
    'Macro step 4 u2013 e-mail workbook</br>
    'EXAMPLE u2013 cell B3 = amay@email, cell B4 = bmay@email</br>
    'The workbook should e-mail based on the input given in column B (beginning wth B3).</br>
    wb.SendMail  u201Ccell B3u201D</br>
    </br>
    'Macro step 5 u2013repeat until no inputs remain</br>
    'EXAMPLE u2013 cell A3 = 1008, cell A4 = 1240</br>
    'Steps 1-4 should repeat for cell A4, then A5 (if necessary) and so on until no more inputs remain.  </br>
    </br>
    </br>
    If anyone has any advice I'd love to try it out.</br>
    </br>
    Thank you for your time.</br>
    Andy
    Edited by: AndyMay on Jul 14, 2009 5:08 PM - I inserted html breaks

    Option Explicit</br>
    </br>
    Sub KeyClient()</br>
    </br>
    'Macro step 1 - filter workbook for client number input and continue</br>
    'EXAMPLE - cell B3 = 1008, cell B4 = 2048</br>
    'All BW queries should run based on the input given in column B (beginning wth B3).</br>
    </br>
    'define x and begin loop</br>
    Dim i, x As Integer</br>
    Dim curCell As Range</br>
        For x = 3 To 22</br>
        Set curCell = Worksheets("Input").Cells(x, 2)</br>
    </br>
    'stop BW from refreshing until we are finished</br>
        Run "SAPBEX.XLA!SAPBEXPauseOn"</br>
        Run "SAPBEx.XLA!SAPBEXsetFilterValue", curCell, "", Sheets("Client Contribution").Range("C9")</br>
    'BW resumes refreshing</br>
        Run "SAPBEX.XLA!SAPBEXPauseOff"</br>

  • Feature not appearing in site collection features list using powershell

    I created a custom web part solution which adds a custom web part to the web part gallery - simple.
    I did this on my dev server and used Visual Studio's deploy button to deploy it, and it all worked. The solution was added to the Solution Store, my feature was now in the Site Collection features list and automatically activated. So I checked my web part
    gallery and it was there as well... great.
    Now I'm ready to migrate my simple web part to my Prod server. I managed to use WSP builder to build my wsp. So now i have my wsp file.
    I used Powershell to add my solution to my Prod server, that worked. So I ran the Install-SPSolution command and looking at the logs, it all seemed to install fine. Here are the commands I used: 
    Add-SPSolution “E:\Deployment WSPs\HRFeedbackForm.wsp“
    Install-SPSolution -Identity "HRFeedbackForm.wsp" -GACDeployment
    However, when I go to my Site Collection Features, I can't see my feature. There is nothing in my 14 hive either and as far as I can see, and there are no errors in my log files.
    So what have I done wrong?
    So I tested adding and deploying the same solution on my dev box using Powershell and I had the same problem as what I've experienced on my Prod server. So what's the difference between deploying solutions via Visual Studio Deploy and using those powershell
    commands??? Is there something else I'm meant to change, somewhere?
    I hope someone can shed some light on this issue.
    Danielle :)

    Hi,
    I wonder whether you have to populate this web part by force in your web part gallery.
    For this, go to your Site's Home page. Then...
    Site Action > Site Settings > Galleries > Web Parts
    From here...
    Under Library Tools go to Documents Tab > Click on New Documents > The New Web Parts popup will open
    Here search for your web part. If you find it, select it and Check "Overwrite if file already exisists" and click on Populate Gallery.
    If the above does not work, I am stumped too. I will be curious what other members of the community have to add.
    Thanks, Soumya | MCITP, SharePoint 2010
    Omg it was there and i've added it to the web parts library and it works.... that was soooo strange.
    Thanks Soumya :)
    Can you explain at all why the web part has been added to the web part gallery, but the feature doesn't appear under site collection features?
    Danielle :)

  • TS1702 Using Numbers app, can't copy excel spreadsheet into Numbers via an attached email document on gmail.  Apple instructions state that an "open in" tab should be available. Can't locate this command. Only "open in Safari" appears.  Using app on iPad.

    USing Numbers app but can't copy excel spreadsheet attached to a gmail email into Numbers. Apple instruction state that you click on opened document and choose option to open in Numbers. Don't have this option, only an option to open in Safari. I need very complete instructions, I'm pretty new to IPad apps. Thanks!

    THanks, but no go.
    when I open spreadsheet attachment, only option is in lower right hand corner-- a box with arrow. When I touch this icon it gives me a choice to open in Safari or Cancel. No white dots.
    PLs be really basic with your response to me. I thought I am pretty computer literate but this has be baffled.
    THanks. I'm sure there is something "simple" that I'm missing.

  • To export pivot table from excel and save as picture using powershell

    I am trying to automate my work by attaching an excel file to email and send it across using powershell . But also, I want to paste the screenshot of  pivot table to my email body .
    One way to do it is to save only the pivot table as picture format like jpeg or png , then attach this picture to the email body .
    I am looking for an powershell script which will save my pivot table as picture format . I am using powershell V1.0
    please help .

    I'm not familiar with PowerShell script, we usually use VBA script within excel.
    The following article describes how to export Excel Range to a Picture File and attach it as the email body by VBA code, it might not be the answer you are looking for, but hope it will give you some inspirations.
    http://www.jpsoftwaretech.com/export-excel-range-to-a-picture-file/
    Also you can post your question to PowerShell forum to get better support.
    Best Regards,
    Wind Zhang

  • Removing non printable characters from an excel file using powershell

    Hello,
    anyone know how to remove non printable characters from an excel file using powershell?
    thanks,
    jose.

    To add - Excel is a binary file.  It cannot be managed via external methods easily.  You can write a macro that can do this.  Post in the Excel forum and explain what you are seeing and get the MVPs there to show you how to use the macro facility
    to edit cells.  Outside of cell text "unprintable" characters are a normal part of Excel.
    ¯\_(ツ)_/¯

  • Using Powershell Script Run simple query in MS Access 2007 and export the results of query to Excel

    Hi Experts,
    I have a Access 2007 DB file and 2 Big tables inside that (bigger than the size that can be easily handled by MS Excel 2007).
    My requirement is automate using powershell scripts the below things.
    1. Create a SQL query in Access DB and save that in access DB
    2. Run the saved query and export the result in excel sheet where I can create the charts and Pivots. Thanks in advance
    Prajesh

    Do you have to use the Access query, couldn't you just recreate the query in Powershell?  Here's a link with good info that references an existing script for querying an Access database:
    http://blogs.technet.com/b/heyscriptingguy/archive/2009/08/13/hey-scripting-guy-can-i-query-a-microsoft-access-database-with-a-windows-powershell-script.aspx
    Once you have your dataset you can pipe it to
    Export-Csv -NoType c:\pathtofile\output.csv

  • How to add a certificate to IIS global "Server Certificates" list using PowerShell?

    Hi, been surfing the web for an example on how to add a certificate to the "global" IIS "Server Certificates" list using PowerShell but to no luck. I already have code in place on how to tie / associate a specific website with a specific cert but not how
    to add the new .cer file using the "Complete Certificate Request..." wizard using PowerShell.... I dont expect the final code to become published but if someone had an idea on howto integrate / get an entry point on where to interact between the "Server Certificate"
    list in IIS and POSH I would be super happy! :|
    I am runnign IIS on a Windows 2008R2 x64 Standard Edition if that helps..... of course, I would saddle for an CLI if there is no other way, but POSH is of course the way to go! :)
    Thanks for the help in advance guys, take care!
    br4tt3

    Hi and thanks for the suggestions!
    Although it comes close, the suggested code example points on howto import / incorporate .pfx files - I am getting fed by .cer files which I need to add into the IIS console using POSH.
    I tried explore the IIS.CertObj object but was not able to work out if this one could be used for importing / adding .cer files into IIS! However, launching the following command from a POSH console with Import-Module Webadministration already
    loaded into that shell;
    $certMgr = New-Object -ComObject IIS.CertObj returns the following error message:
    New-Object : Cannot load COM type IIS.CertObj
    From an IIS perspective I have the following components installed;
    [X] Web Server (IIS)                                    Web-Server
        [X] Web Server                                      Web-WebServer
            [ ] Common HTTP Features                        Web-Common-Http
                [ ] Static Content                          Web-Static-Content
                [ ] Default Document                        Web-Default-Doc
                [ ] Directory Browsing                      Web-Dir-Browsing
                [ ] HTTP Errors                             Web-Http-Errors
                [ ] HTTP Redirection                        Web-Http-Redirect
                [ ] WebDAV Publishing                       Web-DAV-Publishing
            [X] Application Development                     Web-App-Dev
                [ ] ASP.NET                                
    Web-Asp-Net
                [X] .NET Extensibility                      Web-Net-Ext
                [ ] ASP                                    
    Web-ASP
                [ ] CGI                                    
    Web-CGI
                [ ] ISAPI Extensions                        Web-ISAPI-Ext
                [ ] ISAPI Filters                           Web-ISAPI-Filter
                [ ] Server Side Includes                    Web-Includes
            [ ] Health and Diagnostics                      Web-Health
                [ ] HTTP Logging                            Web-Http-Logging
                [ ] Logging Tools                           Web-Log-Libraries
                [ ] Request Monitor                         Web-Request-Monitor
                [ ] Tracing                                
    Web-Http-Tracing
                [ ] Custom Logging                          Web-Custom-Logging
                [ ] ODBC Logging                            Web-ODBC-Logging
            [X] Security                                   
    Web-Security
                [ ] Basic Authentication                    Web-Basic-Auth
                [ ] Windows Authentication                  Web-Windows-Auth
                [ ] Digest Authentication                   Web-Digest-Auth
                [ ] Client Certificate Mapping Authentic... Web-Client-Auth
                [ ] IIS Client Certificate Mapping Authe... Web-Cert-Auth
                [ ] URL Authorization                       Web-Url-Auth
                [X] Request Filtering                       Web-Filtering
                [ ] IP and Domain Restrictions              Web-IP-Security
            [ ] Performance                                 Web-Performance
                [ ] Static Content Compression              Web-Stat-Compression
                [ ] Dynamic Content Compression             Web-Dyn-Compression
        [X] Management Tools                                Web-Mgmt-Tools
            [X] IIS Management Console                      Web-Mgmt-Console
            [X] IIS Management Scripts and Tools            Web-Scripting-Tools
            [ ] Management Service                          Web-Mgmt-Service
            [ ] IIS 6 Management Compatibility              Web-Mgmt-Compat
                [ ] IIS 6 Metabase Compatibility            Web-Metabase
                [ ] IIS 6 WMI Compatibility                 Web-WMI
                [ ] IIS 6 Scripting Tools                   Web-Lgcy-Scripting
                [ ] IIS 6 Management Console                Web-Lgcy-Mgmt-Console
        [X] FTP Server                                      Web-Ftp-Server
            [X] FTP Service                                 Web-Ftp-Service
            [X] FTP Extensibility                           Web-Ftp-Ext
        [ ] IIS Hostable Web Core                           Web-WHC
    More or less the one thing that I am trying to get up and running is an automated FTPS solution - I just use the IIS console to be able to troubleshoot / compare how things scripted from POSH interacts in the MMC representation. The error I am getting
    might be that I am lacking some IIS components to be in place to be able to automate some parts of the IIS - as suggested by the IIS.CertObj object listed in the example..... I will get back if I can track down which component needs to be added to be
    able to reference the IIS.CertObj object.
    Br4tt3 signing out...
    br4tt3

  • 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

  • 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 can I define a name in Excel using Powershell?

    I know how to reference existing names using the RANGE function but how can I create a new defined name using Powershell?
    My specific case involves defining a name for a single cell with a workbook scope.  Just as if you were to right-click a cell in Excel and choose Define Name.
    The closest I've gotten is the NAMES object for the workbook but when I "gm" that all I see is a method for delete - nothing for adding.
    $xlsx = "c:\Sample.xlsx"
    $excel = new-object -comobject Excel.Application
    $xlb = $excel.Workbooks.Open($xlsx)
    $xlb.names | gm

    In Excel a Range has a name.  You can create a range and name it.  "Names" is just a list of the names that have been defined.
    So what is it that you are asking?  If your spreadsheet has names this will find them for you.
    Try this:
    $xlb.names|select name
    $r=$xlb.sheets.item(1).UsedRange
    $r.Name='all'
    # now do this again
    $xlb.names|select name
    So now you know everything about "names" or, as us old pros say "named ranges" like in the old  west.
    ¯\_(ツ)_/¯

Maybe you are looking for

  • How do I import my email and address book from Netscape mail 7.1?

    I've been using Netscape Mail 7.1 since it first came out, but I'm moving to the Apple Mac world and need to keep my old emails. I've been told by the Apple Genius Bar people that I could do this with Thunderbird.

  • 6120 classic:My voice commands do not work

    Please help. Don't know if I'm just being stupid or there is something not right with my 6120c. My voice commands do not work. If I press the button for a voice command, it says that there are no voice tags saved. If I go into the voice command appli

  • WLS6.1 SP2/JDK1.3.1_03/HTTP 302 Error

    Hello, we use WLS6.1 SP2 with JDK1.3.1_03 and we get sometimes an HTTP 302 error, when a JSP-page is requested. The error appears in the browser is following:      This document you requested has moved temporarily.      It's now at </zv/account/accou

  • Do search engines make use of IPTC Core metadata?

    I'm using Bridge to organise a large group of maps (the maps are JPEG images), which will be published on my organisation's website. These maps are about niche topics and very specific areas of the UK. I'm wondering if there are any SEO benefits from

  • Importing Word File - Page Defaults

    I am importing from Word and the Default of 2 columns is always chosen.  I wish to have only 1 column or blank to reflect the 1 for mapping of word page to Ibook page.  I can't seem to find the ability to change this setting anywhere.