I've read several similar posts but they focus on calling a PS script from within another PS script. I can do that and make the other script run, my issue is most likely linked to $MyInvocation when calling a script from another script.
Background
I have a script that half-way through needs to call another script. This other script cannot be a psm1 module because it is used as a standalone script in other processes. I begin the script with
$ScriptDir = (split-path -parent -path $MyInvocation.MyCommand.Path)
Problem
I then run
& "$ScriptDir\Another Script.ps1"
This throws the following error
Set-Location : A positional parameter cannot be found that accepts argument 'C:\Users\MyUser\Desktop\Scripts'.
At C:\Users\MyUser\Desktop\Scripts\Another Script.ps1:30 char:1
+ Set-Location = $ScriptDir
+ ~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidArgument: (:) [Set-Location], ParentContainsErrorRecordException
+ FullyQualifiedErrorId : PositionalParameterNotFound,Microsoft.PowerShell.Commands.SetLocationCommand
Here's the full section of the Another Script.ps1 that is failing
#Requires -RunAsAdministrator
$ErrorActionPreference = "Stop"
$ScriptDir = (split-path -parent -path $MyInvocation.MyCommand.Path)
Set-Location = $ScriptDir
My guess is that the Set-Location does not work because it is currently running a script inside another script. The problem I have is that this part needs to be there in order for Another Script.ps1 to run as a standalone script as well. Are there any workarounds for this, such as ignoring this step if it's run from another script?
References
- https://paulcunningham.dev/powershell-invoke-expressions-spaces-in-path/
- Invoke-Expression: Positional parameter cannot be found that accepts argument /s
- Call PowerShell script PS1 from another PS1 script inside Powershell ISE
- Powershell: A positional parameter cannot be found that accepts argument "xxx"