Powershell脚本通过C#客户端远程执行,但不是从Powershell窗口执行

时间:2014-01-31 10:53:02

标签: c# windows powershell powershell-remoting

我正在尝试运行以下脚本CreateUser.ps1:

$comp = [ADSI]('WinNT://MachineName,computer');
$user = $comp.Create('User', 'User121');
$user.SetPassword('Welcome1$');
$user.SetInfo();
$user.Description = "Created through powershell client";
$user.SetInfo();

我正在使用PowerShell窗口在远程计算机上运行脚本,步骤如下:

 $cred = Get-Credential

 $Session = New-PSSession -ComputerName MachineName -ConfigurationName Microsoft.PowerShell -Credential $cred

Import-PSSession $session

使用以下命令运行脚本:

C:\scripts\CreateUser.ps1

我收到以下异常:

Exception calling "SetInfo" with "0" argument(s): "Access is denied.
"
At C:\scripts\createUser.ps1:4 char:14
+ $user.SetInfo <<<< ();
    + CategoryInfo          : NotSpecified: (:) [], MethodInvocationException
    + FullyQualifiedErrorId : CatchFromBaseAdapterMethodInvokeTI

Cannot set the Value property for PSMemberInfo object of type "System.Management.Automation.PSMethod".
At C:\scripts\createUser.ps1:5 char:7
+ $user. <<<< Description = "Created through powershell client";
    + CategoryInfo          : InvalidOperation: (:) [], RuntimeException
    + FullyQualifiedErrorId : PropertyAssignmentException

Exception calling "SetInfo" with "0" argument(s): "Access is denied.
"
At C:\scripts\createUser.ps1:6 char:14
+ $user.SetInfo <<<< ();
    + CategoryInfo          : NotSpecified: (:) [], MethodInvocationException
    + FullyQualifiedErrorId : CatchFromBaseAdapterMethodInvokeTI

但是从C#客户端做同样的工作

WSManConnectionInfo connectionInfo = new WSManConnectionInfo(false, "MachineName", 5985, "/wsman", shellUri, credential);
using (Runspace runspace = RunspaceFactory.CreateRunspace(connectionInfo))
   {
                runspace.Open();
                using (PowerShell powershell = PowerShell.Create())
                {
                    powershell.Runspace = runspace;
                    String file = @"C:\scripts\createUser.ps1";
                    powershell.Commands.AddScript(System.IO.File.ReadAllText(file));
                    Collection<PSObject> results = powershell.Invoke();
                  }
      }

2 个答案:

答案 0 :(得分:0)

我得到的印象是,当您在计算机上运行时,您正在考虑对计算机A运行命令。 Import-PSSession允许您使用计算机上另一台计算机上的命令和模块。

你可能想要调查invoke-command -Session $ session -scriptBlock {把你的代码放在这里}

答案 1 :(得分:0)

当我尝试使用全新的PowerShell Windows时,问题得以解决。