Error from command-line, not interactively

I am currently trying to run the following script :

add-type "using System.Net;using System.Security.Cryptography.X509Certificates;public class TrustAllCertsPolicy : ICertificatePolicy {public bool CheckValidationResult(ServicePoint srvPoint, X509Certificate certificate,WebRequest request, int certificateProblem) {return true;}}";$AllProtocols = [System.Net.SecurityProtocolType]"Ssl3,Tls,Tls11,Tls12";[System.Net.ServicePointManager]::SecurityProtocol = $AllProtocols;[System.Net.ServicePointManager]::CertificatePolicy = New-Object TrustAllCertsPolicy;$server = "x.x.x.x";$urlbase = "https://${server}:port/api/";$username = "Prop";$password = "Testpassword";$EncodedAuthorization = [System.Text.Encoding]::UTF8.GetBytes($username + ":" + $password);$EncodedPassword = [System.Convert]::ToBase64String($EncodedAuthorization);$headers = @{"Authorization"="Basic $($EncodedPassword)"};$url = $urlbase + "site/custom/PropFiles/files";[xml]$r2 = Invoke-RestMethod -Uri $url -Method GET -Headers $headers;$link = ($r2.BESAPI.SiteFile | where {$_.Name -ieq "manifest"}).Resource;Invoke-RestMethod -Method Put -Uri "$link`?force=true;isClientFile=true" -infile "C:\users\Administrator\Manifest" -ContentType "text/txt" -Headers $headers

Using the following syntax:

powershell.exe -executionpolicy bypass -command {command listed above}

And I get the following error:

ERROR: Invalid pattern is specified in "path:pattern".

However, if I run this same script using powershell interactively (not using the ISE), it runs with no issues. Any thoughts as to why it produces the error when running from command line, but not when running it interactively?

put it in a file and use -f instead of -command, then pass the file path to it.

With creds being in the script I am not wanting to save the script to disk.

Can’t you prompt for the password ? how are you executing the script, is it in a scheduled task ?

Well, this looks like a complex code (multiple double quotes and other notation) in a script block, this can be done but takes time.


I would suggest to save this in a script file and execute. To solve the password problem, you can encrypt your password with below code

ConvertTo-SecureString -AsPlainText "Testpassword" -Force | ConvertFrom-SecureString | Out-File -FilePath C:\Temp\restHash.txt

Later you can decrypt it inside the script.

$username = "Prop"
$password = Get-Content C:\Temp\restHash.txt | ConvertTo-SecureString
$cred = New-Object System.Management.Automation.PSCredential ($username , $password)
$EncodedAuthorization = [System.Text.Encoding]::UTF8.GetBytes($username + ":" + $cred.GetNetworkCredential().Password)

One point to remember, encryption and decryption will work only with the same user context. To decrypt the password in a different user context, you may need to encrypt with a key or certificate.

Hope this helps