为啥cmd powershell -command中的最后一行错误
Posted
技术标签:
【中文标题】为啥cmd powershell -command中的最后一行错误【英文标题】:Why does the last line in cmd powershell -command error为什么cmd powershell -command中的最后一行错误 【发布时间】:2021-11-29 03:18:52 【问题描述】:'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'
【问题讨论】:
设置 $Path 变量需要使用引号字符而不是撇号字符,以便允许对 $CurrentDate 进行变量插值。在引号字符内,必须使用转义。"$Path = "C:\Users...otes_$CurrentDate.csv\""
.
另外,使用$Path = Join-Path $Env:USERPROFILE -ChildPath "Desktop\stockQuotes_$CurrentDate.csv\""
可能会更好。
【参考方案1】:
您正在使用每个命令启动一个新的 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)
或者像这样的批处理文件:
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);
【讨论】:
以上是关于为啥cmd powershell -command中的最后一行错误的主要内容,如果未能解决你的问题,请参考以下文章
powershell 从PowerShell运行CMD中的命令