1

I have a Powershell script to incorporate into an Excel VBA macro. Please reference this question: Powershell Regex: Replace only multiple spaces with tabs

This is the code in question Convert_To_Tab_Delimited.ps1:

gc 'foo.txt'| % { $_ -replace '  +',"`t" } | set-content "<my path>\temp.txt"

I need to get 'foo.txt' to be a VBA variable that I pass to it. Basically a path string that is obtained from a select file dialog in VBA. The Powershell file will be called by this statement:

Shell(“powershell.exe -ExecutionPolicy Unrestricted <pathname>\Convert_To_Tab_Delimited.ps1″, 1)

Is there a way to pass a string variable as an argument to the called Powershell script? Any assistance with this would be greatly appreciated!

1 Answer 1

1

You just need to define parameters at the top of your script:

param([string]$path)
$content = [IO.File]::ReadAllText($path)
# etc.

In VBA, you need to pass the parameter:

Shell("powershell.exe -ExecutionPolicy Unrestricted -File <pathname>\Convert_To_Tab_Delimited.ps1 -path """ & pathVariable & """", 1)
Sign up to request clarification or add additional context in comments.

9 Comments

Wow, I have some reading to do! So you'd use an ampersand and not a '+' sign in the VBA code?
@LawrenceKnowlton I'll admit I haven't done VBA in a long time and I had to double-check that. I guess either one works here. This answer suggests you would want to prefer &:stackoverflow.com/a/1727709/517852
Ah, great! Sounds like it's easier to avoid issues by using & to concatenate strings! Thank you!
Any ideas why I can't seem to pass the parameter, it's like the PS script runs but doesn't do anything.
@LawrenceKnowlton Two ideas: 1) Bypass is not a valid value for ExecutionPolicy. I think you mean Unrestricted. 2) If you are passing a path that contains spaces you will need to quote it. I have made edits to my answer.
|

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.