问题
I have a simple powershell script that creates a txt file thus:-
set-executionpolicy unrestricted -force
$MyVar = 'My Content'
$MyVar | out-file -FilePath "C:\_Testing\test.txt"
This is called from a ColdFusion script here:-
<cfexecute name="C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe"
arguments="C:\ColdFusion9\wwwroot\testsite\wwwroot\_Testing\powershellTest.ps1"/>
And that works - creates the txt file and puts the content in but what I want to do though is pass a variable through the cfexecute into the $MyVar so that the content is dynamic.
any help much appreciated
Paul
回答1:
What you want is a script that has parameters. Parameter definitions are put at the top of your script, and look like this:
param(
[Parameter(Mandatory=$true)]
[string]
# Variable to test that parameter is getting set from ColdFusion
$MyVar
)
$MyVar | Set-Content "C:\_Testing\test.txt"
First come attributes, which are meta data about the parameter. In the example, we are stating the parameters is mandatory and PowerShell will give an error if a value isn't provided.
Next comes the variable's type. You can use any .NET type, e.g. [int]
, [DateTime]
, [Hashtable]
, etc.
After the type, is the variable's documentation, useful when somebody runs Get-Help powershellTest.ps1
.
Finally, we declare the variable, $MyVar
.
You can get more information about parameters, parameter attributes, validation, etc. on the about_functions_advanced_parameters help topic.
Now, the tricky part is that your call to PowerShell is actually going through cmd.exe
first, so depending on the value of your script's parameter, you may need to do some funky magic to get things quoted correctly.
Also, use Set-Content
instead of Out-File
. Out-File
is intended for saving binary objects and data and will encode text files in UCS-2. Set-Content
will encode the files in ANSI/UTF-8.
回答2:
What you can do is make it in to a function that allows parameters. Then you can call the function with the params as necessary.
Example:
function CreateText
{
param ( [string]$MyVar
)
$MyVar | out-file -FilePath "C:\_Testing\test.txt"
}
CreateText -MyVar "Content Here"
And you can call it this way:
<cfexecute name="C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe"
arguments="C:\ColdFusion9\wwwroot\testsite\wwwroot\_Testing\powershellTest.ps1 -MyVar "conent" "/>
来源:https://stackoverflow.com/questions/17528100/coldfusion-variables-into-powershell