【问题标题】:How to call powershell script from other powershell script and script is assigned in the powershell object instead of the file如何从其他powershell脚本调用powershell脚本并且脚本是在powershell对象而不是文件中分配的
【发布时间】:2022-01-24 04:32:50
【问题描述】:

我正在编写一个 PowerShell 脚本,并且我还有另一个 PowerShell 脚本。 我知道,如果它存储在路径中,我们可以使用下面的代码

$scriptPath = "D:\Ashish\powershell\script.ps1"
$argumentList = "asdf fgh ghjk"
$output =Invoke-Expression "& `"$scriptPath`" $argumentList"

但我的 PowerShell 存储在对象而不是文件中。我正在使用下面的代码

$argumentList = "asdf fgh ghjk"
$logPath = "C:\AshishG\powershell\script21.txt"
$x = 'Write-Host "Hello script2" return "script2"' #This is my powershell script
//Write code here to call this script($x) with params and store the return value in the other object and also store the logs in $logpath

一种方法是将 PowerShell 存储到 script.ps1,但我认为,应该有某种方法可以从 PowerShell 对象本身调用它?

请分享您的建议。

【问题讨论】:

    标签: powershell powershell-4.0


    【解决方案1】:

    看来您正在寻找script block

    $argumentList = "asdf fgh ghjk"
    $logPath = "C:\AshishG\powershell\script21.txt"
    $x = {
        param($arguments, $path)
    
        "Arguments: $arguments"
        "Path: $path"
    }
    

    可以使用call operator &:执行脚本块:

    & $x -arguments $argumentList -path $logPath
    

    或者dot sourcing operator .

    . $x -arguments $argumentList -path $logPath
    

    .Invoke(..) method 也可以使用,但是在这种情况下不常用且不推荐使用。更多信息请见this answer

    $x.Invoke($argumentList, $logPath)
    

    另一个选项是调用[scriptblock]::Create(..) 方法,如果脚本存储在字符串中,这是Invoke-Expression which should be avoided. 的推荐替代方法。这也非常有用,例如当我们需要将 function 传递给不同的范围时。感谢@mklement0对此的提醒:)

    $argumentList = "asdf fgh ghjk"
    $logPath = "C:\AshishG\powershell\script21.txt"
    
    $x = @'
    "Arguments: $argumentList"
    "Path: $logPath"
    '@
    
    & ([scriptblock]::Create($x))
    
    # Or:
    $scriptblock = [scriptblock]::Create($x)
    & $scriptblock
    

    【讨论】:

    • 我的 PowerShell 脚本存储在 $x 中,但您已更改它。我不清楚你的逻辑。 powershell 脚本在哪里 [t in this - & $x -arguments $argumentList -path $logPath
    • @AshishGoyanka 我已经添加了 mklement0 的评论,使用 [scriptblock]::Create(),这与您正在做的类似,另一种选择是使用 Invoke-Expression,但我不推荐它。跨度>
    猜你喜欢
    • 1970-01-01
    • 2015-07-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-06-22
    • 2014-02-28
    • 1970-01-01
    相关资源
    最近更新 更多