PowerShell 错误 - 一元运算符'-'后缺少表达式



我有两个PowerShell脚本。一种是在SharePoint服务器上卸载和安装SharePoint 2010解决方案。另一个使用两个命令调用此脚本,一个用于卸载,另一个用于安装。这些不是我写的剧本,但我继承了它们。

以下是调用安装/卸载脚本的脚本(为了简化故障排除,我删除了一些参数(:

& 'C:UsersusernameDocumentssetup.ps1' -InstallOrUninstall '/UNINSTALL'
& 'C:UsersusernameDocumentssetup.ps1' -InstallOrUninstall '/INSTALL'

为了测试的目的,这里是";ps1";脚本:

param ($InstallOrUninstall, 
$SiteURL, 
$WebURL, 
[switch]$ignoreFeatures, 
[switch]$thisAppDomain )
if (-not $thisAppDomain)
{
Write-Host "Invoking script in a new app domain"  -foregroundcolor yellow
Write-Host $MyInvocation.Line
powershell.exe -Version 2 -Command $MyInvocation.Line -thisAppDomain
return;
}
Write-Host "In Body"
Write-Host $MyInvocation.Line

运行第一个脚本会从第一个命令返回错误,但不会从第二个命令返回。错误为:

powershell.exe : - : Missing expression after unary operator '-'.
At C:UsersusernameDocumentssetup.ps1:11 char:6
+      powershell.exe -Version 2 -Command $MyInvocation.Line -thisAppDo ...
+      ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo          : NotSpecified: (- : Missing exp...y operator '-'.:String) [], RemoteException
+ FullyQualifiedErrorId : NativeCommandError

+ CategoryInfo          : ParserError: (-:String) [], ParentContainsErrorRecordException
+ FullyQualifiedErrorId : MissingExpressionAfterOperator

我相信安装/卸载脚本重新发送";版本2";是因为在SharePoint 2010中使用PowerShell旧版本2时出现问题(如此处所述(。然而,我不明白为什么只有第一行失败了。第二个命令也输入if语句,但不会出错。

如果我删除第二行,并且只调用setup.ps1一次,那么调用安装/卸载脚本的脚本就会成功。

一个不错的小脑筋急转弯。显然,$MyInvocation.Line包含完整的行,包括末尾的换行符。因此,-thisAppDomain不被解释为参数,而是以-开始的新表达式的开始。这也是为什么如果你删除第二行,它会起作用,因为然后你在结尾没有换行符。

要重现此错误,请尝试:

powershell.exe -Version 2 -Command "`r`n-thisAppDomain"

请注意,在较新版本中,解析算法明显被修改,错误消息也有所不同。省略-Version 2开关,您可能会得到:

术语"-thisAppDomain";未被识别为cmdlet、函数、脚本文件或可操作程序的名称。。。

解决此问题的一个简单方法是.Trim()(或.TrimEnd()(命令:

powershell.exe -Version 2 -Command $MyInvocation.Line.Trim() -thisAppDomain

不过,我需要补充一点,你应该重新考虑你的实际问题是什么,以及你的解决方案是否真的是解决它的最佳方法。例如,看看工作。

正如marsze所说:它不是一个参数,而是一个以-开头的新表达式的开头。这也是为什么如果你删除第二行,它会起作用,因为这样你就不会在末尾有换行符。

最新更新