1
'C:\Users\kevin>powershell -Command "$Url = 'http://shared4.info/psequotes/files/2021/stockQuotes_$CurrentDate.csv'"

C:\Users\kevin>powershell -Command "$Path = 'C:\Users\kevin\Desktop\stockQuotes_$CurrentDate.csv'"

C:\Users\kevin>powershell -Command "$WebClient = New-Object System.Net.WebClient"

C:\Users\kevin>powershell -Command "$WebClient.DownloadFile($url, $path)"
You cannot call a method on a null-valued expression.
At line:1 char:1
+ $WebClient.DownloadFile($url, $path)
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo          : InvalidOperation: (:) [], RuntimeException
+ FullyQualifiedErrorId : InvokeMethodOnNull'
2
  • Settting the $Path variable needs to use QUOTATION MARK characters instead of APOSTROPHE characters in order to allow variable interpolation of $CurrentDate. Inside QUOTATION MARK characters, escape must be used. "$Path = "C:\Users...otes_${CurrentDate}.csv\"". Commented Oct 9, 2021 at 16:05
  • Also, it would probably be better to use $Path = Join-Path $Env:USERPROFILE -ChildPath "Desktop\stockQuotes_${CurrentDate}.csv\"". Commented Oct 9, 2021 at 16:07

1 Answer 1

5

You're starting a new Powershell session with each command. And so the variable $WebClient doesn't exist in the powershell session created in the last command.

Instead of calling powershell -Command on each line, call powershell once and run all those statements in a single session. eg:

C:\Users\david>powershell
Windows PowerShell
Copyright (C) Microsoft Corporation. All rights reserved.

Install the latest PowerShell for new features and improvements! https://aka.ms/PSWindows

PS C:\Users\david> $Url = 'http://shared4.info/psequotes/files/2021/stockQuotes_$CurrentDate.csv'
PS C:\Users\david> $Path = 'C:\Users\kevin\Desktop\stockQuotes_$CurrentDate.csv'
PS C:\Users\david> $WebClient = New-Object System.Net.WebClient
PS C:\Users\david> $WebClient.DownloadFile($url, $path)

Or from a batch file like this:

powershell -Command ^
$Url = 'http://shared4.info/psequotes/files/2021/stockQuotes_$CurrentDate.csv'; ^
$Path = 'C:\Users\kevin\Desktop\stockQuotes_$CurrentDate.csv'; ^
$WebClient = New-Object System.Net.WebClient; ^
$WebClient.DownloadFile($url, $path);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.