I have a scheduled task set up (in a separate program) which will email a .xlsx file. I have a rule set up that will save the email to an Outlook folder called 04_CFW REPORT
I need Outlook to open the file with Excel and save as .csv to a network drive.
This will happen at night, when i am away from the computer
The closest thing i've found is a function here:
http://www.devhut.net/2012/05/14/ms-access-vba-convert-excel-xls-to-csv/
but i have no idea how to put this function to use in a sub.
Any help would be greatly appreciated.
This might be a place to start. Taken from here
Then you can research into creating a powershell job to run once daily and loop until the specified email subject is found.
Another point to consider, if you have permission Powershell can perform the SQL query and output a CSV which can be converted into an XLSX.
Add-type -assembly "Microsoft.Office.Interop.Outlook" | out-null
$olFolders = "Microsoft.Office.Interop.Outlook.olDefaultFolders" -as [type]
$outlook = new-object -comobject outlook.application
$namespace = $outlook.GetNameSpace("MAPI")
$folder = $namespace.getDefaultFolder($olFolders::olFolderInBox)
Then I can filter on Inbox items using, for example any unread items.
$folder.items | where {$_.UnRead -eq $true}
***EDIT, getting PowerShell to close Excel's comobject correctly. It's a matter of properly releasing the COM object. First (assuming this isn't done) we Save the workbook and Quit Excel.
Next we release COM objects from smallest (here the variable holding a range of cells) to largest (the Excel ComObject variable) in a loop should more than one iteration be required. Now the last two lines I've noticed are not really required, but in testing scripts it's nice to do but run Garbage Collection. Watch task manager to confirm it's operation.
$xlsObj.ActiveWorkbook.SaveAs($xlsFile) | Out-Null
$xlsObj.Quit()
While ([System.Runtime.Interopservices.Marshal]::ReleaseComObject($xlsRng)) {'cleanup xlsRng'}
While ([System.Runtime.Interopservices.Marshal]::ReleaseComObject($xlsSh)) {'cleanup xlsSh'}
While ([System.Runtime.Interopservices.Marshal]::ReleaseComObject($xlsWb)) {'cleanup xlsWb'}
While ([System.Runtime.Interopservices.Marshal]::ReleaseComObject($xlsObj)) {'cleanup xlsObj'}
[gc]::collect() | Out-Null
[gc]::WaitForPendingFinalizers() | Out-Null
Related
I'd like to make a Microsoft Word document be set with a password for opening the document. When I try to run the following code in Powershell, the script will hang once I enter the desired password.
This script will be run in Kaseya to help automate protecting Word documents. I've tried both modifying the Document.Password property and using the Document.Protect method and they both will hang the script.
$path = Read-Host("Specify path to word document")
Write-Host "Creating Word application object..."
$wordAppObj = New-Object -ComObject Word.Application
Write-Host "Creating Word document object..."
$wordDocObj = $wordAppObj.Documents.Open($path)
# Write-Host "Activating Word document object..."
# $wordDocObj.Activate
Write-Host "Setting password..."
$securePass = Read-Host("Set password as") -AsSecureString
$password = ConvertFrom-SecureString $securePass
# $wordDocObj.Protect(3, $true, $password)
$wordDocObj.Password = $password
Write-Host "Saving Word document object..."
$wordDocObj.Save
Write-Host "Closing the Word document..."
$wordDocObj.Close
Write-Host "Closing Word..."
$wordAppObj.Application.Quit()
I expect the script to run through and protect the file, but the script will hang and an instance of Microsoft Word will be running in the background taking up about 6-9% of the CPU. Nothing will happen to the file or in the script. There are no error messages that pop up.
UPDATE: As suggested, I added $wordAppObj.Visible = $true to the script to see if there were any pop-ups that happened during the execution of the script. Unfortunately, I didn't see any. I believe the script may be hanging when it prompts the user to re-enter the password. This happens when I use Word to encrypt a document with a password. Is there any way to fill this field in from Powershell?
I have developed a program in C# with the Microsoft Interop reference for Word. This program worked for me. At this point, I believe that this kind of thing cannot be done from Powershell and I would advise that anyone trying to do this seek another way to get this done. I think Powershell simply doesn't support modifying the password field of a document.
This may be a combination of two questions, but I'm open to multiple solutions.
I open an Excel file with Powershell using the following code
$step=$args[0]
$excel = New-Object -ComObject Excel.Application
$excel.Visible = $True
$excel.WindowState = 'xlMaximized'
$workBook = $excel.Workbooks.Open($step)
When this Excel file opens, it automatically runs several macros intended to download a second Excel file. I need to close the first Excel file, and it looks like there's a macro to do it that I could call, but Powershell never actually returns to the prompt (PS C:\>) after calling Workbooks.Open(), I'm assuming because the UserForm that's generated by the macros is still open (It just contains a close button at this point, which triggers the exit macro).
So, is there either any way I can get Powershell to return to the prompt to run the exit macro, or is there another way I can close the first Excel file without closing the second one?
Because the second file is generated by macros in the first, it will always be in the same process as the first, so using Stop-Process will close both windows.
Try disabling alerts to suppress the popup:
$step=$args[0]
$excel = New-Object -ComObject Excel.Application
$excel.Visible = $True
$excel.WindowState = 'xlMaximized'
$excel.DisplayAlerts = $false
$workBook = $excel.Workbooks.Open($step)
So I am using this code in excel to read environment parameters on startup:
Dim ExcelArgs As String
Dim arg As String
ExcelArgs = Environ("ExcelArgs")
MsgBox ExcelArgs
If InStr(UCase(ExcelArgs), "CREO") >= 0 Then
Application.DisplayAlerts = False
If Len(ExcelArgs) > Len("CREO") Then
arg = Split(ExcelArgs, ",")(1)
Call Creo.addNewPartToPartslist(arg)
End If
Application.DisplayAlerts = True
End If
and this line in my batch script:
echo "Launch excel"
Set "ExcelArgs=CREO,DXFWITHOUTDRW
"C:\Program Files (x86)\Microsoft Office\OFFICE16\Excel.exe" /r "%APPDATA%\Microsoft\Excel\XLSTART\PERSONAL.XLSB"
exit 0
The problem is that if i run the batch file once, keep excel open change the excelargs to CREO,wqhatever in batch file and rerun batch file the excelargs, dos not get updated!!!
So my theory is that excel either caches out the environment variable or that if it is being used by one instance the batch script can not set it
link with some info about passing arguments to excel:
https://superuser.com/questions/640359/bat-file-to-open-excel-with-parameters-spaces
Usually excel sees if there is a previous instance running and let this instance handle the file opening.
Is this important? Yes, in your case both requests to open the file are handled by the same excel process.
How does it make a difference? Environment variables are not shared. Each process has it own environment block that is initialized when the process is created (can be a customized block or a copy of the environment of the parent process) and once the environment is created for a process, only this process can change its environment.
In your case, when you start excel the new process gets a copy of the environment block of the cmd process. Later, when you change the cmd environment, the already running excel instance sees no changes in environment and, as the new request to open excel is converted to a request to the previous process, there is not a new process with a new copy of the cmd environment with the changes.
The only way I see to make it work is to force excel to start a new process (that will inherit the changes in the cmd instance) instead of reusing the previous one.
But this depends on the excel version. As far as I know, the 2013 version includes an /x switch to force separate process usage. For previous versions, maybe this question, or this one could help you.
Excel is open
Then i start the batch script:
The it does not open it as read only by default, but prompt me instead, not a big issue but a bit annoying, and it also make it impossible to loop through to run the batch several times for different input parameters.
A bit unsure how I should post this, couldnt paste images in comments, and to edit the the original question, which was how to start excel with enviroment variable in new instance (/x did the trick), but now /r does not work, Should I post as new question and refer to this one or can I leave it as an answer?
I have several 20+ MB Excel files, and they need to be refreshed every week before business starts (Monday 8 AM).
These files contain one Data sheet, and data comes via external connection (ODC file), from an SQL Server view.
They also have one pivot sheet that also needs to be refreshed after the Data sheet is refreshed.
I am trying to find a solution (Windows PowerShell) to automatize the refreshing of Data and Pivot sheets without the need to touch the files.
"Refresh on opening" and other Excel options are not viable because it takes up to 20 minutes to refresh all the connections.
I also don't want to refresh ALL sheets because the file has custom coloring for charts and "Refresh" resets it to Excel default which cannot happen.
I tried this, but it doesn't seem to work with ODC connection? At least, it doesn't do anything.:
Windows PowerShell:
$ExcelApp = new-object -ComObject Excel.Application
$ExcelApp.Visible = $false
$ExcelApp.DisplayAlerts = $false
$Workbook = $ExcelApp.Workbooks.Open("c:\test\ref_test.xlsx", 3, $false, 5, $null, $null, $true)
Start-Sleep -s 30
$Workbook.RefreshAll()
$Workbook|Get-Member *Save*
$Workbook.Save()
$ExcelApp.Quit()
Any ideas?
Office version: 2010, on Windows 7
Possibly the answer on this question can help. The perl script is also available as a pre-compiled exe file.
I would approach this issue by using Excel VBA, and create your Excel file into a .xlsm.
Then update the file w/ Excel VBA commands and functions to refresh your odbc connection, and then save as a new file for distribution.
http://www.vbforums.com/showthread.php?675977-Auto-Open-Refresh-Pivots-Save-Close-Excel-files-using-VB
I've got a PowerShell script (running on Windows Server 2008 R2 Enterprise) that opens a Word doc in Word 2010, performs a SaveAs, and saves the doc as a PDF. In brief my code looks similar to the below:
$word = new-object -ComObject "word.application"
$word.Visible = $true
$doc = $word.documents.open("path\file.doc")
$doc.SaveAs("path\file.pdf", [ref] 17)
$doc.Close()
ps winword | kill
The above works fine, no problems at all and is converting the documents as expected.
My question is:
If I physically open Word myself and navigate to 'File > Save As' I get various options in the dialog when saving as PDF (eg. page range, optimisation etc)
How can I, if at all, access these options from within the PowerShell script when performing the same action?
Any advice would be appreciated. Maybe it's just not possible.
Thanks in advance
After much investigation I've found that option I needed was ExportAsFixedFormat().
The documentation can be found here:
http://msdn.microsoft.com/en-us/library/bb256835%28v=office.12%29.aspx
And you can see it in action within a PowerShell script here:
http://blog.coolorange.com/2012/04/20/export-word-to-pdf-using-powershell/