This is my powershell script:
cd '\\ac.gf\root\M151 Agie Charmilles SA\Qualità \QP\6-SPC - tools\2-Tools\IPC\Mechanics\OFFICE_2016'
$file = 'SPC_Analysis_v2.3 - 36 mesi_250_macchine.xlsm'
$x1 = New-Object -ComObject "Excel.Application"
$wb = $x1.workbooks.Open($file)
I need to open the file in the specified path, it exist but powershell doesn't find it.
Powershell reported that couldn't find it.
Listing the content of the folder I can see that it exist
Two possible solutions:
1.) Set the CurrentDirectory (this is not the same thing as the "location" in powershell)
[Environment]::CurrentDirectory = Get-Location
# or
[System.IO.Directory]::SetCurrentDirectory($pwd)
2.) Use the full path
$x1.workbooks.Open((Get-Item $file).FullName)
# or
$x1.workbooks.Open((Resolve-Path $file))
Related
Good Day everyone!
I am looking to make PowerShell script that creates a .lnk shortcut on the desktop. Which isn't too big a deal, but when I make one manually with chrome, 3 dots>more tools>create shortcut I get this option. Notice how it has the "Open in a new window" option. That is what I'm looking to accomplish. How would I go about making a .lnk file on the desktop that opens in a new window?
make an .lnk shortcut on desktop save it to desktop
.lnk file opens in new window
-preferably grabs an icon from the browser like when you make one with chrome so I don't have to point to one.
$Shell = New-Object -ComObject ("WScript.Shell")
$Favorite = $Shell.CreateShortcut($env:USERPROFILE + "\Desktop\Google.lnk")
$Favorite.TargetPath = "http://google.com";
$Favorite.IconLocation = "Picturelocation"
$Favorite.Arguments
$Favorite.Save()
Thanks for your time!
Notice the Icon and Open in a New window button
Use the following to create a shortcut file (.lnk) that launches Chrome with a given URL in a new window:
# Define the target URL
$url = 'https://google.com'
# Derive a friendly site name from it, to serve as the name
# of the shortcut file and the downloaded favicon.
# Adjust as needed, e.g. $friendlySiteName = 'Google'
$friendlySiteName = $url -replace '^https?://(?:www\.)?'
# Determine the full path of the shortcut file; adjust as needed.
# Note the required ".lnk" extension
$shortcutPath = "$HOME\Desktop\$friendlySiteName.lnk"
# Determine the full path of the chrome.exe executable, via the registry.
# Note: This is only necessary because chrome.exe is *not* in one
# of the directories listed in $env:PATH.
$chromeExePath = Get-ItemPropertyValue -LiteralPath 'HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\App Paths\chrome.exe' '(default)'
# Download the favicon:
# Create a designated local directory for storing favicons...
$targetDir = New-Item -Type Directory -Force "$HOME\favicons"
# ... and download the target site's favicon into it.
$favIconPath = Join-Path $targetDir.FullName ($friendlySiteName + '.ico')
& {
$ProgressPreference = 'SilentlyContinue'
Invoke-WebRequest -OutFile $favIconPath "$url/favicon.ico"
}
# Create the shortcut file, set its properties, and save it.
$shell = New-Object -ComObject WScript.Shell
$favorite = $shell.CreateShortcut($shortcutPath)
# Tell the shortcut to launch Chrome...
$favorite.TargetPath = $chromeExePath
# ... with the following arguments; -new-window ensures that the
# specified URL is opened in a new window.
$favorite.Arguments = "-new-window $url"
# ... and assign the icon.
$favorite.IconLocation = $favIconPath
$favorite.Save()
Note: The above downloads and assigns the target site's specific favicon as the shortcut file's icon, you can omit the relevant code above, which will make the shortcut file show Chrome's icon.
For the sake of completeness: Creating a URL shortcut file (.url) with the target site's favicon:
Note that such URL shortcut files invariably:
use the default web browser on invocation, and default to that browser's own icon.
typically create a new tab in an existing browser window rather than opening a new window.
As explained in this answer, assigning a custom icon programmatically isn't directly supported via the WScript.Shell COM object, but can be achieved via plain-text processing to modify the .url file after the fact, as shown below.
# Define the target URL.
$url = 'https://google.com'
# Derive a friendly representation from it, to serve as the name of the shortcut file
# and the downloaded favicon.
# Adjust as needed; e.g. $friendlySiteName = 'Google'
$friendlySiteName = $url -replace '^https?://(?:www\.)?'
# Determine the full path of the shortcut file; adjust as needed.
# Note the required ".url" extension.
$urlShortcutPath = "$HOME\Desktop\$friendlySiteName.url"
# Download the favicon:
# Create a designated local directory for storing favicons...
$targetDir = New-Item -Type Directory -Force "$HOME\favicons"
# ... and download the target site's favicon into it.
$favIconPath = Join-Path $targetDir.FullName ($friendlySiteName + '.ico')
& {
$ProgressPreference = 'SilentlyContinue'
Invoke-WebRequest -OutFile $favIconPath "$url/favicon.ico"
}
# Create the URL shortcut file, set its properties, and save it.
$shell = New-Object -ComObject WScript.Shell
$urlShortcut = $shell.CreateShortcut($urlShortcutPath)
# Tell the URL shortcut what URL to launch.
# !! No other properties are directly supported for URL shortcut files.
# !! Plain-text processing below compensates for that.
$urlShortcut.TargetPath = $url
$urlShortcut.Save()
# Now use plain-text processing to add the icon location.
Add-Content -LiteralPath $urlShortcut.FullName -Value #"
IconIndex=0
HotKey=0
IconFile=$favIconPath
"#
I am working on a PowerShell script, which will pull files from an FTP site. The files are uploaded to the FTP site every hour so I need to download the most recent one. The code I currently have downloads all the files from today instead of just one file. How do I make it download only the most recent file?
Here is the code that I am currently using
$ftpPath = 'ftp://***.***.*.*'
$ftpUser = '******'
$ftpPass = '******'
$localPath = 'C:\Temp'
$Date = get-date -Format "ddMMyyyy"
$Files = 'File1', 'File2'
function Get-FtpDir ($url, $credentials)
{
$request = [Net.FtpWebRequest]::Create($url)
if ($credentials) { $request.Credentials = $credentials }
$request.Method = [System.Net.WebRequestMethods+FTP]::ListDirectory
(New-Object IO.StreamReader $request.GetResponse().GetResponseStream()) -split "`r`n"
}
$webclient = New-Object System.Net.WebClient
$webclient.Credentials = New-Object System.Net.NetworkCredential($ftpUser,$ftpPass)
$webclient.BaseAddress = $ftpPath
Foreach ( $item in $Files )
{
Get-FTPDir $ftpPath $webclient.Credentials |
? { $_ -Like $item+$Date+'*' } |
% {
$webClient.DownloadFile($_, (Join-Path $localPath $_))
}
}
It's not easy with the FtpWebRequest. For your task, you need to know file timestamps.
Unfortunately, there's no really reliable and efficient way to retrieve timestamps using features offered by FtpWebRequest/.NET framework/PowerShell as they do not support an FTP MLSD command. The MLSD command provides listing of remote directory in a standardized machine-readable format. The command and the format is standardized by RFC 3659.
Alternatives which you can use, that are supported by .NET framework:
ListDirectoryDetails method (an FTP LIST command) to retrieve details of all files in a directory and then you deal with FTP server specific format of the details (*nix format similar to ls *nix command is the most common, drawback is that the format may change over time, as for newer files "May 8 17:48" format is used and for older files "Oct 18 2009" format is used)
GetDateTimestamp method (an FTP MDTM command) to individually retrieve timestamps for each file. Advantage is that the response is standardized by RFC 3659 to YYYYMMDDHHMMSS[.sss]. Disadvantage is that you have to send a separate request for each file, what can be quite inefficient.
Some references:
C# class to parse WebRequestMethods.Ftp.ListDirectoryDetails FTP response
Parsing FtpWebRequest ListDirectoryDetails line
Retrieving creation date of file (FTP)
Alternatively, use a 3rd party FTP library that supports the MLSD command, and/or supports parsing of the proprietary listing format.
For example WinSCP .NET assembly supports both.
An example code:
# Load WinSCP .NET assembly
Add-Type -Path "WinSCPnet.dll"
# Setup session options
$sessionOptions = New-Object WinSCP.SessionOptions -Property #{
Protocol = [WinSCP.Protocol]::Ftp
HostName = "example.com"
UserName = "user"
Password = "mypassword"
}
$session = New-Object WinSCP.Session
# Connect
$session.Open($sessionOptions)
# Get list of files in the directory
$directoryInfo = $session.ListDirectory($remotePath)
# Select the most recent file
$latest =
$directoryInfo.Files |
Where-Object { -Not $_.IsDirectory } |
Sort-Object LastWriteTime -Descending |
Select-Object -First 1
# Any file at all?
if ($latest -eq $Null)
{
Write-Host "No file found"
exit 1
}
# Download the selected file
$sourcePath = [WinSCP.RemotePath]::EscapeFileMask($remotePath + $latest.Name)
$session.GetFiles($sourcePath, $localPath).Check()
For a full code, see Downloading the most recent file (PowerShell).
(I'm the author of WinSCP)
I tried this, but i get an error:
Error: Exception calling "ListDirectory" with "1" argument(s): "Error listing directory '/path/'.
Could not retrieve directory listing
Can't open data connection for transfer of "/path/"
I read a lot about this problem on the internet, but could not find a solution which seemed fairly simple, and I am not a network setup wizard. So I choose a different approach. In our case the filename of the file which I want to automate the download for, has the date specified in it: backup_2018_08_03_020003_1048387.bak
So we can get the file by using mget *2018_08_03* in a command line ftp session.
Our backup procedure is run every morning at 01.00 AM, so we have a backup each day that we can fetch.
Of course it would have been prettier and nicer to have a script that fetched the latest backup file based on the backup file timestamps, just in case that something went wrong with the latest backup or the backup file naming format changes. The script is just a script to fetch the backup for internal development purposes so its not a big deal if it breaks. I will look into this later and check whether i can make a cleaner solution.
I made a batch script which just asks for todays backup file with the ordinary ftp command prompt scripting.
It is important to get the formatting of todays date right. It must match the formatting of the date in the filename correctly.
If you want to use the script you should replace the variables with your own information. You should also have write access to the directory where you run it from.
This is the script that I made:
#Echo Off
Set _FTPServerName=xxx.xxx.xx.xxx
Set _UserName=Username
Set _Password=Password
Set _LocalFolder=C:\Temp
Set _RemoteFolder="/path/"
Set _Filename=*%date:~-4,4%_%date:~-7,2%_%date:~-10,2%*
Set _ScriptFile=ftptempscript
:: Create script
>"%_ScriptFile%" Echo open %_FTPServerName%
>>"%_ScriptFile%" Echo %_UserName%
>>"%_ScriptFile%" Echo %_Password%
>>"%_ScriptFile%" Echo lcd %_LocalFolder%
>>"%_ScriptFile%" Echo cd %_RemoteFolder%
>>"%_ScriptFile%" Echo binary
>>"%_ScriptFile%" Echo mget -i %_Filename%
>>"%_ScriptFile%" Echo quit
:: Run script
ftp -s:"%_ScriptFile%"
del "%_ScriptFile%"
Just started using powershell on windows 7 and I want to download a file from a site that doesn't include the name of the file in the url. Right now I am using
$webclient = New-Object System.Net.WebClient
$src = "http://just-some-short-url/"
$dest = "C:\Users\Downloads\some-file-2.53.jar"
$webclient.DownloadFile($src,$dst)
And this works but only because I specify the name with some hard-coded value. But I really just want to say
$webclient = New-Object System.Net.WebClient
$src = "http://just-some-short-url/"
$dest = "C:\Users\Downloads\"
$webclient.DownloadFile($src,$dst)
So that whatever version is downloaded would just be named such in the C:\Users\Downloads\ so for example next month when there is a new update to the file I get from the same link presumably I would then have a file named some-file-2.54.jar However the latter code throws an error and is only fixed by hard coding the file name.
I made a basic PowerShell script. To download files from 2 urls
However even though it seems to download the files my computer can't open them.
When I mean my computer can't open the files here are the 2 specific errors:
When I try to open the first file I get the error: This installation package could not be opened. Contact the application vendor to verify that this is a valid Windows Installer package. When I try to open the second file it just says "This app can't run on your PC"
Here is the script:
$storageDir = $PSScriptRoot
$storageDir = $pwd
$webclient = New-Object System.Net.WebClient
$url = "http://www.microsoft.com/en-us/download/confirmation.aspx?id=20914"
$file = "$storageDir\xnafx40_redist.msi"
$webclient.DownloadFile($url,$file)
$url = "http://www.microsoft.com/en-us/download/confirmation.aspx?id=17851"
$file = "$storageDir\dotNetFx40_Full_setup.exe"
$webclient.DownloadFile($url,$file)
A little background about what I'm trying to do and why. We are slowly migrating from using a local copy of office on our end users Win7 machines to publishing office through RDS 2012. With 2012 you can have the end users machine subscribe to a webfeed which puts the shortcuts to the actual RDP files in Appdata. In order to have our image pretty much mirror before RDS, I need to pin the shortcuts to the taskbar. If you pin the shortcut as it comes from the RDS Gateway server the icon on the taskbar is that of the .rdp file. If you edit the target for the shortcut and put mstsc.exe before the path to the .rdp file you can then pin the shortcut to the taskbar using those icons of the shortcut.
I have found posts on how to change the target field of shortcuts but nothing on how to add something to what is currently there. An environment variable is needed since the path to the shorts will be different for each user. Below is I have tried thus far
$Word = $env:userprofile + "\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\RemoteApp and Desktop Connections\Microsoft Word 2010.lnk"
$sh = New-Object -COM WScript.Shell
$targetPath = $sh.CreateShortcut($Word).TargetPath
$sh.TargetPath = "mstsc.exe" + $targetPath ## Make changes
$sh.Save() ## Save$shell = New-Object -COM WScript.Shell
One of the errors i'm getting is : Property 'Arguments' cannot be found on this object; make sure it exists and is settable.
Any help will be greatly appreciated.
Instead of using Shell COM object, how about using a .Net wrapper class? There is a great sample.
To use the VBAccelerator's wrapper in Powershell, extract the source code and compile a DLL like so,
C:\Windows\Microsoft.NET\Framework\v2.0.50727\csc.exe /t:library /out:ShellLink.dll /r:System.Drawing.dll .\ShellLink.cs .\FileIcon.cs
This should create ShellLink.dll, which you can add as Powershell type like so,
Add-Type -path .\ShellLink.dll
And use the class by creating a new object like so,
$lnk = new-object vbAccelerator.Components.Shell.ShellLink
$lnk.Target = "C:\Windows\System32\mstsc.exe"
$lnk.Arguments = "some arguments"
$lnk.Description = "My awesome shortcut"
$lnk.Save("c:\temp\test.lnk")
Your code will prepend "mstsc.exe" to the current target path if you just add this line before your ## Make changes line:
$sh = $sh.CreateShortcut($word)
Sounds like you also want to add a space, so that your lnk file is the "connection file" argument of mstsc.exe. You can set the Arguments property like so:
function Set-RDSshortcut {
param( [parameter(mandatory=$true)]$Shortcut )
$sh = New-Object -COM WScript.Shell
$targetPath = $sh.CreateShortcut($Shortcut).TargetPath
$targetPath = "mstsc.exe"
$sh = $sh.CreateShortcut($Shortcut)
$sh.TargetPath = $targetPath
$sh.Arguments = $Shortcut
$sh.Save()
} #end function