使用参数和凭据从 PowerShell 启动 .ps1 脚本并使用变量获取输出

Starting .ps1 Script from PowerShell with Parameters and Credentials and getting output using variable

Hello Stack 社区 :)

我有一个简单的目标。我想从另一个 Powershell 脚本启动一些 PowerShell 脚本,但有 3 个条件:

  1. 我必须传递凭据(执行连接到具有特定用户的数据库)
  2. 它必须带一些参数
  3. 我想将输出传递给一个变量

有一个类似的问题。但答案是使用文件作为 2 PS 脚本之间的通信方式。我只是想避免访问冲突。 @Update:主脚本将启动其他几个脚本。所以文件的解决方案可能会很棘手,如果执行将同时从多个用户执行。

Script1.ps1 是应该将字符串作为输出的脚本。 (说明一下,这是一个虚构的脚本,真实的有150行,所以我只是想做个例子)

param(  
[String]$DeviceName
)
#Some code that needs special credentials
$a = "Device is: " + $DeviceName
$a

ExecuteScripts.ps1 应该用上面提到的 3 个条件调用那个

我尝试了多种解决方案。例如这个:

$arguments = "C:\..\script1.ps1" + " -ClientName" + $DeviceName
$output = Start-Process powershell -ArgumentList $arguments -Credential $credentials
$output 

我没有从中得到任何输出,我不能只用

调用脚本
&C:\..\script1.ps1 -ClientName PCPC

因为我不能给它传递-Credential参数..

提前致谢!

rcv.ps1

param(
    $username,
    $password
)

"The user is:  $username"
"My super secret password is:  $password"

从另一个脚本执行:

.\rcv.ps1 'user' 'supersecretpassword'

输出:

The user is:  user
My super secret password is:  supersecretpassword

您可以执行以下操作以将参数传递给 ps1 脚本。

第一个脚本可以是 origin。ps1 我们写的地方:

& C:\scripts\dest.ps1 Pa$$w0rd parameter_a parameter_n

目标脚本dest.ps1可以有以下代码来捕获变量

$var0 = $args[0]
$var1 = $args[1]
$var2 = $args[2]
Write-Host "my args",$var0,",",$var1,",",$var2

结果会是

my args Pa$$w0rd, parameter_a, parameter_n

注:

  • 以下解决方案适用于任何外部程序,并且总是将输出捕获为文本.

  • 调用另一个 PowerShell 实例捕获其输出as rich objects(有限制),请参阅底部的变体解决方案或考虑 , which uses the PowerShell SDK.

这是基于 直接使用 System.Diagnostics.Process and System.Diagnostics.ProcessStartInfo .NET types to capture process output in memory (as stated in your question, Start-Process is not an option, because it only supports capturing output in files, as shown in 的概念验证:

注:

  • 由于 运行ning 作为不同的用户,仅 Windows 支持此功能(自 .NET Core 3.1 起),但在两个 PowerShell 版本中都有。

  • 由于需要 运行 作为不同的用户并需要捕获输出,.WindowStyle 不能用于 运行 命令 hidden(因为使用.WindowStyle需要.UseShellExecute$true,这与这些要求不兼容);但是,由于所有输出都被 捕获 ,将 .CreateNoNewWindow 设置为 $true 会有效地导致隐藏执行。

  • 下面仅捕获了 stdout 输出。如果你也想捕获 stderr 输出,你需要通过 events 捕获它,因为使用 $ps.StandardError.ReadToEnd()$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

上面的结果类似于下面的内容,表明进程成功 运行 使用给定的用户身份:

Running `cmd /c echo %USERNAME%` as user jdoe yielded:
jdoe

由于您正在调用另一个 PowerShell 实例,您可能希望利用 PowerShell CLI's ability to represent output in CLIXML format, which allows deserializing the output into rich objects, albeit with limited type fidelity, as explained in .

# 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

上面的输出类似于下面的内容,表明 Get-Date 输出的 [datetime] 实例 (System.DateTime) 被反序列化为:

Running `Get-Date` as user jdoe yielded:

Friday, March 27, 2020 6:26:49 PM

as data type:
System.DateTime

Start-Process 将是我从 PowerShell 调用 PowerShell 的 最后选择 - 特别是因为所有 I/O 都变成字符串而不是(反序列化)对象。

两种选择:

1。如果用户是本地管理员并且配置了 PSRemoting

如果可以选择针对本地计算机的远程会话(不幸的是仅限于本地管理员),我肯定会选择 Invoke-Command:

$strings = Invoke-Command -FilePath C:\...\script1.ps1 -ComputerName localhost -Credential $credential

$strings 将包含结果。


2。如果用户不是目标系统的管理员

您可以通过以下方式启动进程外运行空间来编写自己的 "local-only Invoke-Command":

  1. 在不同的登录名下创建 PowerShellProcessInstance
  2. 正在上述进程中创建运行空间
  3. 在上述进程外运行空间中执行您的代码

我在下面整理了这样一个函数,请参阅内联评论以了解演练:

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()
            }
        }
    }
}

然后像这样使用:

$output = Invoke-RunAs -FilePath C:\path\to\script1.ps1 -Credential $targetUser -NamedArguments @{ClientDevice = "ClientName"}