howto pass procesname parameter to powershell form vbs script - powershell

If have created a VBS script that watches for new created processes like notepad.exe or calc.exe. When a new notepad or calc proces is found i like to do something in powershell with the found procesname.
The VBS script i created works fine when I manually edit the procesname in the VBS file, but when i try to use/pass the procesname form vbs (strName) to powershell I expect to see the procesname (notepad.exe), but instead the powershell window shows "strName".
I've been all over the internet to find a solution, without result.
My VBS file [start.vbs]
source: http://blogs.technet.com/b/heyscriptingguy/archive/2009/11/02/hey-scripting-guy-november-1-2009.aspx
arrProcesses = Array("calc.exe","notepad.exe")
strComputer = "."
Set objWMIService = GetObject("winmgmts:\\" & strComputer & "\root\cimv2")
i = 0
Set colMonitoredProcesses = objWMIService. ExecNotificationQuery _
("Select * From __InstanceCreationEvent Within 5 Where TargetInstance ISA 'Win32_Process'")
Do While i = 0
Set objLatestProcess = colMonitoredProcesses.NextEvent
strProcess = LCase(objLatestProcess.TargetInstance.Name)
For Each strName in arrProcesses
If strName = strProcess Then
''Run Powershell file
'source: https://stackoverflow.com/questions/19156178/passing-arguments-to-powershell
Set WshShell = CreateObject("WScript.Shell")
''this works great
WshShell.Run ("Powershell.exe -file .\GetParamFromVBS.ps1 ""notepad.exe"" ")
'this doesnt
WshShell.Run ("Powershell.exe -file .\GetParamFromVBS.ps1 ""strName"" ")
'OR
'Trying to work arround it, with no result :(
RUNPSVAR="(" + """" +"Powershell.exe -file .\GetParamFromVBS.ps1 & """"" +strName +"""""" +""& " " +"""" +")"
wscript.Echo RUNPSVAR
WshShell.Run ("Powershell.exe -file .\GetParamFromVBS.ps1 ""RUNPSVAR"" ")
End If
Next
Loop
My Powershell File [GetParamFromVBS.ps1]
source: How to pass command-line arguments to a PowerShell ps1 file
param($p1, $p2, $p3, $p4)
$Script:args=""
write-host "Num Args: " $PSBoundParameters.Keys.Count
foreach ($key in $PSBoundParameters.keys) {
$Script:args+= "`$$key=" + $PSBoundParameters["$key"] + " "
}
write-host $Script:args
pause
Anyone any ideas?

Change:
WshShell.Run("Powershell.exe -file .\GetParamFromVBS.ps1 ""strName"" ")
To:
WshShell.Run("Powershell.exe -file .\GetParamFromVBS.ps1 '" & strName & "'")

Variables aren't string literals.
So something like this
a = "a string literal" & aVariableContainingAString

Related

Powershell: Function Prompt In Ps1 Script

Want to pull off something similar to " set /p variable = x " from batch.
How can we make this happen in PS1?
Script example that im using
Function Prompt { 'PS' + $x + '>' }
The equivalent to set /p in PowerShell would be Read-Host:
$value = Read-Host "Give me some input"
The host application (eg. powershell.exe) will now prompt the user for input with the caption Give me some input:, and the result will be stored in $value

How to call a powershell script in vbscript?

I'm trying to call a powershell script in-between one of my project steps in Visual Build.
I've created a new script within visual build and having that call my powershell script.
I selected vbscript and this is the code within the script:
Dim paths, source1
paths = "C:\Dev\"
source1 = "\\10.156.3.14\win"
sCmd = "powershell.exe -noexit -ExecutionPolicy Unrestricted -file C:\Dev\downloadfiles.ps1 -target """ & paths & """ -source """ & source1 & """"
Set xShell = CreateObject("Wscript.Shell")
rReturn = xShell.Run(sCmd, 0, true)
The script timeouts my build.
The powershell script works fine when ran through the console.
Is there something I'm missing?
download.files.ps1 paramaters:
param (
[string[]]$target,
[string[]]$source
)
Additionally is there any way I could see the console output whilst it's running. Even with "-noexit" I'm seeing nothing.
Update --
The first part of the script runs and returns some of the relevant files.
Although the part that takes in the parameters are not functioning.
This seems to be the better alternative as the script is now taking in parameters :
Set objShell = CreateObject("Wscript.Shell")
objShell.run("powershell.exe -noexit -ExecutionPolicy Unrestricted -file .\downloadfiles.ps1 -target """ & paths & """ -source """ & source1 & """")
Follow up question. How would I go about passing in a string arrray through the vbscript call?
e.g
$target = #('c:\dev','d:\lib')
When using -File, I'm afraid all array elements in $target will be forwarded to the PowerShell script as a single string.
Try
VbScript
Option Explicit
'I hate writing """something""" or Chr(34) & "something" & Chr(34)
'all the time, so I use this little helper function
Private Function Quote(text)
Quote = Chr(34) & text & Chr(34)
End Function
Dim paths, source1, script, sCmd, objShell
'join the quoted path elements with a semi-colon
paths = Join(Array(Quote("C:\Dev"), Quote("D:\lib")), ";")
source1 = Quote("\\10.156.3.14\win")
script = Quote("D:\Test\downloadfiles.ps1")
sCmd = "powershell.exe -NoExit -NoLogo -ExecutionPolicy Unrestricted -File " & script & " -target " & paths & " -source " & source1
Set objShell = CreateObject("Wscript.Shell")
objShell.run(sCmd)
Test with PowerShell
downloadfiles.ps1
param (
[string[]]$target,
[string[]]$source
)
$target = $target | ForEach-Object { $_ -split ';' }
$source = $source | ForEach-Object { $_ -split ';' }
Write-Host "Elements in target: $($target.Count)"
Write-Host "Elements in source: $($source.Count)"
Write-Host
for ($i = 0; $i -lt $target.Count; $i++) {
'$target[{0}]: {1}' -f $i, $target[$i]
}
Write-Host
for ($i = 0; $i -lt $source.Count; $i++) {
'$source[{0}]: {1}' -f $i, $source[$i]
}
Output in PowerShell console:
Elements in target: 2
Elements in source: 1
$target[0]: C:\Dev
$target[1]: D:\lib
$source[0]: \\10.156.3.14\win

How to get powershell to output variable with quotes around it

Despite going over the documentation on single and double quotes using 'about_quoting_rules', I can't seem to get the output I'm looking for.
A little backstory:
I have an excel doc and I'm using powershell to create a foreach over every entry. This, in turn, is being used to generate a robocopy command to kick off a sync job.
The part of my script that's pertinent to this is below:
Foreach($script in $roboSource)
{
$StandardSwitches = "/copy:DAT /s /dcopy:DAT /V /L"
$log = "/log:`"$($logPath)$($logFileName)`"" #`
$FileSource = "$($script.a)"
$FileDestination = "$($script.a)"
$RoboArgs = "I:\" + $FileSource + " " + "Z:\" + $FileDestination + " " + $StandardSwitches + " " + $log
}
So, right now, $RoboArgs outputs this:
I:\XXXXX\XXXXX\X\XXXXXXX\XXXXX\XXXX Z:\XXXXX\XXXXX\X\XXXXXXX\XXXXX\XXXX /copy:DAT /s /dcopy:DAT /V /L /log:"C:\XXXXX\XXXXX\X\XXXXXXX\XXXXX\XXXX"
What I need $RoboArgs to output is this:
"I:\XXXXX\XXXXX\X\XXXXXXX\XXXXX\XXXX" "Z:\XXXXX\XXXXX\X\XXXXXXX\XXXXX\XXXX" /copy:DAT /s /dcopy:DAT /V /L /log:"C:\XXXXX\XXXXX\X\XXXXXXX\XXXXX\XXXX"
I've tried adding the backticks to the string, and encapsulating the string and variable together:
$RoboArgs = `""I:\" + $FileSource`"" + " " + "Z:\" + $FileDestination + " " + $StandardSwitches + " " + $log
But regardless of what I try, nothing is resulting in the output that I'm looking for. Any nudge in the right direction would be very helpful and appreciated!
In Powershell ` followed by quotes works, like '\' in other languages:
For example:
"`"toto`""
prints
"toto"
I suggest using PowerShell's string-formatting operator, -f:
$RoboArgs = '"I:\{0}" "Z:\{1}" {2} {3} {4}' -f
$FileSource, $FileDestination, $StandardSwitches, $log
Using '...' (single-quoting) as the delimiters allows you to embed " instances as-is.
{0} is a placeholder for the 1st RHS operand, {1} for the 2nd, and so on.
Try delimiting your string with single quotes. Any double qoutes inside will be preserved in the resulting string.
Example:
$stringWithQuotes = '"' + (pwd) + '"'
And you can also do it the other way around if you want single quotes in your string:
$stringWithQuotes = "'" + (pwd) + "'"

How to return PowerShell variable to VBScript

I have a vbscript to call a PowerShell script in hopes of returning the PowerShell output to an HTA (HTML Application) GUI. Right now I just want to see if I can return the PowerShell output into a MsgBox in the vbscript. I am not having much luck with this.
VBScript Code:
Set shell = CreateObject("WScript.Shell")
return = shell.Run("powershell.exe -executionpolicy bypass -noprofile -file pathToScript\PowerShellToVBA.ps1", , true)
MsgBox return
PowerShell Code:
Clear-Host
return 50
I am trying to keep the return value extremely simple until it works. With this, I would expect the MsgBox to return '50', however it is returning '0' instead. Any ideas what im doing wrong?
I think you just want the exit command to get the return value:
VBScript
pscommand = ".\myscript.ps1; exit $LASTEXITCODE"
cmd = "powershell.exe -noprofile -command " & pscommand
Set shell = CreateObject("WScript.Shell")
rv = shell.Run(cmd, , True)
MsgBox "PowerShell returned: " & rv, vbSystemModal
Powershell
exit 50;
EDIT #1
Or if you want to grab a return string:
VBScript
pscommand = ".\myscript2.ps1"
cmd = "powershell.exe -noprofile -command " & pscommand
Set shell = CreateObject("WScript.Shell")
Set executor = shell.Exec(cmd)
executor.StdIn.Close
MsgBox executor.StdOut.ReadAll
Powershell
Write-Output '***SUCCESS***';
As a followup, using the VBScript above to output a string. In your PS script if you use eg
write-host "Error: some specific thing happened"
to set various error or success messages the
MsgBox executor.StdOut.ReadAll
will display all of what you write via write-host.
A helpful way to display the outcome of the PS script to your VBA user.
Just FYI.

How to pass ADS (Arguments with dynamic strings) which can have spaces from VBscript to Powershell

I wanted to know if it is possible to pass arguments to powershell via VBscript.
Here is my code and my investigation on this topic so far.
VBscript:
Dim pathvalue (pathvalue will dynamic path, which may have spaces in it. lets say path is "\\Server\search\File in some folder\Stack Overflow\")
sCmd = "powershell.exe -ExecutionPolicy ByPass -noexit -File \\server\Support\abhishek\Automation\SearchUtility.ps1 -Inputs " & PathValue
Set oShell = CreateObject("Wscript.Shell")
iResult = oShell.Run(sCmd, 1, true)
PS1.
Param([String] $Inputs)
$FolderPath = $Inputs;
echo "$FolderPath";
Expected result :
\\Server\search\File in some folder\Stack Overflow\
Actual Result :
\\Server\search\File
I tried different methods to pass the arguments ex. by putting it in single quotes, by putting 3 double Quotes but still it is not working.
Here is a code example:
sCmd = "powershell.exe -ExecutionPolicy ByPass -noexit -File \\server\Support\abhishek\Automation\SearchUtility.ps1 -Inputs " &"'" & PathValue & "'"
I got stuck for days and I haven't found a way to get this done. I need some help here. (I am new to Powershell)
Thanks in advance.
Try this. You don't need to build it in steps like this. I just did it this way to make it more readable. The last line is the critical part.
sCmd = "powershell.exe -ExecutionPolicy ByPass -noexit "
sCmd = sCmd & "-File \\server\Support\abhishek\Automation\SearchUtility.ps1 "
sCmd = sCmd & "-Inputs " & Chr(34) & PathValue & Chr(34)