[英]Powershell Script is getting executed remotely through C# client but not from Powershell window
我正在嘗試運行以下腳本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();
}
}
我得到的印象是,您正在考慮在計算機A上運行針對計算機A的命令。 Import-PSSession允許您使用計算機上另一台計算機上的命令,模塊。
您可能需要研究invoke-command -Session $ session -scriptBlock {將代碼放在此處}
當我從新的Powershell Windows嘗試時,該問題已解決。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.