0

I have a Powershell script that takes two arguments.

param([string]$folder, [string]$filename)

When I open a Powershell shell, navigate to the folder that contains the script, and run it from there, the script is executed correctly:

C:\scriptfolder> ".\script.ps1" "C:\folder for argument" "filename.ext"

When I try to run the script from a different folder, I get an error message:

C:\otherfolder> "C:\scriptfolder\script.ps1" "C:\folder for argument" "filename.ext"

At line:1 char:nn

Unexpected token '"C:\folder for argument"' in expression or statement.

How can I run this script from another folder?

2
  • You need to dot-source the path to the ps1 file . "C:\scriptfolder\script.ps1" "C:\folder for argument" "filename.ext" or use the & call operator Commented Feb 3, 2023 at 12:57
  • That works, so I'd accept that as an answer. Commented Feb 6, 2023 at 8:52

1 Answer 1

1

In order not to leave this question as 'Unanswered', here my comment as answer

There are two ways to do what you want. The first is by using dot-sourcing:

. "C:\scriptfolder\script.ps1" "C:\folder for argument" "filename.ext"

The second method would be by using the `& call operator

& "C:\scriptfolder\script.ps1" "C:\folder for argument" "filename.ext"

The difference between the two methods is that a script that is invoked using dot-sourcing runs in the current scope, while with the second method, using the call operator, scripts and functions run in a child scope.

You can find an excellent explanation in the answer here

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.