在 C# 中使用不同的凭据调用远程 powershell 脚本

     2023-04-13     235

关键词:

【中文标题】在 C# 中使用不同的凭据调用远程 powershell 脚本【英文标题】:calling remote powershell script with different credential in C# 【发布时间】:2013-05-08 05:12:31 【问题描述】:

我正在尝试在远程服务器中调用一个 powershell 脚本文件,该文件基本上获取一个参数并使用该参数创建一个共享驱动器。凭据都是正确的,但是每当我运行它时,它都会返回此错误:

当运行空间设置为使用当前线程时,调用设置中的单元状态必须匹配当前线程的状态

这与凭据有关,因为一旦我删除了凭据,它就可以在我的本地计算机上正常运行。 任何人都可以阐明这一点吗?谢谢,

以下是我的 C# 脚本:

PSCredential credential = new PSCredential(_exchangeUsername, password);

// Set exchange connection details
WSManConnectionInfo connectionInfo = new WSManConnectionInfo((new Uri(_exchangeConnectionUri)), "http://schemas.microsoft.com/powershell/Microsoft.Exchange", credential);

connectionInfo.AuthenticationMechanism = AuthenticationMechanism.Default;
string cmdArg = @"\\servername\\c$\\scripts\\HomeDrive.ps1 "+userID;

using (Runspace runspace = RunspaceFactory.CreateRunspace(connectionInfo))

    try
    
        runspace.ThreadOptions = PSThreadOptions.UseCurrentThread;
        runspace.ApartmentState = System.Threading.ApartmentState.STA;
        runspace.Open();

        Pipeline pipeline = runspace.CreatePipeline();
        pipeline.Commands.AddScript(cmdArg);
        pipeline.Commands[0].MergeMyResults(PipelineResultTypes.Error, PipelineResultTypes.Output);
        Collection<PSObject> results = pipeline.Invoke();
        var error = pipeline.Error.ReadToEnd();
        // Check for powershell command errors
        if (error.Count > 0)
        
            throw new Exception(errorMessage.ToString());
        

        // Check for powershell command results
        if (results.Count <= 0)
        
            throw new Exception(String.Format("Error. No results after command invoked.", userID));
        
        runspace.Close();
    
    catch (Exception ex)
    
        runspace.Close();
        throw new ApplicationException(String.Format("Error ", userID), ex);
    

【问题讨论】:

它不喜欢runspace.ApartmentState = System.Threading.ApartmentState.STA,因为当前线程不是STA线程。您需要删除此行或删除其上方的行... 如果我删除任何一行,它会抛出错误“不支持指定方法” 它说不支持哪种方法? Collection 结果 = pipeline.Invoke(); 这条线似乎不被支持。如果我删除 connectionInfo 凭据,它似乎在我的本地机器上工作正常 【参考方案1】:

我认为您使用了错误的构造函数重载 WSManConnectionInfo。您可以在创建对象之后检查对象的 Credential 属性,但在传递它以创建运行空间之前。

这是我自己的代码中的一个 sn-p,它工作正常,我正在使用最冗长的构造函数(我认为)

#region create WSmanconnection
//Create the PowerShell Remoting WinRM WSMan connection object so we can connect to the remote machine, only using credentials if Not Implicitly negotiated.
var ci = new WSManConnectionInfo(
    useSSL, trueFQDN , port, appName, shellUri,
    (authenticationMechanism == AuthenticationMechanism.NegotiateWithImplicitCredential) ? null : credential)
    
        AuthenticationMechanism = authenticationMechanism,
        OpenTimeout = openTimeoutMinutes * 60 * 1000,
        OperationTimeout = operationTimeoutMinutes * 60 * 1000,
        IdleTimeout = idleTimeOut * 60 * 1000
    ;
#endregion

【讨论】:

如何在 C# 中使用反射调用具有不同类型参数的方法

】如何在C#中使用反射调用具有不同类型参数的方法【英文标题】:HowtocallamethodwithargumentsofdifferenttypesusingreflectioninC#【发布时间】:2011-12-0602:42:11【问题描述】:我正在尝试使用C#中的.NET反射调用一个接受两个参数(一个布尔值... 查看详情

使用安全凭据调用 SQL 命令

】使用安全凭据调用SQL命令【英文标题】:InvokeSQLCommandwithSecureCreds【发布时间】:2016-02-0412:13:16【问题描述】:我对如何在Powershell命令中使用安全字符串来运行远程SQL查询有点卡住。以下命令可以在powershell中运行,因为它是在... 查看详情

如何在 C# 中使用服务帐户登录 Google API - 凭据无效

】如何在C#中使用服务帐户登录GoogleAPI-凭据无效【英文标题】:HowtologintoGoogleAPIwithServiceAccountinC#-InvalidCredentials【发布时间】:2016-11-1801:25:30【问题描述】:我正在拼命尝试让一个简单的服务帐户登录以在C#、GoogleAPI和GoogleAnalytic... 查看详情

如何在 c# 应用程序中正确保护 api 凭据

...个WebApi2项目,它是这个restfulapi的服务器端。客户端当前使用用户名/密码组合来获取承载令牌,然后在后续api调用中使用该令牌。该项目存储在GitHub上的私有项目 查看详情

C# 尝试打开远程文件位置但 Windows 未传递凭据

...远程工作站上打开\\\\whatever\\c$。我将首先说应用程序是使用&lt;requestedExecutionLevellevel=&qu 查看详情

如何在 Windows 应用程序 C# 中使用凭据从 URL 下载文件

】如何在Windows应用程序C#中使用凭据从URL下载文件【英文标题】:HowtodownloadafilefromURLwithcredentialsinwindowsapplicationC#【发布时间】:2021-11-1821:02:54【问题描述】:大家好!我需要一个从网站下载文件的功能,在下载之前它将被重定... 查看详情

在 c# 中使用 Pgina 修改 Windows 登录 UI(凭据提供程序)

】在c#中使用Pgina修改Windows登录UI(凭据提供程序)【英文标题】:ModifyWindowsLogonUI(CredentialProvider)usingPginainc#【发布时间】:2017-09-0906:18:37【问题描述】:我正在尝试使用Pgina-fork来修改Windows登录。我不想使用用户名和密码,而是... 查看详情

rabbitmq系列教程之六:远程过程调用(rpc)

远程过程调用(RemoteProceddurecall【RPC】)(本实例都是使用的Net的客户端,使用C#编写) 在第二个教程中,我们学习了如何使用工作队列在多个工作实例之间分配耗时的任务。 但是,如果我们需要在远程计算机上运行功... 查看详情

Laravel:针对远程检查凭据的系统进行身份验证

...,如果登录成功则返回用户信息。这种方法与Laravel完全不同,在Lar 查看详情

使用 Angular 检查远程网站的登录凭据

】使用Angular检查远程网站的登录凭据【英文标题】:ChecklogincredentialsofremotewebsitewithAngular【发布时间】:2019-06-2918:14:31【问题描述】:我正在使用Angular7为黑客新闻创建一个界面。通常我使用可用的公共API,但对于登录服务,它... 查看详情

从 C# 访问 Sharepoint 远程文件夹

...我必须介绍有权查看远程资源的用户的凭据。在此之后,使用以下代码:string 查看详情

“调用线程无法访问此对象,因为不同的线程拥有它”在 C# winforms 中使用 LiveCharts 绘图库时出错

...无法访问此对象,因为不同的线程拥有它”在C#winforms中使用LiveCharts绘图库时出错【英文标题】:\'Thecallingthreadcannotaccessthisobjectbecauseadifferentthreadownsit\'errorusingLiveChartsplottinglibraryinC#winforms【发布时间】:2021-10-1010:28:21【问题描述... 查看详情

使用 c# 枚举远程系统上的 Windows 用户组成员

】使用c#枚举远程系统上的Windows用户组成员【英文标题】:EnumerateWindowsusergroupmembersonremotesystemusingc#【发布时间】:2010-09-0611:55:29【问题描述】:在c#中,我需要能够连接到远程系统,根据需要指定用户名/密码列出该系统上本地... 查看详情

Youtube Data API C# - 无需请求用户凭据即可使用

】YoutubeDataAPIC#-无需请求用户凭据即可使用【英文标题】:YoutubeDataAPIC#-usewithoutrequestingusercredentials【发布时间】:2020-09-0205:07:24【问题描述】:我想在C#中使用YouTubeDataAPI-.NetCore-无需请求用户凭据。我需要从这个API中唯一需要的... 查看详情

无法使用 WMI 和 C# 远程终止进程

】无法使用WMI和C#远程终止进程【英文标题】:UnabletoremotelyterminateaprocessusingWMIandC#【发布时间】:2013-09-2422:44:53【问题描述】:我正在尝试编写一个方法,如果它无法使用StopService方法停止,它将通过进程ID终止远程系统上的服... 查看详情

如何在 c# 中调用与构造函数不同的构造函数? [复制]

】如何在c#中调用与构造函数不同的构造函数?[复制]【英文标题】:HowcanIinvokeadifferentconstructorfromaconstructorinc#?[duplicate]【发布时间】:2016-12-0920:51:43【问题描述】:我有以下课程publicclassReportDataSource:IReportDataSourcepublicstringNameget;... 查看详情

将凭据添加到与本地系统帐户不同的帐户

...alsystemaccount【发布时间】:2019-10-2410:35:20【问题描述】:使用章鱼进行部署,触手作为“本地系统帐户”运行我希望触手为不同的帐户添加凭据。但是我没有运气这样做。到目前为止,我尝试创建一个c#程序,它以其他用户身份... 查看详情

C#在不同线程的同一类中的父线程中调用方法

】C#在不同线程的同一类中的父线程中调用方法【英文标题】:C#Callmethodinparentthreadinsameclassindifferentthread【发布时间】:2018-07-1402:25:23【问题描述】:我有一个问题。在一个表单中,我在一个单独的类的线程中调用函数:publicpart... 查看详情