Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

working with relative paths in powershell WebClient and FileStream

I'm tasked with writing a powershell script to perform a file download, which will eventually be executed as a scheduled task once a week. I have no background in programming in the windows environment so this has been an interesting day.

I am experiencing a problem with the unexpected handling of the $pwd and $home of the shell.

I pass into my program a download URL and a destination file. I would like the destination file to be a relative path, e.g., download/temp.txt.gz

param($srcUrl, $destFile)

$client = new-object System.Net.WebClient
$client.DownloadFile($srcUrl, $destFile)

Ungzip-File $destFile

Remove-Item $destFile

This actually fails on the call to Remove-Item. If $destFile is a relative path then the script happily downloads the file and puts it in a file relative to $home. Likewise, I then unzip this and my function Ungzip-File makes use of System.IO.Filestream, and it seems to find this file. Then Remove-Item complains that there is no file in the path relative to $pwd.

I am a bit baffled, as these are all part of the shell, so to speak. I'm not clear why these functions would handle the path differently and, more to the point, I'm not sure how to fix this so both relative and absolute paths work. I've tried looking at the io.path methods but since my $home and $pwd are on different drives, I can't even use the IsPathRooted which was seemed so close when I found it.

Any help?

like image 275
Matt Thompson Avatar asked Dec 30 '25 20:12

Matt Thompson


2 Answers

You have to be aware of where you are in the path. $pwd works just fine on the command shell but let's say you have started your script from a scheduled job. You might think $pwd is where your script resides and code accordingly but find out that it actually uses, say %windir%\system32.

In general, I would use fullpath to destination and for paths relative to script folder I would use $PSScriptRoot/folder_name/file_path.

There are catches there too. For example, I noticed $PSScriptRoot will resolve just fine within the script but not within Param() block. I would highly suggest using write-verbose when coding and testing, so you know what it thinks the path is.

[CMDLETBINDING()] ## you need this!
Param()
write-verbose "path is $pwd"
Write-Verbose "removing $destFile"
Remove-Item $destfile

and add -verbose when you are calling your script/function:

myscript.ps1 -verbose
mydownloadfunction -verbose
like image 61
Adil Hindistan Avatar answered Jan 01 '26 14:01

Adil Hindistan


To use a relative path, you need to specify the current directory with ./

Example: ./download/temp.txt.gz

You can also change your location in the middle of the script with Set-Location (alias: cd)

like image 39
Vasili Syrakis Avatar answered Jan 01 '26 12:01

Vasili Syrakis