0

I am writing a PowerShell script and I have another PowerShell script. I know, we can use below code if it is stored in the path

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

but my PowerShell is stored in the object instead of a file. I am using the below code

$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

The one way could be to store the PowerShell to the script.ps1 but I think, there should be some way to call it from the PowerShell object itself?

Please share your suggestions.

Ashish Goyanka
  • 207
  • 3
  • 11

1 Answers1

1

Seems like you're looking for a script block:

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

    "Arguments: $arguments"
    "Path: $path"
}

A script block can be executed using the call operator &:

& $x -arguments $argumentList -path $logPath

Or the dot sourcing operator .:

. $x -arguments $argumentList -path $logPath

.Invoke(..) method works too however it's not commonly used and not recommended in this context. See this answer for more information:

$x.Invoke($argumentList, $logPath)

Yet another option is to call the [scriptblock]::Create(..) method, if the script is stored in strings this is the recommended alternative over Invoke-Expression which should be avoided.. This is also very useful for example when we need to pass a function to a different scope. Thanks @mklement0 for the reminder on this one :)

$argumentList = "asdf fgh ghjk"
$logPath = "C:\AshishG\powershell\script21.txt"

$x = @'
"Arguments: $argumentList"
"Path: $logPath"
'@

& ([scriptblock]::Create($x))

# Or:
$scriptblock = [scriptblock]::Create($x)
& $scriptblock
Santiago Squarzon
  • 41,465
  • 5
  • 14
  • 37
  • my PowerShell script is stored in $x but you have changed it. I am not clear about your logic. where is the powershell scrip[t in this - & $x -arguments $argumentList -path $logPath – Ashish Goyanka Dec 23 '21 at 06:15
  • @AshishGoyanka I have added mklement0's comment, using `[scriptblock]::Create()` which is something similar to what you're doing, the other alternative would be to use `Invoke-Expression` but I would not recommend it. – Santiago Squarzon Dec 23 '21 at 13:30