protected override void ProcessRecord()
        {
            if (parFile.StartsWith(@".\"))
            {
                parFile = System.IO.Path.Combine(this.CurrentProviderLocation("FileSystem").ProviderPath, parFile.Substring(2));
            }

            parFile = System.IO.Path.GetFullPath(parFile);

            try
            {
                string destName = string.Format("{0}\\{1}.{2}", Path.GetDirectoryName(parFile), Path.GetFileNameWithoutExtension(parFile), formatName);
                WriteVerbose(string.Format("Will convert {0} to {1}", parFile, destName));

                if (System.IO.File.Exists(destName) && !parOverwrite)
                {
                    WriteError(new ErrorRecord(new UnauthorizedAccessException(string.Format("File already exists and overwrite not specified", destName)), "200", ErrorCategory.PermissionDenied, destName));
                }
                else
                {
                    IDynamic doc = msWord.Property("Documents").Get().Method("Open").AddParameter(parFile).AddMissingParameters(15).Invoke();
                    doc.Method("SaveAs").AddRefParameter(destName).AddRefParameter(format).Invoke();
                    if (!parNoExit)
                    {
                        doc.Method("Close").AddParameter(0).Invoke();
                    }
                }
            }
            catch (Exception ex)
            {
                WriteError(new ErrorRecord(new InvalidDataException(string.Format("Conversion failed: {0}", ex.Message)), "201", ErrorCategory.ParserError, parFile));
            }
        }
Ejemplo n.º 2
0
        private RowCollection GetRows(IDynamic workSheet)
        {
            List <object>      result  = new List <object>();
            DynamicTypeManager dynType = new DynamicTypeManager("Sorlov.PowerShell.MicrosoftOffice", "ExcelWorkbook#" + parFile.GetHashCode().ToString());


            IDynamic endCell = workSheet.Property("Cells").Get().Property("SpecialCells").PropertyParam(11).Get();
            IDynamic range   = workSheet.Property("Range").PropertyParam("A1").PropertyParam(GetExcelCellName(endCell.Property("Column").Get <int>(), endCell.Property("Row").Get <int>())).Get();

            IDynamic columns     = range.Property("Columns").Get();
            int      columnCount = columns.Property("Count").Get <int>();

            IDynamic rows     = range.Property("Rows").Get();
            int      rowCount = rows.Property("Count").Get <int>();

            int startingRow    = range.Property("Row").Get <int>();
            int startingColumn = range.Property("Column").Get <int>();

            for (int i = 0; i < columnCount; i++)
            {
                string colName = workSheet.Property("Cells").Get().Index(startingRow, startingColumn + i).Get().Property("Value").Get <string>();
                if (colName == null)
                {
                    break;
                }
                dynType.CreateProperty(colName, typeof(string));
            }


            for (int i = 1; i < rowCount; i++)
            {
                object newRow = dynType.Create();

                for (int j = 0; j < columnCount; j++)
                {
                    string colName = workSheet.Property("Cells").Get().Index(startingRow, startingColumn + j).Get().Property("Text").Get <string>();
                    if (colName == null)
                    {
                        break;
                    }

                    string cellData = workSheet.Property("Cells").Get().Index(startingRow + i, startingColumn + j).Get().Property("Text").Get <string>();
                    DynamicTypeManager.SetProperty(newRow, colName, cellData);
                }

                result.Add(newRow);
            }


            return(new RowCollection(result));
        }
        protected override void BeginProcessing()
        {
            base.BeginProcessing();

            if (!(GetOfficeVersion.GetVersion("Word")).IsInstalled)
            {
                ThrowTerminatingError(new ErrorRecord(new FileNotFoundException("Excel is not installed"), "1", ErrorCategory.InvalidOperation, null));
            }


            msWord = BindingFactory.CreateAutomationBinding("Word.Application");
            if (parDisplay)
            {
                WriteVerbose("Display have been set, making application visible");
                msWord.Property("Visible").Set(true);
            }

            switch (parFormat.ToLower())
            {
            case "word": format = 12; formatName = "docx"; break;

            case "word97": format = 0; formatName = "doc"; break;

            case "pdf": format = 17; formatName = "pdf"; break;

            case "xps": format = 18; formatName = "xps"; break;

            case "odf": format = 23; formatName = "odf"; break;

            case "rtf": format = 6; formatName = "rtf"; break;
            }

            WriteVerbose(string.Format("Setting output format to {0} (.{1})", parFormat, formatName));
        }
Ejemplo n.º 4
0
        protected override void BeginProcessing()
        {
            base.BeginProcessing();

            if (!(GetOfficeVersion.GetVersion("Excel")).IsInstalled)
            {
                ThrowTerminatingError(new ErrorRecord(new FileNotFoundException("Excel is not installed"), "1", ErrorCategory.InvalidOperation, null));
            }

            //if (!ValidLicense())
            //    ThrowTerminatingError(new ErrorRecord(new Licensing.InvalidLicenseException("Product licence could not be verified"), "10", ErrorCategory.SecurityError, null));

            msExcel = BindingFactory.CreateAutomationBinding("Excel.Application");
            if (parDisplay)
            {
                WriteVerbose("Display have been set, making application visible");
                msExcel.Property("Visible").Set(true);
            }

            currentCulture = Thread.CurrentThread.CurrentCulture;
            int langSettings = msExcel.Property("LanguageSettings").Get().Property("LanguageID").PropertyParam(2).Get <int>();

            CultureInfo newCulture = new CultureInfo(langSettings);

            WriteVerbose(string.Format("Changing culture ({0}->{1})", currentCulture.DisplayName, newCulture.DisplayName));
            Thread.CurrentThread.CurrentCulture = newCulture;

            switch (parFormat.ToLower())
            {
            case "excel": format = 51; formatName = "xlsx"; break;

            case "excel97": format = 56; formatName = "xls"; break;

            case "pdf": format = 57; formatName = "pdf"; break;

            case "xps": format = 58; formatName = "xps"; break;
            }

            WriteVerbose(string.Format("Setting output format to {0} (.{1})", parFormat, formatName));
        }
Ejemplo n.º 5
0
        private WorksheetCollection GetWorksheets(IDynamic workBook)
        {
            List <Worksheet> result = new List <Worksheet>();

            IDynamic nativeWorksheets = workBook.Property("Worksheets").Get();
            int      sheetCount       = nativeWorksheets.Property("Count").Get <int>();

            for (int i = 1; (i - 1) < sheetCount; i++)
            {
                Worksheet newSheet = new Worksheet();

                IDynamic nativeworkSheet = nativeWorksheets.Index(i).Get();
                newSheet.Name = nativeworkSheet.Property("Name").Get <string>();

                newSheet.Rows = GetRows(nativeworkSheet);

                result.Add(newSheet);
            }

            return(new WorksheetCollection(result));
        }
Ejemplo n.º 6
0
        protected override void BeginProcessing()
        {
            base.BeginProcessing();

            if (!(GetOfficeVersion.GetVersion("Excel")).IsInstalled)
            {
                ThrowTerminatingError(new ErrorRecord(new FileNotFoundException("Excel is not installed use Out-OExcel instead."), "1", ErrorCategory.InvalidOperation, null));
            }


            if (parPath.StartsWith(@".\"))
            {
                parPath = System.IO.Path.Combine(this.CurrentProviderLocation("FileSystem").ProviderPath, parPath.Substring(2));
            }

            parPath = System.IO.Path.GetFullPath(parPath);

            WriteVerbose(string.Format("Checking for existance of file {0}", parPath));
            WriteProgress(new ProgressRecord(10, "Out-Excel", "Initializing.."));

            if (File.Exists(parPath))
            {
                if (!parOverwrite)
                {
                    WriteVerbose("File exists and -Overwrite have not been specified");
                    ThrowTerminatingError(new ErrorRecord(new System.IO.IOException("The file already exists and -Overwrite have not been specified"), "100", ErrorCategory.ResourceExists, parPath.ToString()));
                }
                else
                {
                    WriteVerbose("File exists and -Override have been specified, will delete file");
                    File.Delete(Path);
                }
            }

            WriteVerbose("Starting Microsoft Excel");
            msExcel = BindingFactory.CreateAutomationBinding("Excel.Application");

            currentCulture = Thread.CurrentThread.CurrentCulture;
            int langSettings = msExcel.Property("LanguageSettings").Get().Property("LanguageID").PropertyParam(2).Get <int>();

            CultureInfo newCulture = new CultureInfo(langSettings);

            WriteVerbose(string.Format("Changing culture ({0}->{1})", currentCulture.DisplayName, newCulture.DisplayName));
            Thread.CurrentThread.CurrentCulture = newCulture;

            if (parDisplay)
            {
                WriteVerbose("Display have been set, making application visible");
                msExcel.Property("Visible").Set(true);
            }

            WriteProgress(new ProgressRecord(10, "Out-Excel", "Creating document.."));
            try
            {
                WriteVerbose("Creating new document");
                workBook = msExcel.Property("Workbooks").Get().Method("Add").Invoke();
            }
            catch
            {
                workBook.Method("Close").AddParameter(0).Invoke();
                msExcel.Method("Quit").AddParameter(0).Invoke();
                WriteVerbose("Document creation failed ");
                ThrowTerminatingError(new ErrorRecord(new System.IO.IOException("Document creation failed"), "101", ErrorCategory.ResourceUnavailable, msExcel));
            }

            WriteVerbose("Activating document");
            workBook.Method("Activate").Invoke();
        }
Ejemplo n.º 7
0
        protected override void EndProcessing()
        {
            base.EndProcessing();

            if (tableStyle == string.Empty)
            {
                tableStyle = "TableStyleMedium9";
            }
            WriteVerbose("Setting table styles");
            WriteProgress(new ProgressRecord(10, "Out-Excel", "Formatting tables.."));

            IDynamic dynamicWorksheets = workBook.Property("Worksheets").Get();
            int      tableCount        = dynamicWorksheets.Property("Count").Get <int>();

            for (int i = 1; (i - 1) < tableCount; i++)
            {
                //worksheet.ListObjects.Add(XlListObjectSourceType.xlSrcRange,worksheet.Range("A1",worksheet.Cells.SpecialCells(XlCellType.xlCellTypeLastCell)), Type.Missing, XlYesNoGuess.xlYes,"Table1",tableStyle);
                IDynamic worksheet = dynamicWorksheets.Index(i).Get();

                IDynamic endCell = worksheet.Property("Cells").Get().Property("SpecialCells").PropertyParam(11).Get();
                IDynamic range   = worksheet.Property("Range").PropertyParam("A1").PropertyParam(GetExcelCellName(endCell.Property("Column").Get <int>(), endCell.Property("Row").Get <int>())).Get();

                worksheet.Property("Columns").Get().Method("AutoFit").Invoke();
                worksheet.Property("ListObjects").Get().Method("Add").AddParameter(1).AddParameter(range.InstanceObject).AddMissingParameters(1).AddParameter(1).AddParameter("Table1").AddParameter(tableStyle).Invoke();
            }

            WriteProgress(new ProgressRecord(10, "Out-Excel", "Saving document.."));
            int format = 0;

            switch (parFormat.ToLower())
            {
            case "excel": format = 51; break;

            case "excel97": format = 56; break;

            case "pdf": format = 57; break;

            case "xps": format = 58; break;
            }

            WriteVerbose(string.Format("Saving document in {0}", parFormat));

            try
            {
                workBook.Method("SaveAs").AddRefParameter(parPath).AddRefParameter(format).Invoke();
            }
            catch (Exception ex)
            {
                WriteVerbose("Save failed, see error log for details");

                if (parNoExit)
                {
                    WriteVerbose("-NoExit specified, making word visible if not already");
                    msExcel.Property("Visible").Set(true);
                }
                else
                {
                    WriteVerbose("-NoExit not specified, quitting Excel");
                    workBook.Method("Close").AddParameter(0).Invoke();
                    msExcel.Method("Quit").Invoke();
                }


                ThrowTerminatingError(new ErrorRecord(ex, "300", ErrorCategory.FromStdErr, parPath));
            }

            if (parNoExit)
            {
                WriteVerbose("-NoExit specified, making Excel visible if not already");
                msExcel.Property("Visible").Set(true);
            }
            else
            {
                WriteVerbose("-NoExit not specified, quitting word");
                workBook.Method("Close").AddParameter(0).Invoke();
                msExcel.Method("Quit").Invoke();
            }

            WriteVerbose("Reverting culture");
            Thread.CurrentThread.CurrentCulture = currentCulture;

            WriteProgress(new ProgressRecord(10, "Out-Excel", "Done"));
            WriteVerbose("Done");

            WriteObject(new FileInfo(parPath));
        }
Ejemplo n.º 8
0
        protected override void ProcessRecord()
        {
            if (parObject == null)
            {
                WriteVerbose("A null object found in the pipe, ignoring it.");
            }
            else
            {
                if (parObject.GetType() != lastObject)
                {
                    WriteVerbose("New object type detected");
                    WriteProgress(new ProgressRecord(10, "Out-Excel", "Creating new table.."));

                    lastObject = parObject.GetType();

                    int columns = 0;
                    foreach (PSMemberInfo property in parObject.Properties)
                    {
                        columns++;
                    }

                    WriteVerbose(string.Format("Adding header (#{0})", headerCount++));
                    WriteProgress(new ProgressRecord(10, "Out-Excel", string.Format("Adding header (#{0})", headerCount)));

                    if (isFirstObject)
                    {
                        currentSheet  = msExcel.Property("Worksheets").Get().Index(1).Get();
                        isFirstObject = false;
                    }
                    else
                    {
                        currentSheet = msExcel.Property("Worksheets").Get().Method("Add").Invoke();
                    }
                    rowCount = 2;

                    int headerCounter = 1;
                    foreach (PSMemberInfo property in parObject.Properties)
                    {
                        currentSheet.Property("Cells").Get().Index(1, headerCounter).Get().Property("Value").Set(property.Name);
                        headerCounter++;
                    }
                }

                WriteVerbose(string.Format("Adding object row (#{0})", totalCount++));
                WriteProgress(new ProgressRecord(10, "Out-Excel", string.Format("Adding row (#{0})", totalCount)));

                int rowCounter = 1;
                foreach (PSMemberInfo property in parObject.Properties)
                {
                    try
                    {
                        currentSheet.Property("Cells").Get().Index(rowCount, rowCounter).Get().Property("Value").Set(property.Value.ToString());
                    }
                    catch
                    {
                    }
                    rowCounter++;
                }
                rowCount++;
            }
        }
Ejemplo n.º 9
0
        protected override void BeginProcessing()
        {
            base.BeginProcessing();

            if (!(GetOfficeVersion.GetVersion("Excel")).IsInstalled)
            {
                ThrowTerminatingError(new ErrorRecord(new FileNotFoundException("Excel is not installed use Import-OExcelWorkbook instead."), "1", ErrorCategory.InvalidOperation, null));
            }

            msExcel = BindingFactory.CreateAutomationBinding("Excel.Application");

            currentCulture = Thread.CurrentThread.CurrentCulture;
            int langSettings = msExcel.Property("LanguageSettings").Get().Property("LanguageID").PropertyParam(2).Get <int>();

            CultureInfo newCulture = new CultureInfo(langSettings);

            WriteVerbose(string.Format("Changing culture ({0}->{1})", currentCulture.DisplayName, newCulture.DisplayName));
            Thread.CurrentThread.CurrentCulture = newCulture;

            if (parFile.StartsWith(@".\"))
            {
                parFile = System.IO.Path.Combine(this.CurrentProviderLocation("FileSystem").ProviderPath, parFile.Substring(2));
            }

            parFile = System.IO.Path.GetFullPath(parFile);

            if (!System.IO.File.Exists(parFile))
            {
                msExcel.Method("Quit").Invoke();
                ThrowTerminatingError(new ErrorRecord(new FileNotFoundException(string.Format("The source file does not exist", parFile)), "200", ErrorCategory.OpenError, parFile));
            }

            IDynamic nativeWorkbook = null;

            try
            {
                nativeWorkbook = msExcel.Property("Workbooks").Get().Method("Open").AddParameter(parFile).AddMissingParameters(14).Invoke();
                FileInfo fileInfo = new FileInfo(parFile);

                Workbook workbook = new Workbook();
                workbook.Filepath         = parFile;
                workbook.FileIsReadOnly   = fileInfo.IsReadOnly;
                workbook.FileLastModified = fileInfo.LastWriteTime;
                workbook.FileCreated      = fileInfo.CreationTime;

                workbook.Author   = nativeWorkbook.Property("Author").Get <string>();
                workbook.Title    = nativeWorkbook.Property("Title").Get <string>();
                workbook.Comments = nativeWorkbook.Property("Comments").Get <string>();
                workbook.Keywords = nativeWorkbook.Property("Keywords").Get <string>();

                workbook.Worksheets = GetWorksheets(nativeWorkbook);

                WriteObject(workbook);
            }
            catch (Exception ex)
            {
                WriteError(new ErrorRecord(new InvalidDataException(string.Format("Conversion failed: {0}", ex.Message)), "201", ErrorCategory.ParserError, parFile));
            }
            finally
            {
                if (nativeWorkbook != null)
                {
                    nativeWorkbook.Method("Close").AddParameter(0).Invoke();
                }
                msExcel.Method("Quit").Invoke();
            }
        }
Ejemplo n.º 10
0
        protected override void EndProcessing()
        {
            base.EndProcessing();

            WriteProgress(new ProgressRecord(10, "Out-Word", "Creating footers.."));
            if (parFooter != string.Empty)
            {
                WriteVerbose("Adding footer");
                IDynamic newPara = wordDoc.Property("Paragraphs").Get().Method("Add").Invoke();
                try
                {
                    newPara.Property("Style").Set(wordFooterStyle);
                }
                catch
                {
                    WriteWarning(string.Format("The style specified for document footer ('{0}') was not found", wordFooterStyle));
                }
                newPara.Property("Range").Get().Property("Text").Set("");
                newPara.Property("Range").Get().Method("InsertParagraphAfter").Invoke();
                currentRange = newPara.Property("Range").Get();
                try
                {
                    newPara.Property("Style").Set(wordFooterStyle);
                }
                catch
                {
                    WriteWarning(string.Format("The style specified for document footer ('{0}') was not found", wordFooterStyle));
                }

                newPara.Property("Range").Get().Property("Text").Set(parFooter);
                newPara.Property("Range").Get().Method("InsertParagraphAfter").Invoke();
                currentRange = newPara.Property("Range").Get();
            }

            WriteVerbose("Setting table styles");
            WriteProgress(new ProgressRecord(10, "Out-Word", "Formatting tables.."));

            IDynamic tables     = wordDoc.Property("Tables").Get();
            int      tableCount = tables.Property("Count").Get <int>();

            for (int i = 1; (i - 1) < tableCount; i++)
            {
                IDynamic table = tables.Index(i).Get();
                try
                {
                    table.Property("Style").Set(wordTableStyle);
                }
                catch
                {
                    WriteWarning(string.Format("The style specified for tables ('{0}') was not found", wordTableStyle));
                }

                table.Property("Columns").Get().Method("AutoFit").Invoke();
            }



            WriteProgress(new ProgressRecord(10, "Out-Word", "Saving document.."));
            int format = 0;

            switch (parFormat.ToLower())
            {
            case "word": format = 12; break;

            case "word97": format = 0; break;

            case "pdf": format = 17; break;

            case "xps": format = 18; break;

            case "odf": format = 23; break;

            case "rtf": format = 6; break;
            }

            WriteVerbose(string.Format("Saving document in {0}", parFormat));

            try
            {
                wordDoc.Method("SaveAs").AddRefParameter(parPath).AddRefParameter(format).Invoke();
            }
            catch (Exception ex)
            {
                WriteVerbose("Save failed, see error log for details");

                if (parNoExit)
                {
                    WriteVerbose("-NoExit specified, making word visible if not already");
                    msWord.Property("Visible").Set(true);
                }
                else
                {
                    WriteVerbose("-NoExit not specified, quitting word");
                    wordDoc.Method("Close").AddParameter(0).Invoke();
                    msWord.Method("Quit").AddParameter(0).Invoke();
                }


                ThrowTerminatingError(new ErrorRecord(ex, "300", ErrorCategory.FromStdErr, parPath));
            }

            if (parNoExit)
            {
                WriteVerbose("-NoExit specified, making word visible if not already");
                msWord.Property("Visible").Set(true);
            }
            else
            {
                WriteVerbose("-NoExit not specified, quitting word");
                wordDoc.Method("Close").AddParameter(0).Invoke();
                msWord.Method("Quit").AddParameter(0).Invoke();
            }

            WriteProgress(new ProgressRecord(10, "Out-Word", "Done"));
            WriteVerbose("Done");

            WriteObject(new FileInfo(parPath));
        }
Ejemplo n.º 11
0
        protected override void ProcessRecord()
        {
            base.ProcessRecord();

            if (parObject == null)
            {
                WriteVerbose("A null object found in the pipe, ignoring it.");
            }
            else
            {
                if (parObject.GetType() != lastObject)
                {
                    WriteVerbose("New object type detected");
                    WriteProgress(new ProgressRecord(10, "Out-Word", "Creating new table.."));

                    lastObject = parObject.GetType();

                    int columns = 0;
                    foreach (PSMemberInfo property in parObject.Properties)
                    {
                        columns++;
                    }

                    if (columns > 63)
                    {
                        wordDoc.Method("Close").AddParameter(0).Invoke();
                        msWord.Method("Quit").AddParameter(0).Invoke();
                        WriteVerbose("To many properties detected on the object");
                        ThrowTerminatingError(new ErrorRecord(new IndexOutOfRangeException("One or more objects exceeds 63 properties which is maximum in Word"), "200", ErrorCategory.InvalidData, parObject));
                    }
                    else
                    {
                        WriteVerbose(string.Format("Adding header (#{0})", headerCount++));
                        WriteProgress(new ProgressRecord(10, "Out-Word", string.Format("Adding header (#{0})", headerCount)));

                        currentTable = wordDoc.Property("Tables").Get().Method("Add").AddParameter(currentRange.InstanceObject).AddParameter(1).AddParameter(columns).Invoke();
                        currentRange = currentTable.Property("Range").Get();

                        int headerCounter = 1;
                        foreach (PSMemberInfo property in parObject.Properties)
                        {
                            IDynamic cell = currentTable.Method("Cell").AddParameter(1).AddParameter(headerCounter).Invoke().Property("Range").Get();
                            try
                            {
                                cell.Property("Style").Set(wordTableHeaderStyle);
                            }
                            catch
                            {
                                WriteWarning(string.Format("The style specified for table header rows ('{0}') was not found", wordTableHeaderStyle));
                            }
                            cell.Method("InsertAfter").AddParameter(property.Name).Invoke();
                            headerCounter++;
                        }
                    }
                }

                WriteVerbose(string.Format("Adding object row (#{0})", rowCount++));
                WriteProgress(new ProgressRecord(10, "Out-Word", string.Format("Adding row (#{0})", rowCount)));
                currentTable.Property("Rows").Get().Method("Add").Invoke();

                int colCounter = 1;
                foreach (PSMemberInfo property in parObject.Properties)
                {
                    IDynamic cell = currentTable.Method("Cell").AddParameter(rowCount + 1).AddParameter(colCounter).Invoke().Property("Range").Get();

                    try
                    {
                        cell.Property("Style").Set(wordTableRowStyle);
                    }
                    catch
                    {
                        WriteWarning(string.Format("The style specified for table rows ('{0}') was not found", wordTableRowStyle));
                    }

                    try
                    {
                        cell.Method("InsertAfter").AddParameter(property.Value.ToString()).Invoke();
                    }
                    catch
                    {
                        //this.WriteError(new ErrorRecord(new NullReferenceException(string.Format("Property ({0}) contains null value",property.Name)),"900",ErrorCategory.InvalidData,parObject));
                    }
                    colCounter++;
                }
            }
        }
Ejemplo n.º 12
0
        protected override void BeginProcessing()
        {
            base.BeginProcessing();

            if (!(GetOfficeVersion.GetVersion("Word")).IsInstalled)
            {
                ThrowTerminatingError(new ErrorRecord(new FileNotFoundException("Excel is not installed use Out-OWord instead."), "1", ErrorCategory.InvalidOperation, null));
            }


            if (parPath.StartsWith(@".\"))
            {
                parPath = System.IO.Path.Combine(this.CurrentProviderLocation("FileSystem").ProviderPath, parPath.Substring(2));
            }

            parPath = System.IO.Path.GetFullPath(parPath);

            WriteVerbose(string.Format("Checking for existance of file {0}", parPath));
            WriteProgress(new ProgressRecord(10, "Out-Word", "Initializing.."));

            if (File.Exists(parPath))
            {
                if (!parOverwrite)
                {
                    WriteVerbose("File exists and -Overwrite have not been specified");
                    ThrowTerminatingError(new ErrorRecord(new System.IO.IOException("The file already exists and -Overwrite have not been specified"), "100", ErrorCategory.ResourceExists, parPath.ToString()));
                }
                else
                {
                    WriteVerbose("File exists and -Override have been specified, will delete file");
                    File.Delete(Path);
                }
            }

            WriteVerbose("Starting Microsoft Word");
            msWord = BindingFactory.CreateAutomationBinding("Word.Application");

            if (parDisplay)
            {
                WriteVerbose("Display have been set, making application visible");
                msWord.Property("Visible").Set(true);
            }

            WriteProgress(new ProgressRecord(10, "Out-Word", "Creating document.."));
            try
            {
                WriteVerbose("Creating new document");
                wordDoc = msWord.Property("Documents").Get().Method("Add").AddParameter(Template).AddParameter(false).AddParameter(0).AddParameter(true).Invoke();
            }
            catch
            {
                msWord.Method("Quit").AddParameter(0).Invoke();
                WriteVerbose("Document creation failed (error in template most likely)");
                ThrowTerminatingError(new ErrorRecord(new System.IO.IOException("Template not valid/found"), "101", ErrorCategory.ResourceUnavailable, parTemplate));
            }

            //WriteVerbose("Activating document");
            //msWord.Method("Activate").Invoke();


            if (wordTitleStyle == string.Empty)
            {
                wordTitleStyle = wordDoc.Property("Styles").Get().Index(-63).Get().Property("NameLocal").Get <string>();
                //wordTitleStyle = wordDoc.Styles[WdBuiltinStyle.wdStyleTitle].NameLocal;
                WriteVerbose(string.Format("Default localized TITLE style is: {0}", wordTitleStyle));
            }
            if (wordHeaderStyle == string.Empty)
            {
                //wordHeaderStyle = wordDoc.Styles[WdBuiltinStyle.wdStyleNormal].NameLocal;
                wordHeaderStyle = wordDoc.Property("Styles").Get().Index(-1).Get().Property("NameLocal").Get <string>();
                WriteVerbose(string.Format("Default localized HEADER style is: {0}", wordHeaderStyle));
            }
            if (wordFooterStyle == string.Empty)
            {
                //wordFooterStyle = wordDoc.Styles[WdBuiltinStyle.wdStyleQuote].NameLocal;
                wordFooterStyle = wordDoc.Property("Styles").Get().Index(-181).Get().Property("NameLocal").Get <string>();
                WriteVerbose(string.Format("Default localized FOOTER style is: {0}", wordFooterStyle));
            }
            if (wordTableStyle == string.Empty)
            {
                //wordTableStyle = wordDoc.Styles[WdBuiltinStyle.wdStyleTableMediumList1Accent1].NameLocal;
                wordTableStyle = wordDoc.Property("Styles").Get().Index(-178).Get().Property("NameLocal").Get <string>();
                WriteVerbose(string.Format("Default localized TABLE style is: {0}", wordTableStyle));
            }
            if (wordTableHeaderStyle == string.Empty)
            {
                //wordTableHeaderStyle = wordDoc.Styles[WdBuiltinStyle.wdStyleIntenseEmphasis].NameLocal;
                wordTableHeaderStyle = wordDoc.Property("Styles").Get().Index(-262).Get().Property("NameLocal").Get <string>();
                WriteVerbose(string.Format("Default localized TABLEHEADER style is: {0}", wordTableHeaderStyle));
            }
            if (wordTableRowStyle == string.Empty)
            {
                //wordTableRowStyle = wordDoc.Styles[WdBuiltinStyle.wdStyleEmphasis].NameLocal;
                wordTableRowStyle = wordDoc.Property("Styles").Get().Index(-89).Get().Property("NameLocal").Get <string>();
                WriteVerbose(string.Format("Default localized TABLEROW style is: {0}", wordTableRowStyle));
            }

            currentRange = msWord.Property("Selection").Get().Property("Range").Get();

            WriteProgress(new ProgressRecord(10, "Out-Word", "Creating title and headers.."));

            if (parTitle != String.Empty)
            {
                WriteVerbose("Adding title");
                IDynamic newPara = wordDoc.Property("Paragraphs").Get().Method("Add").Invoke();
                try
                {
                    newPara.Property("Style").Set(wordTitleStyle);
                }
                catch
                {
                    WriteWarning(string.Format("The style specified for document title ('{0}') was not found", wordTitleStyle));
                }
                newPara.Property("Range").Get().Property("Text").Set(parTitle);
                newPara.Property("Range").Get().Method("InsertParagraphAfter").Invoke();
                currentRange = newPara.Property("Range").Get();
            }

            if (parHeader != String.Empty)
            {
                WriteVerbose("Adding header");
                IDynamic newPara = wordDoc.Property("Paragraphs").Get().Method("Add").Invoke();
                try
                {
                    newPara.Property("Style").Set(wordHeaderStyle);
                }
                catch
                {
                    WriteWarning(string.Format("The style specified for document header ('{0}') was not found", wordHeaderStyle));
                }
                newPara.Property("Range").Get().Property("Text").Set(parHeader);
                newPara.Property("Range").Get().Method("InsertParagraphAfter").Invoke();
                currentRange = newPara.Property("Range").Get();
            }
        }