我在Powershell中遇到过这个奇怪的问题(不是在其他语言中)。有人可以向我解释为什么会这样吗?
我试图返回一个指定的数字(数字8),但该功能一直向我抛出一切。这是一个错误还是设计?
#include "server_http.hpp"
#include "client_http.hpp"
//Added for the json-example
#define BOOST_SPIRIT_THREADSAFE
#include <boost/property_tree/ptree.hpp>
#include <boost/property_tree/json_parser.hpp>
//Added for the default_resource example
#include <fstream>
#include <boost/filesystem.hpp>
#include <vector>
#include <algorithm>
using namespace std;
//Added for the json-example:
using namespace boost::property_tree;
typedef SimpleWeb::Server<SimpleWeb::HTTP> HttpServer;
typedef SimpleWeb::Client<SimpleWeb::HTTP> HttpClient;
//Added for the default_resource example
void default_resource_send(const HttpServer &server, shared_ptr<HttpServer::Response> response,
shared_ptr<ifstream> ifs, shared_ptr<vector<char> > buffer);
int main() {
//HTTP-server at port 8080 using 1 thread
//Unless you do more heavy non-threaded processing in the resources,
//1 thread is usually faster than several threads
HttpServer server(8080, 1);
//Add resources using path-regex and method-string, and an anonymous function
//POST-example for the path /string, responds the posted string
server.resource["^/string$"]["POST"]=[](shared_ptr<HttpServer::Response> response, shared_ptr<HttpServer::Request> request) {
//Retrieve string:
auto content=request->content.string();
//request->content.string() is a convenience function for:
//stringstream ss;
//ss << request->content.rdbuf();
//string content=ss.str();
*response << "HTTP/1.1 200 OK\r\nContent-Length: " << content.length() << "\r\n\r\n" << content;
};
//POST-example for the path /json, responds firstName+" "+lastName from the posted json
//Responds with an appropriate error message if the posted json is not valid, or if firstName or lastName is missing
//Example posted json:
//{
// "firstName": "John",
// "lastName": "Smith",
// "age": 25
//}
server.resource["^/json$"]["POST"]=[](shared_ptr<HttpServer::Response> response, shared_ptr<HttpServer::Request> request) {
try {
ptree pt;
read_json(request->content, pt);
string name=pt.get<string>("firstName")+" "+pt.get<string>("lastName");
*response << "HTTP/1.1 200 OK\r\nContent-Length: " << name.length() << "\r\n\r\n" << name;
}
catch(exception& e) {
*response << "HTTP/1.1 400 Bad Request\r\nContent-Length: " << strlen(e.what()) << "\r\n\r\n" << e.what();
}
};
//GET-example for the path /info
//Responds with request-information
server.resource["^/info$"]["GET"]=[](shared_ptr<HttpServer::Response> response, shared_ptr<HttpServer::Request> request) {
stringstream content_stream;
content_stream << "<h1>Request from " << request->remote_endpoint_address << " (" << request->remote_endpoint_port << ")</h1>";
content_stream << request->method << " " << request->path << " HTTP/" << request->http_version << "<br>";
for(auto& header: request->header) {
content_stream << header.first << ": " << header.second << "<br>";
}
//find length of content_stream (length received using content_stream.tellp())
content_stream.seekp(0, ios::end);
*response << "HTTP/1.1 200 OK\r\nContent-Length: " << content_stream.tellp() << "\r\n\r\n" << content_stream.rdbuf();
};
//GET-example for the path /match/[number], responds with the matched string in path (number)
//For instance a request GET /match/123 will receive: 123
server.resource["^/match/([0-9]+)$"]["GET"]=[&server](shared_ptr<HttpServer::Response> response, shared_ptr<HttpServer::Request> request) {
string number=request->path_match[1];
*response << "HTTP/1.1 200 OK\r\nContent-Length: " << number.length() << "\r\n\r\n" << number;
};
//Get example simulating heavy work in a separate thread
server.resource["^/work$"]["GET"]=[&server](shared_ptr<HttpServer::Response> response, shared_ptr<HttpServer::Request> /*request*/) {
thread work_thread([response] {
this_thread::sleep_for(chrono::seconds(5));
string message="Work done";
*response << "HTTP/1.1 200 OK\r\nContent-Length: " << message.length() << "\r\n\r\n" << message;
});
work_thread.detach();
};
//Default GET-example. If no other matches, this anonymous function will be called.
//Will respond with content in the web/-directory, and its subdirectories.
//Default file: index.html
//Can for instance be used to retrieve an HTML 5 client that uses REST-resources on this server
server.default_resource["GET"]=[&server](shared_ptr<HttpServer::Response> response, shared_ptr<HttpServer::Request> request) {
const auto web_root_path=boost::filesystem::canonical("web");
boost::filesystem::path path=web_root_path;
path/=request->path;
if(boost::filesystem::exists(path)) {
path=boost::filesystem::canonical(path);
//Check if path is within web_root_path
if(distance(web_root_path.begin(), web_root_path.end())<=distance(path.begin(), path.end()) &&
equal(web_root_path.begin(), web_root_path.end(), path.begin())) {
if(boost::filesystem::is_directory(path))
path/="index.html";
if(boost::filesystem::exists(path) && boost::filesystem::is_regular_file(path)) {
auto ifs=make_shared<ifstream>();
ifs->open(path.string(), ifstream::in | ios::binary);
if(*ifs) {
//read and send 128 KB at a time
streamsize buffer_size=131072;
auto buffer=make_shared<vector<char> >(buffer_size);
ifs->seekg(0, ios::end);
auto length=ifs->tellg();
ifs->seekg(0, ios::beg);
*response << "HTTP/1.1 200 OK\r\nContent-Length: " << length << "\r\n\r\n";
default_resource_send(server, response, ifs, buffer);
return;
}
}
}
}
string content="Could not open path "+request->path;
*response << "HTTP/1.1 400 Bad Request\r\nContent-Length: " << content.length() << "\r\n\r\n" << content;
};
thread server_thread([&server](){
//Start server
server.start();
});
//Wait for server to start so that the client can connect
this_thread::sleep_for(chrono::seconds(1));
//Client examples
HttpClient client("localhost:8080");
auto r1=client.request("GET", "/match/123");
cout << r1->content.rdbuf() << endl;
string json_string="{\"firstName\": \"John\",\"lastName\": \"Smith\",\"age\": 25}";
auto r2=client.request("POST", "/string", json_string);
cout << r2->content.rdbuf() << endl;
auto r3=client.request("POST", "/json", json_string);
cout << r3->content.rdbuf() << endl;
server_thread.join();
return 0;
}
void default_resource_send(const HttpServer &server, shared_ptr<HttpServer::Response> response,
shared_ptr<ifstream> ifs, shared_ptr<vector<char> > buffer) {
streamsize read_length;
if((read_length=ifs->read(&(*buffer)[0], buffer->size()).gcount())>0) {
response->write(&(*buffer)[0], read_length);
if(read_length==static_cast<streamsize>(buffer->size())) {
server.send(response, [&server, response, ifs, buffer](const boost::system::error_code &ec) {
if(!ec)
default_resource_send(server, response, ifs, buffer);
else
cerr << "Connection interrupted" << endl;
});
}
}
}
答案 0 :(得分:6)
这是一个错误还是设计?
按设计。在PowerShell中,cmdlet可以返回对象流,就像在C#中使用yield return
来返回IEnumerable
集合一样。
要返回的输出值不需要return
关键字,它只是退出(或从返回)当前范围。
来自Get-Help about_Return
(强调补充):
The Return keyword exits a function, script, or script block. It can be used to exit a scope at a specific point, to return a value, or to indicate that the end of the scope has been reached. Users who are familiar with languages like C or C# might want to use the Return keyword to make the logic of leaving a scope explicit. In Windows PowerShell, the results of each statement are returned as output, even without a statement that contains the Return keyword. Languages like C or C# return only the value or values that are specified by the Return keyword.
答案 1 :(得分:4)
马蒂亚斯照常上场。
我想在您的代码中解决此评论:
$number10 #1 WHY NO OUTPUT HERE ??????? I don't want to use write host
为什么不想使用Write-Host
?是因为您可能遇到this very popular post from PowerShell's creator with the provocative title Write-Host
Considered Harmful?
如果是这样,我建议您阅读tby标题为Is Write-Host
Really Harmful?
有了这些信息,应该很清楚,正如Mathias所说,你正在将对象返回到管道,但你也应该掌握选择替代方案所需的信息,无论它是Write-Verbose
,Write-Debug
,甚至Write-Host
。
如果我对此有所建议,我会选择Write-Verbose
,稍微改变你的功能定义以支持它:
function Main {
[CmdletBinding()]
param()
$Number10 = GetNum
Write-Verbose -Message $number10
$result = 8 # I WANT THIS NUMBER ONLY
PAUSE
$result
}
当您通过拨打$again = Main
来调用它时,您在屏幕上看不到任何内容,$again
的值为8
。但是,如果你这样称呼它:
$again = Main -Verbose
然后$again
仍然会有8
的值,但在屏幕上您会看到:
VERBOSE: 10
可能使用不同颜色的文字。
这不仅是一种显示值的方法,而且是调用者控制是否看到值的方法,而不更改函数的返回值。
要进一步推动文章中的某些要点,请考虑使用-Verbose
来调用您的函数不一定非必要。
例如,我们假设您将整个脚本存储在名为FeelingNum.ps1
的文件中。
如果除了上面所做的更改之外,还要将以下内容添加到文件的最顶层:
[CmdletBinding()]
param()
然后,你仍然调用你的功能&#34;通常&#34;作为$again = Main
,您仍然可以通过-Verbose
调用脚本来获取详细输出:
powershell.exe -File FeelingNum.ps1 -Verbose
使用-Verbose
参数设置一个名为$VerbosePreference
的变量,并在每个调用堆栈的函数上继承(除非它被覆盖)。您也可以手动设置$VerbosePreference
。
因此,使用这些内置功能可以获得很大的灵活性,无论是作为作者还是使用代码的任何人,即使是唯一的好东西使用它的人就是你。