找不到接受参数-System.Management.Automation.PSCredential'-Error的位置参数

时间:2019-06-08 03:44:12

标签: powershell

我有一个脚本,需要通过远程传递脚本中的凭据,如下所示:-

$UserName = Read-Host "Enter User Name:" 
$Password = Read-Host -AsSecureString "Enter Your Password:" 
$Credential = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $UserName , $Password 


Set-Service -Name HiTrust -StartupType Automatic -ComputerName ServerName -credential $Credential 
(Get-Service  -Name "HiTrust" -credential $Credential -ComputerName ServerName).Start() 
Exit

但是我仍然遇到如下错误:-

Set-Service : A positional parameter cannot be found that accepts argument 'System.Management.Automation.PSCredential'.
At C:\Users\ucub\Desktop\Test.ps1:9 char:15
+ ...             Set-Service -Name HiTrust -StartupType Automatic -Compute ...
+                 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidArgument: (:) [Set-Service], ParentContainsErrorRecordException
    + FullyQualifiedErrorId : PositionalParameterNotFound,Microsoft.PowerShell.Commands.SetServiceCommand

2 个答案:

答案 0 :(得分:0)

问题在于,设置服务没有凭据参数。看here

尝试这样的事情:

Enter-PSSession -ComputerName $computername -Credential $credentials
Set-Service -Name HiTrust -StartupType Automatic

Invoke-Command -ComputerName $computername -Credential $credential -ScriptBlock {Set-Service -Name HiTrust -StartupType Automatic}

答案 1 :(得分:0)

如果您使用的是此PSVersion及更低版本,这是您在Set-Service上失败的根本原因...

$PSVersionTable.PSVersion

<#
Major  Minor  Build  Revision
-----  -----  -----  --------
5      1      17763  503  
#>   



(Get-Command -Name Set-Service).Parameters.Keys
# Results

ComputerName
Name
DisplayName
Description
StartupType
Status
InputObject
PassThru
Verbose
Debug
ErrorAction
WarningAction
InformationAction
ErrorVariable
WarningVariable
InformationVariable
OutVariable
OutBuffer
PipelineVariable
WhatIf
Confirm

您也不需要脚本中的内容。

我建议重构

(Get-Command -Name Invoke-Command).Parameters.Keys
# Results
Session
ComputerName
Credential
...


$ServerName = Read-Host 'Enter a target server name:' 
$ServiceName = Read-Host 'Enter a target service name:' 
Invoke-Command -ComputerName $ServerName -ScriptBlock {
    "Executing service actions on $env:COMPUTERNAME"
    Set-Service -Name $ServiceName -StartupType Automatic
    Start-Service -Name $ServiceName
} -Credential (Get-Credential -Credential "$env:USERDOMAIN\$env:USERNAME")