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


10

你好堆栈社区:)

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

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

有一个类似的问题Link。但是答案是使用文件作为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参数传递给它。

先感谢您!


如果这仅与访问冲突有关: 为每次调用创建唯一的文件名将解决您的问题,对吗?
mklement0

1
@ mklement0(如果这是唯一的方法),我将使用该解决方案进行堆叠。只是生成随机文件名,检查此类文件是否存在...我将从Java代码中执行6到10个脚本,每次我使用或其他人使用我的应用程序时,它都需要6到10个文件。因此,它也与性能有关
Dmytro

Answers:


2

注意:

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

  • 调用另一个PowerShell实例并将其输出捕获为丰富对象(有限制),请参阅底部的变体解决方案,或考虑Mathias R. Jessen的有用答案,该答案使用PowerShell SDK

这里有一个验证的概念基础上直接使用的System.Diagnostics.ProcessSystem.Diagnostics.ProcessStartInfo.NET类型来捕获过程输出在内存中(如你的问题说,Start-Process是不是一种选择,因为它仅支持捕获输出文件,如图这个答案) :

注意:

  • 由于以其他用户身份运行,因此仅Windows(自.NET Core 3.1起)支持此功能,但在两个PowerShell版本中均支持。

  • 由于需要以其他用户身份运行并且需要捕获输出,.WindowStyle因此不能用于运行隐藏的命令(因为使用.WindowStylerequire .UseShellExecute$true,这与这些要求不兼容);但是,由于捕获了所有输出,因此设置.CreateNoNewWindow$true有效会导致隐藏执行。

# 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以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

上面的输出类似于以下内容,显示by 的[datetime]instance(System.DateTimeGet-Date已反序列化为:

Running `Get-Date` as user jdoe yielded:

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

as data type:
System.DateTime

5

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

两种选择:

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

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

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

$strings 将包含结果。


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

您可以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"}

0

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

1
我必须把这份遗嘱传给别人……
Dmytro

更新了相关部分。
thepip3r

需要说明的是:目的不仅是为了传递凭据,而是以凭据标识的用户身份运行
mklement0

1
@ mklement0,感谢您的澄清,因为对于所问问题的不同迭代,这一点我一点都不明白。
thepip3r

0

您可以执行以下操作来将参数传递给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

1
主要目标是将所有条件合并为1个执行。我必须传递参数并传递凭据!
Dmytro

“将所有条件合并为1个执行”是什么意思。我不认为您可以像以前那样用“-”符号添加参数。.我认为您必须在目标脚本上重新格式化字符串
Andy McRae

我必须使用参数执行一些PS1文件,并将参数传递-Credential $credentials给此执行,然后将其输出到变量中。ps1。我执行的脚本在结尾处抛出一个单字字符串。只要看看我的操作方式即可,Start-process但此功能不会产生输出
Dmytro

我认为powershell不允许您传递类似$ arguments =“ C:\ .. \ script1.ps1” +“ -ClientName” + $ DeviceName这样的参数。您可能应该考虑删除“-”
Andy McRae

1
那个蜜蜂说。Start-Process确实使用参数和凭据执行脚本,但是它不会将此输出保存到变量中。如果我试图访问$output变量,则为NULL。来自@ mklement0的另一个想法是将输出保存到文件中。但就我而言,它将在一个地方引起大量文件。所有内容都是由具有不同脚本的不同用户创建的
Dmytro
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.