将值作为参数的 Powershell 错误

Powershell error with value as a parameter

我在 Powershell 中有以下脚本:

#more code here

$CRMConn = "AuthType=AD;Url=http://${ipSolution}/${organizationName}; Domain=${domain}; Username=${username}; Password=${password}; OrganizationName=${organizationName}"

echo $CRMConn

Invoke-Command -Computername $hostnameSolution -ScriptBlock {Import-XrmSolution -SolutionFilePath "${fDrive}:\DEPLOYMENT\TCRM\CrmSolution${solutionName}" -ConnectionString $CRMConn -PublishWorkflows $true -OverwriteUnmanagedCustomizations $true -SkipProductUpdateDependencies $true -WaitForCompletion $true -Timeout 7200 -verbose:$true} -Credential $cred

执行时出现如下错误(已修改敏感信息):

AuthType=AD;Url=http://192.168.10.53/ORGNAME; Domain=domain; Username=username; Password=Password123@; OrganizationName=ORGNAME

Cannot bind argument to parameter 'ConnectionString' because it is null. + CategoryInfo : InvalidData: (:) [Import-XrmSolution], Parameter BindingValidationException + FullyQualifiedErrorId : ParameterArgumentValidationErrorNullNotAllowed,X
rm.Framework.CI.PowerShell.Cmdlets.ImportXrmSolutionCommand + PSComputerName : li1appcrmf14

$CRMConn 变量在您的脚本块中不可见。您必须使用 Invoke-CommandArgumentList 参数将变量传递给您的脚本块。

Invoke-Command -Computername $hostnameSolution `
    -ScriptBlock {param($conn, $fDrive, $solutionName) Import-XrmSolution -SolutionFilePath "${fDrive}:\DEPLOYMENT\TCRM\CrmSolution${solutionName}" -ConnectionString $conn -PublishWorkflows $true -OverwriteUnmanagedCustomizations $true -SkipProductUpdateDependencies $true -WaitForCompletion $true -Timeout 7200 -verbose:$true} ` 
    -Credential $cred `
    -ArgumentList $CRMConn, $fDrive, $solutionName

问题是您试图将变量从 "outside" 运行 脚本传递到独立的 "inside" 脚本块。也就是说,您应该将脚本块视为一个完全独立的独立代码块,应该是完全独立的。如果你想传递信息或变量,你应该在脚本块中使用参数来做到这一点(参见@dee-see post)。唯一的替代方法 (PowerShell v3+) 是使用 $using: 范围变量 (PowerShell: Passing variables to remote commands)

Invoke-Command -Computername $hostnameSolution -ScriptBlock {Import-XrmSolution -SolutionFilePath "${fDrive}:\DEPLOYMENT\TCRM\CrmSolution${solutionName}" -ConnectionString $using:CRMConn -PublishWorkflows $true -OverwriteUnmanagedCustomizations $true -SkipProductUpdateDependencies $true -WaitForCompletion $true -Timeout 7200 -verbose:$true} -Credential $cred