【问题标题】:Method invocation error when using PSCredential in Powershell在 Powershell 中使用 PSCredential 时方法调用错误
【发布时间】:2019-10-25 04:39:28
【问题描述】:

我首先要说的是,当我在笔记本电脑上本地运行时,我已经成功地测试了这个脚本,并针对远程开发服务器。

但是,当我将脚本迁移到我们的 TFS 服务器时,我现在遇到了以下(已清理)错误消息。

2019-06-10T18:46:05.8256626Z Generating script.
2019-06-10T18:46:05.8257313Z Formatted command: . 'E:\***.ps1' -username "***" -password "***" -servername "***" -ScriptPath "***" -SourcePath "***" -DestinationPath "***" -CleanupFlag "***"
2019-06-10T18:46:06.0290179Z ##[command]"C:\windows\System32\WindowsPowerShell\v1.0\powershell.exe" -NoLogo -NoProfile -NonInteractive -ExecutionPolicy Unrestricted -Command ". 'E:\***.ps1'"
2019-06-10T18:46:06.7520864Z Method invocation failed because [System.Management.Automation.PSCredential] does not contain a method named 'new'.
2019-06-10T18:46:06.7521292Z At E:\***.ps1:5 char:1
2019-06-10T18:46:06.7521480Z + $CredentialSec = [System.Management.Automation.PSCredential]::new($username,$PWsec)
2019-06-10T18:46:06.7523016Z + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
2019-06-10T18:46:06.7523588Z     + CategoryInfo          : InvalidOperation: (:) [], ParentContainsErrorRecordException
2019-06-10T18:46:06.7524614Z     + FullyQualifiedErrorId : MethodNotFound
2019-06-10T18:46:06.7525361Z  
2019-06-10T18:46:06.8602349Z ##[error]PowerShell exited with code '1'.

脚本正在尝试在远程系统上调用命令(以运行不同的脚本)。它似乎在从用户名和加密密码创建凭据的部分搞砸了。

这是我正在尝试执行的代码:

param($username, $password, $servername, $ScriptPath, $SourcePath, $DestinationPath, $CleanupFlag)


$PWsec = ConvertTo-SecureString -String $password -AsPlainText -Force
$CredentialSec = [System.Management.Automation.PSCredential]::new($username,$PWsec)

Invoke-Command -ComputerName $servername -Credential $CredentialSec -FilePath $ScriptPath -ArgumentList $SourcePath, $DestinationPath, $CleanupFlag

【问题讨论】:

  • 我不记得确切的细节,但我认为使用 "::new" 来调用构造函数是最近对 PowerShell 的补充。尝试在您的机器和 tfs 服务器上运行 $psversiontable 以检查安装的版本,并尝试使用“new-object System.Management.Automation.PSCredential($username,$PWsec)”而不是“::new”样式。
  • 啊,我们开始...learn-powershell.net/2014/09/07/… - 添加到 PowerShell 5 - 请参阅“新增功能”部分。如果可行,我会将其变成答案...
  • 成功了。谢谢!

标签: powershell tfs automation scripting


【解决方案1】:

根据 mcclayton 在 cmets 中的建议...因为新服务器运行的是旧版本的 Powershell,所以当我从这种格式更改时它可以工作:

$CredentialSec = [System.Management.Automation.PSCredential]::new($username,$PWsec)

转成这种格式:

$CredentialSec = New-Object System.Management.Automation.PSCredential($username,$PWsec)

【讨论】:

  • 太棒了!感谢您在此处分享您的解决方案,您可以接受它作为答案,这样它可以帮助遇到相同问题的其他社区成员,我们可以归档这个帖子,谢谢。
猜你喜欢
  • 1970-01-01
  • 2018-11-23
  • 1970-01-01
  • 2020-07-24
  • 2021-11-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-09-28
相关资源
最近更新 更多