I'm trying to execute a PowerShell script that opens an Excel file and does a SaveAs with it. the problem is that it works when I put the full path for the file, but I want it to be directed to the working folder, that way if I take the script and files to other location I don't have to modify the script for each environment.
$excel = New-Object -ComObject Excel.Application
$excel.Visible = $true
$excel.DisplayAlerts = $false
$wb = $excel.Workbooks.Open("E:\TEMP\TEMPLATE4WEEKS.xlsx")#Opening like this works
$wb = $excel.Workbooks.Open(ThisWorkbook.Path & "\TEMPLATE4WEEKS.xlsx") #this is not working
$wb.SaveAs(ThisWorkbook.Path & "\TEMPLATE4WEEKSprotected.xlsx",[Type]::Missing,"password") #this is not working
$excel.Quit()
I was trying to concatenate current folder so it will work if I say move the entire folder to another path.
Right now the folder that contains the PS1 script is the same that contains the TEMPLATE4WEEKS.xlsx file. I want all to operate inside the same folder.
Changed as per Ansgar's response:
$excel = New-Object -ComObject Excel.Application
$excel.Visible = $true
$excel.DisplayAlerts = $false
$file = Join-Path $excel.ThisWorkbook.Path "TEMPLATE4WEEKS.xlsx"
$wb = $excel.Workbooks.Open($file)
$wb.SaveAs($file,[Type]::Missing,"password")
$excel.Quit()
I'm getting this error now:
Join-Path : Cannot bind argument to parameter 'Path' because it is null.
At C:\Users\AGUIRRG2\Desktop\Newfolder\PasswordProtect4WEEKSCopy.ps1:4 char:19
+ $file = Join-Path $excel.ThisWorkbook.Path "TEMPLATE4WEEKS.xlsx"
+ ~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidData: (:) [Join-Path], ParameterBindingValidationException
+ FullyQualifiedErrorId : ParameterArgumentValidationErrorNullNotAllowed,Microsoft.PowerShell.Commands.JoinPathCommand
Sorry, we couldn't find . Is it possible it was moved, renamed or deleted?
At C:\Users\AGUIRRG2\Desktop\Newfolder\PasswordProtect4WEEKSCopy.ps1:5 char:1
+ $wb = $excel.Workbooks.Open($file)
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : OperationStopped: (:) [], COMException
+ FullyQualifiedErrorId : System.Runtime.InteropServices.COMException
You cannot call a method on a null-valued expression.
At C:\Users\AGUIRRG2\Desktop\Newfolder\PasswordProtect4WEEKSCopy.ps1:6 char:1
+ $wb.SaveAs($file,[Type]::Missing,"password")
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [], RuntimeException
+ FullyQualifiedErrorId : InvokeMethodOnNull
& in PowerShell is not a concatenation operator. Plus, you don't want to build paths via string concatenation in the first place. You also cannot use the object ThisWorkbook directly in PowerShell (that only works in VBA, and it's the location of the current macro, so it won't work here at all because you're not running a macro).
Change this:
$wb = $excel.Workbooks.Open(ThisWorkbook.Path & "\TEMPLATE4WEEKSxlsx")
into this:
$wb = $excel.Workbooks.Open("${PSScriptRoot}\TEMPLATE4WEEKS.xlsx")
Note: The automatic variable $PSScriptRoot was introduced with PowerShell v3 and doesn't exist in earlier versions. If you're running an older version you need to define it yourself, e.g. like this:
$PSScriptRoot = Split-Path $MyInvocation.MyCommand.Path -Parent
To use a relative path instead of a physical one, use the variable $pwd. It's your current working directory:
$excel = New-Object -ComObject Excel.Application
$excel.Visible = $true
$excel.DisplayAlerts = $false
$LoadPath = Join-Path -Path $pwd -ChildPath "TEMPLATE4WEEKS.xlsx" #$pwd is your current working dir
$SavePath = Join-Path -Path $pwd -ChildPath "TEMPLATE4WEEKSprotected.xlsx"
$wb = $excel.Workbooks.Open($LoadPath)
$wb.SaveAs($SavePath,[Type]::Missing,"password")
$excel.Quit()
Related
I am trying to create a shortcut on desktop using a Powershell Script. However, I got an error code when trying to run the code below.
$new_object = New-Object -ComObject WScript.Shell
$destination = $new_object.SpecialFolders.Item("AllUsersDesktop")
$source_path = Join-Path -Path $destination -ChildPath "\\Test Intranet.url"
$source = $new_object.CreateShortcut($source_path)
$source.TargetPath = "https://sharepoint.com/"
$source.IconLocation="C:\Users\Public\Pictures\ShortcutIcon.ico"
$source.Save()
Any help will be appreciated.
Thanks.
You didn't show this, but the error message you received is probably this one:
Exception setting "IconLocation": "The property 'IconLocation' cannot be found on this object. Verify that the property exists and can be set."
At line:8 char:1
+ $source.IconLocation="C:\Users\Public\Pictures\ShortcutIcon.ico"
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [], SetValueInvocationException
+ FullyQualifiedErrorId : ExceptionWhenSetting
That is because an Internet shortcut has different properties than a 'normal' (.lnk) shortcut to a file of folder.
Another thing is that you have prefixed the shortcut filename with a double backslash and by doing so, you will get a wrong path: C:\Users\Public\Desktop\\Test Intranet.url
In below code, I have changed some of the variable names to be more self-descripting (at least, I like to think so..)
$shell = New-Object -ComObject WScript.Shell
$destination = $shell.SpecialFolders.Item("AllUsersDesktop")
$shortcutPath = Join-Path -Path $destination -ChildPath 'Test Intranet.url'
# create the shortcut
$shortcut = $shell.CreateShortcut($shortcutPath)
# for a .url shortcut only set the TargetPath
$shortcut.TargetPath = 'https://sharepoint.com/'
$shortcut.Save()
# next update the shortcut with a path to the icon file and the index of that icon
# you can do that because a .url file is just a text file in INI format
Add-Content -Path $shortcutPath -Value "IconFile=C:\Users\Public\Pictures\ShortcutIcon.ico"
Add-Content -Path $shortcutPath -Value "IconIndex=0"
# clean up the COM objects
[System.Runtime.Interopservices.Marshal]::ReleaseComObject($shortcut) | Out-Null
[System.Runtime.Interopservices.Marshal]::ReleaseComObject($shell) | Out-Null
[System.GC]::Collect()
[System.GC]::WaitForPendingFinalizers()
When opened in notepad, your shortcut file looks like this:
[{000214A0-0000-0000-C000-000000000046}]
Prop3=19,11
[InternetShortcut]
IDList=
URL=https://sharepoint.com/
IconFile=C:\Users\Public\Pictures\ShortcutIcon.ico
IconIndex=0
I am trying to run a powershell script inside a SQL Agent job. I keep getting the error: Import-Clixml : The system cannot find the file specified. At \Data\Powershell\Collibra\Dev\test.ps1:95 char:21 + ... redential = Import-Clixml -Path Filesystem::\Data\Powershell... + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : NotSpecified: (:) [Import-Clixml], Cryptographic Exception + FullyQualifiedErrorId : System.Security.Cryptography.CryptographicExcept ion,Microsoft.PowerShell.Commands.ImportClixmlCommand
$Credential = Import-Clixml -Path
Filesystem::\\energy\data\apps\BISharedServices\Powershell\Collibra\Dev\credentials.xml
$username = $Credential.GetNetworkCredential().UserName
$password = $Credential.GetNetworkCredential().Password
$credPair = "$($username):$($password)"
$encodedCredentials = [System.Convert]::ToBase64String([System.Text.Encoding]::ASCII.GetBytes($credPair))
$H = #{ Authorization = "Basic $encodedCredentials" }
I have tried mapping a new drive and doing a set-location. Same results. This is driving me nuts!
Thanks for the help.
In basic Powershell without SSIS at least, it's only one slash at the beginning:
Import-Clixml -Path FileSystem::\path\to\file.txt
I want to copy a file from remoter server(which is on another domain) to local
I am new to powershell and got this code from tech forum, however its not working
$Source = "\\xx.xxx.xxx.xx\Users\test\test_1.txt"
$Dest = "D:\Demo\"
$Username = "domainname\username"
$Password = "xxx"
$WebClient = New-Object System.Net.WebClient
$WebClient.Credentials = New-Object System.Net.NetworkCredential($Username, $Password)
$WebClient.DownloadFile($Source, $Dest)
getting below error
Exception calling "DownloadFile" with "2" argument(s): "An exception occurred during a WebClient request."
At line:9 char:1
+ $WebClient.DownloadFile($Source, $Dest)
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : WebException
Pretty sure your problem is you need to specify the full file path. Not just a target folder. Looking at WebClient.DownloadFile we can see
fileName String
The name of the local file that is to receive the data.
So perhaps all you need to do is...
$Source = "\\xx.xxx.xxx.xx\Users\test\test_1.txt"
$Dest = [io.path]::Combine("D:\Demo\", Split-Path $source -Leaf)
It was probably denied access to write to a folder.
I am using the current code to download a file from a sharepoint...
$webClient = New-Object System.Net.WebClient
$webClient.UseDefaultCredentials = $true
$webClient.DownloadFile($sharepointPathFile, $localPathFile) | Out-Null
But what if I wanted to check if the file is already at the local location and the size matches or is different? How would I do this using powershell?
Update
This was the closest I could get...
$url = $sharepointPathFile
$clnt = [System.Net.WebRequest]::Create($url)
$resp = $clnt.GetResponse()
$fileSize = $resp.ContentLength
Write-Host $fileSize
But I am getting the following error:
Exception calling "GetResponse" with "0" argument(s): "The remote server returned an error: (401) Unauthorized."
At C:\Scripts\Tests\testCheckUpdatedSearchFiles.ps1:345 char:2
+ $resp = $clnt.GetResponse()
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : WebException
I have full read and download rights, so is there something else not going right here?
I'm not sure if the "GetResponse" method will return exactly what you're looking for. And depending on the ContentLength, you may want to explicitly define your types. I would try something like this:
$webClient = New-Object System.Net.WebClient
$webClient.OpenRead("path/to/file")
[Int64]$fileSize = $webClient.ResponseHeaders["Content-Length"]
Write-Host $fileSize
I'm fairly new to Powershell and found the following script on the web: (I've modified it for my project)
# Acquire a list of DOC files in a folder
$Word = New-Object -ComObject word.application
$formats = "Microsoft.Office.Interop.Word.WdSaveFormat" -as [type]
$Word.visible = $false
$fileTypes = "*.docx","*doc"
$complyDocPath = "i:\2014\COMPLY\DOC\"
$complyPDFPath = "i:\2014\COMPLY\PDF\"
$Files=GET-CHILDITEM $complyDocPath -include $fileTypes
Foreach ($File in $Files) {
# open a Word document, filename from the directory
#$Doc=$Word.Documents.Open($File.fullname)
$Doc=$Word.Documents.Open($File)
# Swap out .DOCX/.DOC with 5.PDF in the Filename
$fileName = [system.io.path]::GetFileNameWithoutExtension($File)
$destPath = Join-Path -path $complyPDFPath -childpath ($fileName +"5.PDF")
Add-Type -AssemblyName "Microsoft.Office.Interop.Word"
"Converting $File to pdf ... $destPath"
# Save this File as a PDF in Word 2010/2013
$Doc.SaveAs($destPath, $formats::wdFormatPDF)
$Doc.Close($false)
}
$Word.Quit()
I get the following errors:
Argument: '2' should be a System.Management.Automation.PSReference. Use [ref].
At line:25 char:5
+ $Doc.SaveAs($destPath, $formats::wdFormatPDF)
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [], MethodException
+ FullyQualifiedErrorId : NonRefArgumentToRefParameterMsg
Argument: '1' should be a System.Management.Automation.PSReference. Use [ref].
At line:26 char:5
+ $Doc.Close($false)
+ ~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [], MethodException
+ FullyQualifiedErrorId : NonRefArgumentToRefParameterMsg
Exception calling "Open" with "1" argument(s): "Type mismatch. (Exception from HRESULT: 0x80020005 (DISP_E_TYPEMISMATCH))"
At line:14 char:5
+ $Doc=$Word.Documents.Open($File)
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : ComMethodTargetInvocation
For the 1st error, I changed my code to include [ref], like these variations (but to no success):
$Doc.SaveAs([ref] $destPath, $formats::wdFormatPDF)
$Doc.SaveAs($destPath, [ref] $formats::wdFormatPDF)
$Doc.SaveAs([ref] $destPath, [ref] 17)
[Update] FYI: Files in the source directory are named like this:
I:\2014\Comply\DOC\IBM=US.DOC
I:\2014\Comply\DOC\CTC.A=CA.DOC
How can I generate a PDF from Word doc?
The above code works if the source & destination paths were the same. Since I didn't get any responses, I've decided to go the C#.Net route and implemented the code that I found in:
How do I convert Word files to PDF programmatically?