首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >为什么cmd powershell中的最后一行出现-command错误

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

Stack Overflow用户
提问于 2021-10-09 15:29:54
回答 1查看 88关注 0票数 1
代码语言:javascript
复制
'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'
EN

回答 1

Stack Overflow用户

发布于 2021-10-09 15:35:44

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

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

代码语言:javascript
复制
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)

或者从如下所示的批处理文件:

代码语言:javascript
复制
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);
票数 5
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/69508142

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档