英文:
Write-Error: Cannot bind argument to parameter 'Exception' because it is null
问题
I’ve run into a strange error using WinSCP's .NET Assembly to develop an SFTP client. It occurs when I call PutFileToDirectory()
as follows:
try {
$hostDirectory = Get-PathBelowWebRoot -root $pcRoot -file $file
$remove = $false
$session.PutFileToDirectory($file.fullName, $hostDirectory, $remove, $options)
}
catch {
$errorObject = $Error[0]
Write-Error $errorObject
$($errorObject.InvocationInfo)
exit
}
Upon calling PutFileToDirectory
, execution goes to the catch block, and PowerShell issues this message:
Write-Error: Cannot bind argument to parameter 'Exception' because it is null.
I've used $Error[0]
successfully in the past to get error details, but for some reason it doesn’t work here.
Does anyone know how to discover the error details?
Output from $PSVersionTable.PSVersion
:
Major Minor Patch PreReleaseLabel BuildLabel
----- ----- ----- --------------- ----------
7 3 4
I’m using the PowerShell extension to Visual Studio Code, version 1.79.0
英文:
I’ve run into a strange error using WinSCP's .NET Assembly to develop an SFTP client. It occurs when I call PutFileToDirectory()
as follows:
try {
$hostDirectory = Get-PathBelowWebRoot -root $pcRoot -file $file
$remove = $false
$session.PutFileToDirectory($file.fullName, $hostDirectory, $remove, $options)
}
catch {
$errorObject = $Error[0]
Write-Error $errorObject
$($errorObject.InvocationInfo)
exit
}
Upon calling PutFileToDirectory
, execution goes to the catch block, and PowerShell issues this message:
> Write-Error: Cannot bind argument to parameter 'Exception' because it is null.
I've used $Error[0]
successfully in the past to get error details, but for some reason it doesn’t work here.
Does anyone know how to discover the error details?
Output from $PSVersionTable.PSVersion
:
Major Minor Patch PreReleaseLabel BuildLabel
----- ----- ----- --------------- ----------
7 3 4
I’m using the PowerShell extension to Visual Studio Code, version 1.79.0
答案1
得分: 1
这个答案并没有解释你的症状,但基于你的反馈,提供了一个有效的解决方法:
-
在你的
catch
块中,不需要使用 自动变量$Error
,而是使用 自动变量$_
来引用当前的错误。 -
如果仅仅打印错误的 消息,即其 字符串表示 足够的话,你可以使用:
Write-Error -Message $_
另外:如果在脚本中以响应 错误 使用 exit
,最好传递一个 非零的退出代码 给调用者,以表示发生了错误;例如 exit 1
。
英文:
This answer doesn't explain your symptom, but - based on your feedback - offers an effective workaround:
-
There's no need to use the automatic
$Error
variable in yourcatch
block - instead, use the automatic$_
variable to refer to the error at hand. -
If merely printing the error's message, i.e. its string representation is enough, you can use:
Write-Error -Message $_
As an aside: if you're using exit
in a script in response to an error, it's best to pass it a nonzero exit code to signal to the caller that an error occurred; e.g. exit 1
.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论