在Powershell中使用PSCredential时方法调用错误

时间:2019-06-10 19:05:04

标签: powershell tfs automation scripting

首先,我说说我在笔记本电脑上针对远程开发服务器在本地运行时已成功测试了此脚本。

但是,当我将脚本迁移到我们的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

1 个答案:

答案 0 :(得分:0)

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

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

为此格式:

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