check website url status using powershell version 2.0 - powershell-2.0

I need to check if URL is working properly or not using "PowerShell Version 2.0"
I found this script over internet, but it is not wokring fine for wrong URL's. It should go in else loop for wrong URL's as well as print website code. And I am not able to pass credentials in this script.
e.g. for www.google.com(correct URL) status code should be 200but
for www.gfjgugy79rt9(Wrong URL) status code should be something like 404
script I found over internet for powershell version 2.0:
# First we create the request.
$HTTP_Request = [System.Net.WebRequest]::Create('http://google.com')
# We then get a response from the site.
$HTTP_Response = $HTTP_Request.GetResponse()
# We then get the HTTP code as an integer.
$HTTP_Status = [int]$HTTP_Response.StatusCode
If ($HTTP_Status -eq 200) {
Write-Host "Site is OK!"
}
Else {
Write-Host "The Site may be down, please check!"
}
# Finally, we clean up the http request by closing it.
$HTTP_Response.Close()

In PowerShell higher than 2.0 you should use try ... catch ... finally because this code fire exception when the URI is no conform or when the adress part is not solvable by the DNS :
try {
# First we create the request.
$HTTP_Request = [System.Net.WebRequest]::Create('http://google.com')
# We then get a response from the site.
$HTTP_Response = $HTTP_Request.GetResponse()
# We then get the HTTP code as an integer.
$HTTP_Status = [int]$HTTP_Response.StatusCode
If ($HTTP_Status -eq 200) {
Write-Host "Site is OK!"
}
Else {
Write-Host "The Site may be down, please check!"
}
}
catch {
Write-Verbose $_.ScriptStackTrace
Write-Verbose "Ligne $($_.InvocationInfo.ScriptLineNumber) : $($_.exception.message)"
}
finally {
# Finally, we clean up the http request by closing it.
$HTTP_Response.Close()
}
In PowShell 2.0 you just have to put a Trap code at the beginnig of the scope (function, script) where you want to catch these exception :
trap
{
Write-Verbose $_.ScriptStackTrace
Write-Verbose "Ligne $($_.InvocationInfo.ScriptLineNumber) : $($_.exception.message)"
Write-Verbose ([datetime]::Now)
return
}

Related

Filename with a hash (#) not uploading

I'm attempting to send a file to OneDrive using the following code:
$uri = "/me/drive/items/$folderId/children('{$fileName}')/content";
$graph = $this->graph->create($user);
$client = $this->graph->createClient();
$item = $graph->createRequest("PUT", $uri)
->attachBody($fileContent)
->setReturnType(Model\DriveItem::class)
->execute($client);
This works great if $fileName is something like Test.doc
But for some reason, when the filename has a hash (#) in the filename, then I get an error:
object(Microsoft\Graph\Model\DriveItem)#1509 (1) {
["_propDict":protected]=>
array(1) {
["error"]=>
array(3) {
["code"]=>
string(10) "BadRequest"
["message"]=>
string(36) "Bad Request - Error in query syntax."
["innerError"]=>
array(2) {
["request-id"]=>
string(36) "ff3fe15f-b1ee-4e92-8abd-2400b1c1b5cf"
["date"]=>
string(19) "2018-10-04T14:30:51"
}
}
}
Can someone possibly clarify if this is a bug or actual behaviour (i.e. you cannot have a # in a filename)
Thanks
I guess you are utilizing Microsoft Graph Library for PHP, special characters such as # needs to be escaped.
So, either replace the hash with %23 (percent encoding) or use rawurlencode function as shown below:
$fileName = rawurlencode("Guide#.docx");
$requestUrl = "https://graph.microsoft.com/v1.0/drives/$driveId/root:/$fileName:/content";
try {
$item = $client->createRequest("PUT", $requestUrl)
->attachBody($fileContent)
->setReturnType(Model\DriveItem::class)
->execute();
} catch (\Microsoft\Graph\Exception\GraphException $ex) {
print $ex;
}
Although the file name have support # in name, but it doesn't mean the Product Team provide the API or adjust the existing API first time, the API you use may not have fully adjusted to suit thore latest naming rules. So it should be actual behavior now but not bug/or you can treat it as none-existed feature.
There are a related issue in the SharePoint dev issue list, although they aren't same one, but the suggestion is the same, vote the exising feature or submit an new one on UserVoice.

How to check the status of a link?

I'm running a MANET simulation in ns2 using AODV routing protocol. Is there any way I can check whether a node forwards data it receives to the next node in the route or check whether the link between 2 nodes is active?
Try this:
package require http
package require tls
http::register https 443 [list ::tls::socket -tls1 1]
set url "https://google.com"
if {![catch {set token [::http::geturl $url]} msg]} {
if {[::http::status $token] == "ok"} {
#Do something when token is ok for example print HTTTP code
puts [::http::code $token]
} else {
#Do something when status token is not ok
}
} else {
#print error when Url is invalid or host is unreachable
puts "oops: $msg"
}

Redeployment with Powershell in Multi Tenant Environment

I want to redeploy a multiple tenants using powershell. We have 100+ tenants in UIT and I don't want to do this manually. In order to redeploy, I have to use a specific link and log in. My question is, if it is possible to do this in an automated way using powershell. Here is what I have so far:
Function SendRequest($tenantName)
{
$url = "http://<machine-name>/$tenantName/Account /LogOn?ReturnUrl=%2f$tenantName%2fadmin%2fdeploytenant%3fsyncmetadata%3dtrue&syncmetadata=true"
$req = [system.Net.WebRequest]::Create($url)
$req.Credentials = [System.Net.NetworkCredential]::($username, (ConvertTo-SecureString $pwd -AsPlainText -force))
try
{
$res = $req.GetResponse()
}
catch [System.Net.WebException]
{
$res = $_.Exception.Response
}
$int = [int]$res.StatusCode
$status = $res.StatusCode
Write-Host $status
return "$int $status"
}
The status that is returned is "200 OK" but it does not redeploy. Maybe I need to log in first and then send another request with the redeployment parameters. So what would be the best way to accomplish this?
Maybe this is just a snippet of your code, but I'm seeing you reference $username and $pwd without actually feeding in a username and password.
Perhaps that could that explain the lack of a successful redeploy.

error "not a valid Socket resource" implementing the phpwebsocket library

I'm trying to work with the phpwebsocket library at http://code.google.com/p/phpwebsocket/
I'm using the version r8 of the server.php file. For testing I just tried with the client.html file, also provided by the website.
When the server is started I get this:
Server Started : 2011-08-29 22:11:23
Master socket : Resource id #4
Listening on : www.midomain.com port 12345
But when I load the client.html file in the browser, the server shows the following errors:
Notice: Undefined variable: key1 in /home/mink500/public_html/test/server.php on line 143
Notice: Undefined variable: key2 in /home/mink500/public_html/test/server.php on line 143
Warning: socket_select(): 5 is not a valid Socket resource in /home/mink500/public_html/test/server.php on line 15
There are two variables that are not defined, and the function socket_select() returns the error "5 is not a valid Socket resource"
In the browser I get the "Disconnected" message as soon as the file is loaded.
I tried to make the server work locally using XAMPP (Apache and PHP) but I got the same errors. I also tried to change ports and follow the instructions in this issue:
http://code.google.com/p/phpwebsocket/issues/detail?id=33
But I still get the error "5 is not a valid Socket resource"
I remember that refreshing the page several times I got it running a few months ago, but now it's impossible. Besides, I need it to work all the time, not just after I refresh the page like 20 times.
I also tried with the websocket.class.php file, but this time I get an error on the client side. The browser now returns "Error during WebSocket handshake: 'Sec-WebSocket-Accept' header is missing".
So, I can't make it work with old or new files, with remote or local server, with magic or a ouija board!
Any idea?
Thanks
Starting with the newest phpwebsocket client.html and server.php files I replaced both the getheaders() and dohandshake() functions with the code below works for me in newest Chrome. However it currently does not write to the browser nor stay alive after one uer comment in the chat box.
function dohandshake($user, $buffer) {
$key = null;
console("\nRequesting handshake...");
console($buffer);
console("Handshaking...");
preg_match("#Sec-WebSocket-Key: (.*?)\r\n#", $buffer, $match) && $key = $match[1];
$key .= "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
$key = sha1($key);
$key = pack('H*', $key);
$key = base64_encode($key);
$upgrade =
"HTTP/1.1 101 Switching Protocols\r\n" .
"Upgrade: websocket\r\n" .
"Connection: Upgrade\r\n" .
"Sec-WebSocket-Accept: {$key}\r\n\r\n";
socket_write($user->socket, $upgrade . chr(0), strlen($upgrade . chr(0)));
$user->handshake = true;
console($upgrade);
console("Done handshaking...");
return true;
}
function getheaders($header) {
$retVal = array();
$fields = explode("\r\n", preg_replace('/\x0D\x0A[\x09\x20]+/', ' ', $header));
foreach ($fields as $field) {
if (preg_match('/([^:]+): (.+)/m', $field, $match)) {
$match[1] = preg_replace('/(?<=^|[\x09\x20\x2D])./e', 'strtoupper("\0")', strtolower(trim($match[1])));
if (isset($retVal[$match[1]])) {
$retVal[$match[1]] = array($retVal[$match[1]], $match[2]);
} else {
$retVal[$match[1]] = trim($match[2]);
}
}
}
if (preg_match("/GET (.*) HTTP/", $header, $match)) {
$retVal['GET'] = $match[1];
}
return $retVal;
}

Twitter OAuth Problem

I am trying to use Twitter Oauth to login.
index.php
<?php
require ("twitteroauth/twitteroauth.php");
session_start();
// The TwitterOAuth instance
$twitteroauth = new TwitterOAuth('00000000000000000', '0000000000000000000000000000000');
// Requesting authentication tokens, the parameter is the URL we will be redirected to
$request_token = $twitteroauth->getRequestToken('http://bakasura.in/twitter/twitter_oauth.php');
// Saving them into the session
$_SESSION['oauth_token'] = $request_token['oauth_token'];
$_SESSION['oauth_token_secret'] = $request_token['oauth_token_secret'];
// If everything goes well..
if($twitteroauth->http_code==200){
// Let's generate the URL and redirect
$url = $twitteroauth->getAuthorizeURL($request_token['oauth_token']);
header('Location: '. $url);
} else {
// It's a bad idea to kill the script, but we've got to know when there's an error.
die('Something wrong happened.');
}
?>
Once the page loads it takes me to the Authorization Page When i click Allow it takes me back to the http://bakasura.in/twitter/twitter_oauth.php
<?php
require ("twitteroauth/twitteroauth.php");
if(!empty($_GET['oauth_verifier']) && !empty($_SESSION['oauth_token']) && !empty($_SESSION['oauth_token_secret'])){
// We've got everything we need
echo "Authorized";
} else {
// Something's missing, go back to square 1
//header('Location: twitter_login.php');
echo "Not Authorized";
}
?>
And it says "Not Authorized"
you can try it here http://bakasura.in/twitter/
you did not start your session in the second page. As long as you do not call session_start(), your session variables are not available
Some PHP setups have configured their php.ini to autostart your session, but when I look at your server setup, I see you are not sending out a cookie header for your php session on your second page, so I'm pretty sure that your session is not started on your second page...

Resources