2

I have a power shell script which has include script in it as below.

. "$PSScriptRoot\CheckPermissions.ps1"

When the script is invoked from c#, I am getting this error

{The term '\CheckPermissions.ps1' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again.}

The script works fine when run from PS window.

Is not $PSScriptRoot variable available when script is run from c#?

2 Answers 2

2

You could try using the following to get the script directory:

$scriptDir = Split-Path $script:MyInvocation.MyCommand.Path

Note that the folder path returned will end with a backslash (\).

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

3 Comments

Is not working for me. Actually $PSScriptRoot this works when the script is run directly from PS window and only it is not working when the script is called from c#.
What version of PowerShell is your C# script running? As $PSScriptRoot only works in later versions of PowerShell, you can check by outputting the host info to a text file e.g. host > "C:\HostInfo.txt"
This works perfectly when run from powershell window. So version is not a problem. My version of PS is 3.
0

Try the below code

$scriptpath = "your second file path"
$psContent = @(Get-Content $scriptPath)
[string]$psCmd = $psContent -join "`n"
$secondscriptoutput = iex $psCmd
$secondscriptoutput #output returned by second file

Myinvocation will not work when ps scripts are invoked from c# code. Please mark this as answer if it works for you. Thanks!

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.