Dmy*_*tro 10 powershell runas start-process
你好堆栈社区:)
我有一个简单的目标。我想从另一个 Powershell 脚本启动一些 PowerShell 脚本,但有 3 个条件:
有一个类似的问题链接。但答案是使用文件作为在 2 个 PS 脚本之间进行通信的一种方式。我只是想避免访问冲突。@Update:主脚本将启动其他几个脚本。因此,如果要同时从多个用户执行执行,则文件解决方案可能会很棘手。
Script1.ps1是应该有字符串作为输出的脚本。(需要说明的是,这是一个虚构的脚本,真实的脚本有 150 行,所以我只是想举个例子)
param(
[String]$DeviceName
)
#Some code that needs special credentials
$a = "Device is: " + $DeviceName
$a
Run Code Online (Sandbox Code Playgroud)
ExecuteScripts.ps1应该调用具有上述 3 个条件的那个
我尝试了多种解决方案。这一个例如:
$arguments = "C:\..\script1.ps1" + " -ClientName" + $DeviceName
$output = Start-Process powershell -ArgumentList $arguments -Credential $credentials
$output
Run Code Online (Sandbox Code Playgroud)
我没有得到任何输出,我不能只是调用脚本
&C:\..\script1.ps1 -ClientName PCPC
Run Code Online (Sandbox Code Playgroud)
因为我无法将-Credential参数传递给它..
先感谢您!
Start-Process将是我从 PowerShell 调用 PowerShell 的最后选择- 特别是因为所有 I/O 都变成字符串而不是(反序列化)对象。
两种选择:
如果针对本地机器的远程会话(不幸的是仅限于本地管理员)是一个选项,我肯定会选择Invoke-Command:
$strings = Invoke-Command -FilePath C:\...\script1.ps1 -ComputerName localhost -Credential $credential
Run Code Online (Sandbox Code Playgroud)
$strings 将包含结果。
您可以Invoke-Command通过以下方式启动进程外运行空间来编写自己的“仅限本地”:
PowerShellProcessInstance在不同的登录名下创建一个我在下面汇总了这样一个函数,请参阅内联注释以进行演练:
function Invoke-RunAs
{
[CmdletBinding()]
param(
[Alias('PSPath')]
[ValidateScript({Test-Path $_ -PathType Leaf})]
[Parameter(Position = 0, Mandatory = $true, ValueFromPipeline = $true, ValueFromPipelineByPropertyName = $true)]
[string]
${FilePath},
[Parameter(Mandatory = $true)]
[pscredential]
[System.Management.Automation.CredentialAttribute()]
${Credential},
[Alias('Args')]
[Parameter(ValueFromRemainingArguments = $true)]
[System.Object[]]
${ArgumentList},
[Parameter(Position = 1)]
[System.Collections.IDictionary]
$NamedArguments
)
begin
{
# First we set up a separate managed powershell process
Write-Verbose "Creating PowerShellProcessInstance and runspace"
$ProcessInstance = [System.Management.Automation.Runspaces.PowerShellProcessInstance]::new($PSVersionTable.PSVersion, $Credential, $null, $false)
# And then we create a new runspace in said process
$Runspace = [runspacefactory]::CreateOutOfProcessRunspace($null, $ProcessInstance)
$Runspace.Open()
Write-Verbose "Runspace state is $($Runspace.RunspaceStateInfo)"
}
process
{
foreach($path in $FilePath){
Write-Verbose "In process block, Path:'$path'"
try{
# Add script file to the code we'll be running
$powershell = [powershell]::Create([initialsessionstate]::CreateDefault2()).AddCommand((Resolve-Path $path).ProviderPath, $true)
# Add named param args, if any
if($PSBoundParameters.ContainsKey('NamedArguments')){
Write-Verbose "Adding named arguments to script"
$powershell = $powershell.AddParameters($NamedArguments)
}
# Add argument list values if present
if($PSBoundParameters.ContainsKey('ArgumentList')){
Write-Verbose "Adding unnamed arguments to script"
foreach($arg in $ArgumentList){
$powershell = $powershell.AddArgument($arg)
}
}
# Attach to out-of-process runspace
$powershell.Runspace = $Runspace
# Invoke, let output bubble up to caller
$powershell.Invoke()
if($powershell.HadErrors){
foreach($e in $powershell.Streams.Error){
Write-Error $e
}
}
}
finally{
# clean up
if($powershell -is [IDisposable]){
$powershell.Dispose()
}
}
}
}
end
{
foreach($target in $ProcessInstance,$Runspace){
# clean up
if($target -is [IDisposable]){
$target.Dispose()
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
然后像这样使用:
$output = Invoke-RunAs -FilePath C:\path\to\script1.ps1 -Credential $targetUser -NamedArguments @{ClientDevice = "ClientName"}
Run Code Online (Sandbox Code Playgroud)
笔记:
以下解决方案适用于任何外部程序,并且始终将输出捕获为文本。
要调用另一个 PowerShell 实例并将其输出捕获为丰富对象(有限制),请参阅底部部分中的变体解决方案或考虑Mathias R. Jessen 的有用答案,该答案使用PowerShell SDK。
这是基于直接使用System.Diagnostics.Process和System.Diagnostics.ProcessStartInfo.NET 类型来捕获内存中的进程输出的概念验证(如您的问题中所述,Start-Process这不是一个选项,因为它仅支持捕获文件中的输出,如本答案所示) :
笔记:
由于以不同用户身份运行,因此仅在 Windows上受支持(从 .NET Core 3.1 开始),但在两个 PowerShell 版本中均受支持。
由于需要以不同用户身份运行并需要捕获输出,因此不能用于隐藏.WindowStyle运行命令(因为使用需要be ,这与这些要求不兼容);然而,由于所有输出都被捕获,设置为有效会导致隐藏执行。.WindowStyle.UseShellExecute$true.CreateNoNewWindow$true
下面仅捕获标准输出输出。如果您也想捕获stderr输出,则需要通过events捕获它,因为使用$ps.StandardError.ReadToEnd()side$ps.StandardOutput.ReadToEnd()可能会导致死锁。
# Get the target user's name and password.
$cred = Get-Credential
# Create a ProcessStartInfo instance
# with the relevant properties.
$psi = [System.Diagnostics.ProcessStartInfo] @{
# For demo purposes, use a simple `cmd.exe` command that echoes the username.
# See the bottom section for a call to `powershell.exe`.
FileName = 'cmd.exe'
Arguments = '/c echo %USERNAME%'
# Set this to a directory that the target user
# is permitted to access.
WorkingDirectory = 'C:\' #'
# Ask that output be captured in the
# .StandardOutput / .StandardError properties of
# the Process object created later.
UseShellExecute = $false # must be $false
RedirectStandardOutput = $true
RedirectStandardError = $true
# Uncomment this line if you want the process to run effectively hidden.
# CreateNoNewWindow = $true
# Specify the user identity.
# Note: If you specify a UPN in .UserName
# (user@doamin.com), set .Domain to $null
Domain = $env:USERDOMAIN
UserName = $cred.UserName
Password = $cred.Password
}
# Create (launch) the process...
$ps = [System.Diagnostics.Process]::Start($psi)
# Read the captured standard output.
# By reading to the *end*, this implicitly waits for (near) termination
# of the process.
# Do NOT use $ps.WaitForExit() first, as that can result in a deadlock.
$stdout = $ps.StandardOutput.ReadToEnd()
# Uncomment the following lines to report the process' exit code.
# $ps.WaitForExit()
# "Process exit code: $($ps.ExitCode)"
"Running ``cmd /c echo %USERNAME%`` as user $($cred.UserName) yielded:"
$stdout
Run Code Online (Sandbox Code Playgroud)
上面的结果类似于以下内容,表明该进程已使用给定的用户身份成功运行:
# Get the target user's name and password.
$cred = Get-Credential
# Create a ProcessStartInfo instance
# with the relevant properties.
$psi = [System.Diagnostics.ProcessStartInfo] @{
# For demo purposes, use a simple `cmd.exe` command that echoes the username.
# See the bottom section for a call to `powershell.exe`.
FileName = 'cmd.exe'
Arguments = '/c echo %USERNAME%'
# Set this to a directory that the target user
# is permitted to access.
WorkingDirectory = 'C:\' #'
# Ask that output be captured in the
# .StandardOutput / .StandardError properties of
# the Process object created later.
UseShellExecute = $false # must be $false
RedirectStandardOutput = $true
RedirectStandardError = $true
# Uncomment this line if you want the process to run effectively hidden.
# CreateNoNewWindow = $true
# Specify the user identity.
# Note: If you specify a UPN in .UserName
# (user@doamin.com), set .Domain to $null
Domain = $env:USERDOMAIN
UserName = $cred.UserName
Password = $cred.Password
}
# Create (launch) the process...
$ps = [System.Diagnostics.Process]::Start($psi)
# Read the captured standard output.
# By reading to the *end*, this implicitly waits for (near) termination
# of the process.
# Do NOT use $ps.WaitForExit() first, as that can result in a deadlock.
$stdout = $ps.StandardOutput.ReadToEnd()
# Uncomment the following lines to report the process' exit code.
# $ps.WaitForExit()
# "Process exit code: $($ps.ExitCode)"
"Running ``cmd /c echo %USERNAME%`` as user $($cred.UserName) yielded:"
$stdout
Run Code Online (Sandbox Code Playgroud)
由于您正在调用另一个PowerShell实例,因此您可能希望利用PowerShell CLI的能力以 CLIXML 格式表示输出,这允许将输出反序列化为丰富的对象,尽管类型保真度有限,如此相关答案中所述。
# Get the target user's name and password.
$cred = Get-Credential
# Create a ProcessStartInfo instance
# with the relevant properties.
$psi = [System.Diagnostics.ProcessStartInfo] @{
# Invoke the PowerShell CLI with a simple sample command
# that calls `Get-Date` to output the current date as a [datetime] instance.
FileName = 'powershell.exe'
# `-of xml` asks that the output be returned as CLIXML,
# a serialization format that allows deserialization into
# rich objects.
Arguments = '-of xml -noprofile -c Get-Date'
# Set this to a directory that the target user
# is permitted to access.
WorkingDirectory = 'C:\' #'
# Ask that output be captured in the
# .StandardOutput / .StandardError properties of
# the Process object created later.
UseShellExecute = $false # must be $false
RedirectStandardOutput = $true
RedirectStandardError = $true
# Uncomment this line if you want the process to run effectively hidden.
# CreateNoNewWindow = $true
# Specify the user identity.
# Note: If you specify a UPN in .UserName
# (user@doamin.com), set .Domain to $null
Domain = $env:USERDOMAIN
UserName = $cred.UserName
Password = $cred.Password
}
# Create (launch) the process...
$ps = [System.Diagnostics.Process]::Start($psi)
# Read the captured standard output, in CLIXML format,
# stripping the `#` comment line at the top (`#< CLIXML`)
# which the deserializer doesn't know how to handle.
$stdoutCliXml = $ps.StandardOutput.ReadToEnd() -replace '^#.*\r?\n'
# Uncomment the following lines to report the process' exit code.
# $ps.WaitForExit()
# "Process exit code: $($ps.ExitCode)"
# Use PowerShell's deserialization API to
# "rehydrate" the objects.
$stdoutObjects = [Management.Automation.PSSerializer]::Deserialize($stdoutCliXml)
"Running ``Get-Date`` as user $($cred.UserName) yielded:"
$stdoutObjects
"`nas data type:"
$stdoutObjects.GetType().FullName
Run Code Online (Sandbox Code Playgroud)
上面的输出类似于以下内容,表明[datetime]实例 ( System.DateTime) 输出已Get-Date被反序列化:
Running `cmd /c echo %USERNAME%` as user jdoe yielded:
jdoe
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4129 次 |
| 最近记录: |