考虑:
Function ABC {
[Object] $Connection = ((New-Object -TypeName System.IO.Ports.SerialPort -ArgumentList COM1, 11200, None, 8, one)
$Connection.open()
}
现在我想在我需要的时候在外面使用$Connection
。我怎样才能访问
$Connection.write("`r") # Calling from outside
$Connection.Readexisting("`r") # Calling from outside
答案 0 :(得分:0)
您遇到的问题是范围。如果在函数内声明变量,则变量仅具有该函数的作用域,并在函数运行后消失。你需要做的是在函数之外声明$connection
,将它传递给函数,在那里修改它,然后仍然可以访问函数之外的变量。
示例:
$connection
function MyFunction
{
param([Parameter(Mandatory=$true)][AllowNull()]$connection)
# do work here
}
另一种方法是将函数的返回值声明为变量
$myConnection = MyFunction
然后你可以在函数内部使用return
来返回变量。
答案 1 :(得分:0)
从函数中返回<body>
<p>Note: Make sure the numbers are among the following: 4, 6, 8, 10, and 20.</p>
<form id="diceForm" name="diceForm" action="">
<label>Enter your number here:</label>
<input type="number" name="dicenum" required='required' placeholder="Enter a number among 4, 6, 8, 10, and 20...">
<br>
<input type="submit" value="submit">
</form>
<%
if(request.getParameter("dicenum") != null) { // Opening curly braces for NPE guard
%>
<%
int num = Integer.parseInt(request.getParameter("dicenum"));
if (num == 4 || num == 6 || num == 10 || num == 20){
num = 1 + (Math.random()*num);
} else {
num = 0;
}
%>
<%= (num == 0)? "The number you've entered is out of range.": num %>
<% } %> // Closing curly braces for NPE guard
</body>
对象:
$connection
现在您可以使用它:
function New-COM1Connection
{
$Connection = New-Object -TypeName System.IO.Ports.SerialPort -ArgumentList COM1, 11200, None, 8, One
$Connection.Open()
return $Connection
}