Powershell, Invoke Web-Request Error (just at Windows Server 2012R) - powershell

at the moment i am writing some scripts to handle our Backups of our Costumers.
So the backups are running over a Synology Box.
The Script works really fine with Windows 10 and Windows Server 2019.
But i can not start it at WindowsServer 2012R2. And i tried so many things to handle but it didnt work.
$ip = "XXXXXXXXXX"
$u = "XXXXXXX"
$p = "XXXXXXX"
$d = "XXXXXX"
#Session ID auslesen & Authentifizierung
$a = Invoke-WebRequest -UseBasicParsing "http://$ip/webapi/auth.cgi?api=SYNO.API.Auth&version=2&method=login&account=$u&passwd=$p&session=ActiveBackup&format=cookie"
$ajson = $a.Content
$aobject = ConvertFrom-Json -InputObject $ajson
$s = $aobject.data.sid
At first he shows me the error that he can not handle utf-8, ive updated Powershell to Version 5.1 and now Windows always tells me that the Value of $a is not allowed to be null. It Seems that he cannot receive any session Number. On Windows 10 and Windows Server 2019 it runs perfectly. Please can anybody help me please. Would beeee really nice
Greetings
Yaspo
Edit i got it.
For everybody who got the same problems just go the classic way without
invoke-webrequest
$url = "http://$ip/webapi/auth.cgi?api=SYNO.API.Auth&version=2&method=login&account=$u&passwd=$p&session=ActiveBackup&format=cookie"
$wc = New-Object System.Net.WebClient
$result = $wc.DownloadString($url)

Related

How to send email by using MailKit via PowerShell?

I am having difficulty creating the Message object using mailkit so I can add the From, To, Subject and body with message that may have attachments to be send before disconnecting. I have created the MailKit object, Cancelation Token object. I am able to load the MailKit and MimeKit dlls using the add-type -path and I am able to connect, authenticate, Disconnect and Dispose but the message object creation part and sending is where I need help with. I have the following:
$MkSmtp = New-Object MailKit.Net.smtp.SmtpClient
$CanToken = New-Object System.Threading.CancellationToken ($false)
$SSL = [MailKit.Security.SecureSocketOptions]::SslOnConnect
$MkSmtp.Connect($MailServer, $Port, $SSL, $CanToken)
$MkSmtp.Authenticate(([System.Text.Encoding]::UTF8), $Username, $Password, $CanToken)
#$Message = New-Object ????
$MkSmtp.Send($Message)
$MkSmtp.Disconnect($true)
$MKSmtp.Dispose()
I thought the answer was:
$Message = [Mimekit.MimeMessage]::new()
$Message.From.Add($From)
$Message.To.Add($To)
$Message.Subject = "Test"
$TextPart = [MimeKit.TextPart]::new("plain")
$Body = "This is just a test"
$TextPart.Text = $Body
$Message.Body = $TextPart
Which came from https://www.powershellgallery.com/packages/PSGSuite/2.13.2/Content/Private%5CNew-MimeMessage.ps1. This worked on my developer machine but putting it to production yields the following error:
Method invocation failed because [MimeKit.MimeMessage] does not contain a method named 'new'
When it tries to go passed the following line:
$Message = [Mimekit.MimeMessage]::new()
Placing a breakpoint at this line after loading the dll via add-type and running "[MimeKit.MimeMessage] | Get-Member -Static" on the powershell command line on the development and production server it shows the following:
Development
Production
Same DLL is loaded on both the Development and Production. I have loaded the DLL using both Add-Type and System.Reflection.Assembly. Production is on PowerShell 4.0 while my development box is on PowerShell 5.1. Don't know if that is the issue. Anyone have any ideas?
Updated our live server to WIndows Management Framework 5.1 (PowerShell) and now has the New Method when viewing the Static Get-Member.
$Message = New-Object Mimekit.MimeMessage

SSAS Deployment Via Powershell Corrupting Format String

I am having a problem when deploying cubes via PowerShell that I don’t know how to fix. In my solution I have some measures with FormatString: \£ #,##0;-\£ #,##0. If I deploy them normally via Visual Studio, the XMLA I pull from the SSAS server after deployment will have <FormatString>\£ #,##0;-\£ #,##0</FormatString> which is all good and expected. However, if I deploy via PowerShell, the resulting XMLA from the server is <FormatString>\£ #,##0;-\£ #,##0</FormatString>.
I realise the issue is with £ being parsed, but I am not sure how to resolve it.
The bit of background here is that I am using Octopus Deploy, and I've extracted the PowerShell below where the issue occurs:
$modelpath = "C:\...\Project_Name.xmla"
$Path_To_Microsoft_AnalysisServices_Deployment = "C:\Program Files (x86)\Microsoft SQL Server\140\Tools\Binn\ManagementStudio\Microsoft.AnalysisServices.Deployment.exe"
$SSAS_Project_Name = "Project_Name"
$Path_To_SSAS_Bin_Folder = "F:\Octopus Deploy\CustomInstallation\Project_Name\Content"
$FilePath_asdatabase = "$Path_To_SSAS_Bin_Folder\$SSAS_Project_Name.asdatabase"
$FilePath_deploymenttargets = "$Path_To_SSAS_Bin_Folder\$SSAS_Project_Name.deploymenttargets"
$FilePath_configsettings = "$Path_To_SSAS_Bin_Folder\$SSAS_Project_Name.configsettings"
$FilePath_deploymentoptions = "$Path_To_SSAS_Bin_Folder\$SSAS_Project_Name.deploymentoptions"
Start-Process -FilePath $Path_To_Microsoft_AnalysisServices_Deployment -ArgumentList "`"$FilePath_asdatabase`"","/s:`"$FilePath_DeploymentLog`"","/o:`"$SSAS_Project_Name.xmla`"","/d" -Wait -NoNewWindow
# Load the Adomd Client
[System.Reflection.Assembly]::LoadWithPartialName(“Microsoft.AnalysisServices.AdomdClient”) | Out-Null;
# Connect to the server
Write-Host "Executing Deployment Script"
$serverName = “Data Source=.”
$conn = New-Object Microsoft.AnalysisServices.AdomdClient.AdomdConnection $serverName
$conn.Open()
# Read XMLA
$xmla = Get-Content $modelpath
# Execute XMLA
$cmd = New-Object Microsoft.AnalysisServices.AdomdClient.AdomdCommand $xmla, $conn
return $cmd.ExecuteNonQuery();
I have done some investigation and I’ve found the following:
The xmla file produced by PowerShell (not in the snippet) has the correct Format String \£ #,##0;-\£ #,##0
The .asdatabase file also has the correct format string
I suspect that something is happening either at:
Start-Process -FilePath $Path_To_Microsoft_AnalysisServices_Deployment -ArgumentList “`”$FilePath_asdatabase`””,”/s:`”$FilePath_DeploymentLog`””,”/o:`”$SSAS_Project_Name.xmla`””,”/d” -Wait -NoNewWindow
or further down at:
# Execute XMLA
$cmd = New-Object Microsoft.AnalysisServices.AdomdClient.AdomdCommand $xmla, $conn
return $cmd.ExecuteNonQuery();
Any help would be appreciated.
PS: I’ve tried playing with the Format String when setting it in the solution but haven’t been able to find a solution. Note that I can’t simple use “Currency” b/c the server is set to English (US).
The answer to this is to specify the encoding. From Jeroen in the comment in response to my question:
It looks like PowerShell is auto-detecting the encoding of the XMLA incorrectly as Windows-1252, when it's actually UTF-8 (without a BOM). Try $xmla = Get-Content $modelpath -Encoding UTF8. It may also be the case that the XMLA itself is actually incorrect -- make sure to inspect it in an editor capable of reporting the encoding, like Notepad++, not just have it echo back by PowerShell itself. – Jeroen Mostert 15 mins ago

access sharepoint REST api using powershell with windows authentication

I have a sharepoint 2013 server, which I can log into using Windows Authentication via a web-browser. When I have logged on using my browser, if I then - using that same browser - browse to http://mysharepointserver/_api/web I get some useful XML.
However, I want to write a powershell script that uses this XML. To that end, following the suggestions from this page:
How to make an authenticated web request in Powershell?
I wrote the following code:
$PWord = ConvertTo-SecureString –String "MyAwesomePassword" –AsPlainText -Force
$creds = New-Object System.Net.NetworkCredential("MyUserName",$PWord,"TheDomain")
$webclient = New-Object System.Net.WebClient
$webclient.Credentials = $creds
$url = "http://mysharepointserver/_api/web"
$output = $webclient.DownloadString($url)
echo $output
However, when I run this code, I get the error message:
Exception calling "DownloadString" with "1" argument(s): "The remote server returned an error: (403) Forbidden."
Even though I can access the same URL using a web-browser, if I type in the (same) credentials using the Windows login dialog that pops up for authentication purposes.
Does anyone know if it is possible to do this using Powershell?
thanks heaps all
Why aren't you using the default CMDlets that come with Powershell (unless using PS2 or lower)?
Invoke-Webrequest and Invoke-Restmethod both support the -credential switch which can be used to authenticate against the webserver.
You can also use Get-credential to store your credentials (though you can't get yhem from a file or string that way, at least not the password)
Script (in pseudo code and since i'm on my phone no code tags) would look like this :
Invoke-Restmethod -uri 'http://bla/api' -credential (get-credential)

Call an URL with Scheduled Powershell Script

I just want to call an URL with the tasks scheduler on Windows Server 2008 and a Powershell Script.
So I developed the following script :
$url = "http://example.com"
$log_file = "${Env:USERPROFILE}\Desktop\Planification.log"
$date = get-date -UFormat "%d/%m/%Y %R"
"$date [INFO] Exécution de $url" >> $log_file
$request = [System.Net.WebRequest]::Create($url)
$response = $request.GetResponse()
$response.Close()
The script works without any issue when I execute it from the Powershell ISE, the Powershell console or with the command :
powershell PATH_TO_MY_SCRIPT.ps1
But it doesn't works when I execute it from the Scheduler tasks, it returns the code 0xFFFD0000. I found this : http://www.briantist.com/errors/scheduled-task-powershell-0xfffd0000/
So it can be a permission problem, so I tried many others profiles and option (including "Execute with all permissions") to test, without success.
I execute also another Powershell script which just mount a network drive and copy two files, and I don't have any issue with this script. So I think that the issue come from the using of the .NET object to call my URL.
I saw that I may have to include modules in my script before any other commands, but I don't know exactly what I have to do. (I don't know Powershell, I just try to use it for resolving my problems).
Thank you for you help.
i used the following in a scheduled task and it works as expected :
$url="http://server/uri"
(New-Object System.Net.WebClient).DownloadString("$url");
following code should do what you need.
$url = "http://www.google.com"
PowerShell Invoke-WebRequest -Uri $url -Method GET
You'll want to put that log file out somewhere in a shared directory. Scheduled tasks may or may not have access to $env:USERPROFILE. Also, use Start-Transcript to have PowerShell write your script's output to a log file (except for STDOUT, you'll need to pipe the output from executables to Write-Host, e.g. hostname | Write-Host).
$url = "http://example.com"
$log_file = "C:\PlanificationLogs\Planification.log"
Start-Transcript -Path $log_file
Get-Date -UFormat "%d/%m/%Y %R"
Write-Host "$date [INFO] Exécution de $url"
# PowerShell 3
Invoke-WebRequest -Uri $url
# PowerShell 2
$request = [System.Net.WebRequest]::Create($url)
$response = $request.GetResponse()
$response.Close()

Powershell Web with Proxy

I am getting a proxy error with my script. "The remote server returned an error: (407) Proxy Authentication Required."
IE uses a script to configure it's connection (that's all the info I have). I looked in there and tried some IPs/ports in my script, but none seemed to work. Is there some other way of using this IE connection script in PS?
$web_client = New-Object System.Net.WebClient;
$web_client.Headers.Add("user-agent", "PowerWeb");
$proxyAddr = "http://172.16.192.34:9090"
$proxy = new-object System.Net.WebProxy
$proxy.useDefaultCredentials = $true
$proxy.Address = $proxyAddr
$web_client.proxy = $proxy
$data = $web_client.DownloadData("http://stackoverflow.com")
If you are using PowerShell 3.0 you can use Invoke-WebRequest