为什么 cmd powershell -command 中的最后一行出现错误

ms *_*vie 1 powershell cmd batch-file

'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'
Run Code Online (Sandbox Code Playgroud)

Dav*_*oft 5

您将使用每个命令启动一个新的 Powershell 会话。因此,$WebClient在上一个命令中创建的 powershell 会话中不存在该变量。

不要powershell -Command 在每一行上调用,而是调用powershell 一次并在单个会话中运行所有这些语句。例如:

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)
Run Code Online (Sandbox Code Playgroud)

或者从这样的批处理文件中:

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);
Run Code Online (Sandbox Code Playgroud)