Powershell Script Issues

Welcome Forums General PowerShell Q&A Powershell Script Issues

This topic contains 5 replies, has 3 voices, and was last updated by

 
Participant
6 months ago.

  • Author
    Posts
  • #102137

    Participant
    Points: 0
    Rank: Member

    Hi Chaps,

    Never used powershell scripting before so bear with me! Took some sample code and tried to get this working. BAsically want to see if a file has been added to a folder. This sample looks at the last 10mins. Anyway, having issues: ex:

    At line:9 char:24
    + [string]$SMTPClient.Credentials = "New-Object System.Net.NetworkC ...
    + ~
    Missing ')' in function parameter list.
    At line:10 char:2
    + )
    + ~
    Unexpected token ')' in expression or statement.

    This is the code:

    Param (
    [string]$Path = "C:\Users\Uesr\Desktop\ScanFolder",
    [string]$SMTPServer = "smtp.live.com",
    [string]$From = "user@msn.com",
    [string]$To = "user@msn.com",
    [string]$Subject = "New File Uploaded to FTP Site",
    [string]$Body = "Test",
    [string]$SMTPClient = "New-Object Net.Mail.SmtpClient($SMTPServer, 587)",
    [string]$SMTPClient.Credentials = "New-Object System.Net.NetworkCredential("user@msn.com", "password")";
    )

    $SMTPMessage = @{
    To = $To
    From = $From
    Subject = $Subject
    Body = $Body
    Smtpserver = $SMTPClient
    }

    $File = Get-ChildItem $Path | Where { $_.LastWriteTime -ge [datetime]::Now.AddMinutes(-10) }
    If ($File)
    { $SMTPBody = "'nThe following files have recently been added/changed:'n'n"
    $File | ForEach { $SMTPBody += "$($_.FullName)`n" }
    Send-MailMessage @SMTPMessage -Body $SMTPBody
    }

  • #102139

    Participant
    Points: 303
    Helping Hand
    Rank: Contributor

    You've got a couple of things that you can do to make this work better for you. Your main issue is credentials. Most Powershell cmdlets use a -Credential parameter, including Send-MailMessage.

    param (
        [string]$Path = "C:\Users\Uesr\Desktop\ScanFolder",
        [string]$SMTPServer = "smtp.live.com",
        [string]$From = "user@msn.com",
        [string]$To = "user@msn.com",
        [string]$Subject = "New File Uploaded to FTP Site",
        [string]$Body = "Test",
        [PSCredential]$Credential #pass in credential
    )
    
    #Splat
    $smtpMessage = @{
        To = $To
        From = $From
        Subject = $Subject
        Smtpserver = $SMTPClient
        Credential = $Credential
        BodyAsHtml = $true
    }
    
    #You can use [datetime]:Now, but it's more common to leverage the Get-Date cmdlet to get the current
    #date.  You wrap params around it to resolve the date and then call the AddMinutes method
    $file = Get-ChildItem $Path | 
            Where { $_.LastWriteTime -ge (Get-Date).AddMinutes(-10) }
    
    If ( $file ) {	
        #If you set the BodyAsHTML param, you can leverage the ConvertTo-HTML to make formatting
        #much more simple.  Even if you wanted to make a pretty table, you simply add CSS.
        $body = $file | 
                ConvertTo-HTML -Property FullName -Body "The following files have recently been added/changed:" | 
                Out-String
    
        #With splatting, you are using a hashtable.  You can Add\Remove and Set the parameters dynamically.
        #So, we can build the body and then add the parameter like so...
        $smtpMessage.Add("Body", $body)
        
        Send-MailMessage @smtpMessage
    }
    

    Getting the credentials to pass to the script can be done a couple of ways. You can use the Get-Credential method which will prompt for the credentials:

    $creds = Get-Credential -UserName "username@msn.com"
    ./myscript.ps1 -Credential $cred
    

    or if you are wanting to do plain text (obviously less secure):

    $secpasswd = ConvertTo-SecureString "P@ssword!" -AsPlainText -Force
    $creds = New-Object System.Management.Automation.PSCredential ("username@msn.com", $secpasswd)
    ./myscript.ps1 -Credential $cred
    
  • #102145

    Participant
    Points: 0
    Rank: Member

    Many thanks for that, Rob.

    Apologies I should have given more context. Eventually, we'd want to schedule a task to run this shell script on a windows server. So how would we embed the credentials within the script itself? Could we pass it inside the params list?

  • #102194
    D

    Participant
    Points: 0
    Rank: Member

    Hi Guys I am trying to call this Api, but I am struggling to get the output and getting 401 error. tried on Rest Client app and it worked but not been able to get it working on powershell.
    The Curl code I got when it worked on Rest Client is as follows:-

    curl -X POST -k -H 'Content-Type: application/json' -H 'Authorization: OAuth oauth_signature_method="HMAC-SHA256", oauth_nonce="UPsZ9", oauth_timestamp="1242546", oauth_consumer_key="random", oauth_token="random", oauth_version="1.0", oauth_signature="random"' -i 'https://random.net/messaging_history/api/account/37007926/agent-view/summary' --data '{}'
    
    

    I am just trying to get it working using powershell.

    The powershell script I am using is getting Oauthentication correctly but failing at INVOKE-RESTMETHOD. I have tried searching Oauth 1.0 examples online but there isn't much information available. So this code is more or less borrowed from here and there andthats why looks like two codes as follows:-

    [Reflection.Assembly]::LoadWithPartialName("System.Security")
    [Reflection.Assembly]::LoadWithPartialName("System.Net")
    
    $status = [System.Uri]::EscapeDataString("{}");
    $oauth_consumer_key = "random";
    $oauth_consumer_secret = "random";
    $oauth_token = "random";
    $oauth_token_secret = "random";
    $oauth_nonce = [System.Convert]::ToBase64String([System.Text.Encoding]::ASCII.GetBytes([System.DateTime]::Now.Ticks.ToString()));
    $ts = [System.DateTime]::UtcNow - [System.DateTime]::ParseExact("01/01/1970", "dd/MM/yyyy", $null).ToUniversalTime();
    $oauth_timestamp = [System.Convert]::ToInt64($ts.TotalSeconds).ToString();
    
    $signature = "POST&";
    $signature += [System.Uri]::EscapeDataString("https://random") + "&";
    $signature += [System.Uri]::EscapeDataString("oauth_consumer_key=" + $oauth_consumer_key + "&");
    $signature += [System.Uri]::EscapeDataString("oauth_nonce=" + $oauth_nonce + "&"); 
    $signature += [System.Uri]::EscapeDataString("oauth_signature_method=HMAC-SHA1&");
    $signature += [System.Uri]::EscapeDataString("oauth_timestamp=" + $oauth_timestamp + "&");
    $signature += [System.Uri]::EscapeDataString("oauth_token=" + $oauth_token + "&");
    $signature += [System.Uri]::EscapeDataString("oauth_version=1.0&");
    $signature += [System.Uri]::EscapeDataString("status=" + $status);
    
    $signature_key = [System.Uri]::EscapeDataString($oauth_consumer_secret) + "&" + [System.Uri]::EscapeDataString($oauth_token_secret);
    
    $hmacsha1 = new-object System.Security.Cryptography.HMACSHA1;
    $hmacsha1.Key = [System.Text.Encoding]::ASCII.GetBytes($signature_key);
    $oauth_signature = [System.Convert]::ToBase64String($hmacsha1.ComputeHash([System.Text.Encoding]::ASCII.GetBytes($signature)));
    
    $oauth_authorization = 'OAuth ';
    $oauth_authorization += 'oauth_consumer_key="' + [System.Uri]::EscapeDataString($oauth_consumer_key) + '",';
    $oauth_authorization += 'oauth_nonce="' + [System.Uri]::EscapeDataString($oauth_nonce) + '",';
    $oauth_authorization += 'oauth_signature="' + [System.Uri]::EscapeDataString($oauth_signature) + '",';
    $oauth_authorization += 'oauth_signature_method="HMAC-SHA1",'
    $oauth_authorization += 'oauth_timestamp="' + [System.Uri]::EscapeDataString($oauth_timestamp) + '",'
    $oauth_authorization += 'oauth_token="' + [System.Uri]::EscapeDataString($oauth_token) + '",';
    $oauth_authorization += 'oauth_version="1.0"';
    
    $url = 'https://random'
    
    
    
    [System.Net.HttpWebRequest] $request = [System.Net.WebRequest]::Create("https://random");
    $request.Method = "POST";
    $request.Headers.Add("Authorization", $oauth_authorization);
    $request.ContentType = "application/json";
    $result = $request.GetRequestStream();
    $headers=@{"Authorization"= $oauth_authorization}
    
    
    $algorithm = "{`"alg`":`"none`"}`n"
    
    
    $algorithmBase64 = [Convert]::ToBase64String([System.Text.Encoding]::ASCII.GetBytes($algorithm))
    $body = {} -f 'eyJhbGciOiJub25lIn0K',$accessCode
    
    $params = @{
        ContentType = 'application/x-www-form-urlencoded'
        Headers = @{"Authorization"= $oauth_authorization}
        Body = {} -f $algorithmBase64
        Method = 'Post'
        URI = $url
    }
    
    
    $d= Invoke-RestMethod -Uri $url -Method POST -Headers $headers -body $body
    
    # Invoke-RestMethod @params
    
    
  • #102296

    Participant
    Points: 303
    Helping Hand
    Rank: Contributor

    @DM4

    You should just move things around a bit. The params block is for passing arguments to a script, but you could simplify it something like this:

    $secpasswd = ConvertTo-SecureString "P@ssword!" -AsPlainText -Force
    $creds = New-Object System.Management.Automation.PSCredential ("username@msn.com", $secpasswd)
    
    #Splat
    $smtpMessage = @{
        To         = 'user@msn.com'
        From       = 'user@msn.com'
        Subject    = 'New File Uploaded to FTP Site'
        Smtpserver = 'smtp.live.com'
        Credential = $creds
        BodyAsHtml = $true
    }
    
    #You can use [datetime]:Now, but it's more common to leverage the Get-Date cmdlet to get the current
    #date.  You wrap params around it to resolve the date and then call the AddMinutes method
    $file = Get-ChildItem 'C:\Users\Uesr\Desktop\ScanFolder' | 
            Where { $_.LastWriteTime -ge (Get-Date).AddMinutes(-10) }
    
    If ( $file ) {	
        #If you set the BodyAsHTML param, you can leverage the ConvertTo-HTML to make formatting
        #much more simple.  Even if you wanted to make a pretty table, you simply add CSS.
        $body = $file | 
                ConvertTo-HTML -Property FullName -Body "The following files have recently been added/changed:" | 
                Out-String
    
        #With splatting, you are using a hashtable.  You can Add\Remove and Set the parameters dynamically.
        #So, we can build the body and then add the parameter like so...
        $smtpMessage.Add("Body", $body)
        
        Send-MailMessage @smtpMessage
    }
    

    @D,

    Not sure why you added this to an existing post, but you should start your own thread with your questions.

  • #102299

    Participant
    Points: 0
    Rank: Member

    Many Thanks Rob! Working now.

The topic ‘Powershell Script Issues’ is closed to new replies.