I have the following directory tree:
e:\powershell\services\This-Script-Here-Should-Call-Press any key to continue.ps1
e:\powershell\utils\Press any key to continue.ps1
and now I'd like to call a script named "Press any key to continue.ps1" that sits in the "utils"-folder from a script that I have in the "services"-folder. How do I do that? I cannot figure out the relative path.
I tried to do it this way:
"$ '.\..\utils\Press any key to continue.ps1'"
but it did not work.
You don't need Start-Process. PowerShell scripts can run other scripts. Just put the command that runs the second script as a command in the first script (the same way as you would type it on the PowerShell command line).
To run a script on one or more remote computers, use the FilePath parameter of the Invoke-Command cmdlet. Enter the path and filename of the script as the value of the FilePath parameter. The script must reside on the local computer or in a directory that the local computer can access.
For example, if the file in question lives at absolute path C:\Users\MyUsername\Desktop\test. txt, and I decide that the root directory is C:\Users\MyUsername, the relative path would be Desktop\test. txt, which is what should be stored in the CSV.
Based on what you were doing, the following should work:
& "..\utils\Press any key to continue.ps1"
or
. "..\utils\Press any key to continue.ps1"
(lookup the difference between using &
and .
and decide which one to use)
This is how I handle such situations ( and slight variation to what @Shay mentioned):
$scriptDir = Split-Path -Parent $MyInvocation.MyCommand.Path
$utilsDir = Join-Path -Path $scriptDir -ChildPath ..\utils
& "$utilsDir\Press any key to continue.ps1"
Put the following function in the calling script to get its directory path and join the utils path along with the script name:
# create this function in the calling script
function Get-ScriptDirectory { Split-Path $MyInvocation.ScriptName }
# generate the path to the script in the utils directory:
$script = Join-Path (Get-ScriptDirectory) 'utils\Press any key to continue.ps1'
# execute the script
& $script
To get the current script path $PSScriptRoot variable can be used. for example Following is the structure: solution\mainscript.ps1 solution\secondscriptfolder\secondscript.ps1
#mainscript.ps1
$Second = Join-Path $PSScriptRoot '\secondscriptfolder\secondscript.ps1'
$Second
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With