1

I have Powershell ISE open as Administrator. When I execute the script from the desktop (e.g. C:\Users\myUser\Desktop\CompareScripts\runCompareScript.ps1), the script works fine. However, when I execute from the C:\CompareScripts\runCompareScript.ps1 the script changes the file path to C:\Windows\system32\runCompareScript.ps1. Why is this occurring and how can I prevent this from happening?

Note: This is happening during the execution of a invoke-sqlcmd statement.

enter image description here

1
  • 2
    It is not clear how you execute your script and it shouldn't change to C:\windows..., you can use $pwd for the current directory, to access data files in the user directory use: $env:UserProfile\Desktop\CompareScripts\foo.sql You may need to show more of your script for us to see what's going wrong. Commented Aug 3, 2017 at 2:43

1 Answer 1

2

The current working directory is changing as you change contexts. Use the absolute file path.

Invoke-Sqlcmd -InputFile "C:\Users\myUser\Desktop\CompareScripts\---.sql" 
Sign up to request clarification or add additional context in comments.

4 Comments

Why can't I do something a little more dynamic? Right now I'm using the following $rootDir = split-path -parent $MyInvocation.MyCommand.Definition; to get the current working directory. I know the statement works, because the extractRSPath in the above screenshot is correct yet the error thrown is not.
If you put a breakpoint on line 128 and run $extractPath when execution pauses, I guarantee the output is 'C:\Windows\system32\---.sql'. I can't explain why that is without seeing the script. With the information available, the best solution is to use an absolute path.
@PhiL $rootDir is the location of your script, not your working directory. Compare the output of $rootDir and $PWD.Path. You can build an absolute path for the invoked script like this: Join-Path $rootDir 'something.sql'.
Thanks guys!. When Powershell ISE is initially opened the default working directory is C:\Windows\system32 and the statement that was causing the issue was in terms of a relative path (e.g. $sqlPath = $sqlScript). To resolve the issue, I changed it to $sqlPath = $rootDir + $sqlScript.

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.