ms mavie
ms mavie

Reputation: 15

Why does the last line in cmd powershell -command error

'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'

Upvotes: 1

Views: 132

Answers (1)

David Browne - Microsoft
David Browne - Microsoft

Reputation: 89424

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);

Upvotes: 5

Related Questions