Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/313.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 如何从PowerShell CmdLet中获取登录用户名_C#_Powershell_Credentials - Fatal编程技术网

C# 如何从PowerShell CmdLet中获取登录用户名

C# 如何从PowerShell CmdLet中获取登录用户名,c#,powershell,credentials,C#,Powershell,Credentials,我已在C#中编写了PowerShell CmdLet。它是从用户名系统下作为Windows服务运行的C#应用程序调用的。调用(服务)应用程序执行新的PSSession(添加用户名为“Joe”的凭据参数),然后执行导入PSSession以创建CmdLet的运行空间 当CmdLet执行时,我可以使用Environment.UserName获取当前用户名,但它是系统(从服务进程)。我想要的是恢复PowerShell会话凭据中提供的用户名(在本例中为“Joe”)。如何在执行C#CmdLet的上下文中恢复

我已在C#中编写了PowerShell CmdLet。它是从用户名系统下作为Windows服务运行的C#应用程序调用的。调用(服务)应用程序执行新的PSSession(添加用户名为“Joe”的凭据参数),然后执行导入PSSession以创建CmdLet的运行空间

当CmdLet执行时,我可以使用Environment.UserName获取当前用户名,但它是系统(从服务进程)。我想要的是恢复PowerShell会话凭据中提供的用户名(在本例中为“Joe”)。如何在执行C#CmdLet的上下文中恢复该凭据

我已经看到了中包含的建议;他们不工作;他们只给我调用进程运行时使用的系统用户名,而不是它为创建PowerShell会话提供的“Joe”凭据


FWIW,PowerShell会话提供了一个connectionuri,在一般情况下,它通常是一个远程系统,但在特定示例中是127.0.0.1(本地主机)。

本例中的问题与PowerShell会话的创建和导入方式有关。导入实际上“以静默方式失败”,因此CmdLet是在进程“本机”上下文中执行的

New PSSession
命令指定了一个配置(
-ConfigurationName MyConfiguration
)。此配置已正确注册,但基本上没有执行任何操作。因此,
Import PSSession
尝试导入包含所需模块的默认会话。这引入了许多冲突,导致导入失败。由于计算机上已经安装了CmdLet(我们正在回送,因为
新PSSession
指定了
-ConnectionUrihttp://127.0.0.1:5985/WSMAN
)它似乎正常工作,因此没有注意到失败的导入。唯一的线索是用户名不一致

通过使用
RestrictedRemoteServer
正确定义配置,问题得以解决:

$sessionConfigurationName = 'MyConfiguration'
$tempFile = $env:TEMP + "\psconfig.pssc"
New-PSSessionConfigurationFile -SessionType RestrictedRemoteServer -ModulesToImport MyModule -Path $tempFile
Register-PSSessionConfiguration -Name $sessionConfigurationName -NoServiceRestart -Path $tempFile
Remove-Item -Path $tempFile

这允许
New PSSession
创建一个会话,该会话可以成功导入而不会发生冲突。生成的会话已在正确的凭据下获取并运行。

请尝试重复问题中的$env:username@ClaudiuA CmdLet是C#;建议的答案是ps脚本。我假设$env:UserName相当于System.Environment.UserName,它给了我“System”(不是我想要的)。我假设[System.Security.Principal.WindowsIdentity]::GetCurrent()。名称是System.Security.Principal.WindowsIdentity.GetCurrent().Name,当我进入远程PSSession时,它也会给我“System”,而不是“Joe”,而
$env:UserName
显示我连接的用户名:
$cred=Get-Credential$sess=New PSSession-ComputerName server.domain.tld-Credential$cred;输入PSSession-会话$sess$env:UserName
我发现了问题。由于无法解决的冲突,导入会话失败。因此,执行CmdLet的会话仍然是调用进程的会话。当我解决冲突时(对实际导入的内容非常有选择性),使用正确的凭据和System.Environment.UserName执行的CmdLet包含预期值。@CRobinson,请将您的发现作为答案发布-这将有助于未来的读者。