If I run IE on my computer as the user DOMAIN\automatic the url works:
right click IE
shift + right click "Internet Explorer" in the menu
run as different user
When opening the url http://server/ClearCache there is no problem.
When I do the same with powershell and run it again as DOMAIN\automatic the following script runs:
$url = "http://server/ClearCache"
$req = [system.Net.WebRequest]::Create($url)
$req.UseDefaultCredentials = $true
$res = $req.GetResponse()
$res
The route ClearCache has [AllowAnonymous] in the controller.
When I go to the server with remote desktop logged in as user DOMAIN\automatic that needs to run the powershell script (sql server agent job step) and run the script in powershell I get:
Exception calling "GetResponse" with "0" argument(s): "The remote
server returned an error: (400) Bad Request." At line:1 char:1
+ $res = $req.GetResponse()
+ ~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : WebException
Opening the url in IE gives me the response 400 Bad Request.
This seems to be related to an IE profile on the server because Chrome on the server can open the url.
Would anyone know what reg key or setting in the ocean of options I need to change to make this work?
Thank you for reading my question.
[UPDATE]
When trying to run it under my credentials I still get the 400 error so don't think it is because of authentication:
$url = "http://server/ClearCache"
$req = [system.Net.WebRequest]::Create($url)
# $req.UseDefaultCredentials = $true
$passwd = ConvertTo-SecureString "password" -AsPlainText -Force;
$req.Credentials = New-Object System.Management.Automation.PSCredential ("myAccount", $passwd);
$res = $req.GetResponse()
$res
Not sure what the problem was or why it worked in Chrome but not IE. Since the response body (can see the response body in IE devtools when you press F12) says "Invalid host name" I tried to add some DNS bindings in C:\Windows\System32\drivers\etc\hosts like 127.0.0.1 myserver and uncommenting localhost but with no result.
Finally replaced the server name with the ip address and that solved it (xxx are numbers of ip address):
$url = "http://xxx.xxx.xxx.xxx/ClearCache"
Related
Issue description: (Please see below screen dump for reference)
Failure using Tag with Import-AzureKeyVaultCertificate cmdlet.
The certificate would be imported into key vault okay even though I got the error message (as shown below).
However, I am not able to retrieve the certificate using Get-AzureKeyVaultCertificate cmdlet, even though I could use Get-AzureKeyVaultSecret cmdlet (Tags displayed correctly).
Additional info
• If I remove Tags from Azure portal or re-import the certificate without -Tag, I will still get the same error (Unable to cast object).
• If I delete the cert and re-import the certificate without Tags, everything is working great.
Assistance needed:
I am using 5.1.2 Azure PowerShell. Please advise what am I missing. Thanks.
PS C:\Users\tonychou> $certificateTag = #{
type = "certificate";
subjectname = "rsppe-microsoft-com";
alternatename = "dss";
environment = "Test"
};
PS C:\Users\tonychou> $certificatePasswordSecuredString = ConvertTo-SecureString $certificatePassword -AsPlainText -Force;
Import-AzureKeyVaultCertificate -VaultName $kvName -CertificateName $certInCertName -FilePath $certificatePfxFile -Password $certificatePasswordSecuredString -Tag $certificateTag;
Import-AzureKeyVaultCertificate : Unable to cast object of type 'System.Collections.Generic.Dictionary`2[System.String,System.String]' to type 'System.Collections.Hashtable'.
At line:2 char:1
+ Import-AzureKeyVaultCertificate -VaultName $kvName -CertificateName $ ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : CloseError: (:) [Import-AzureKeyVaultCertificate], InvalidCastException
+ FullyQualifiedErrorId : Microsoft.Azure.Commands.KeyVault.ImportAzureKeyVaultCertificate
PS C:\Users\tonychou> $certInCertificate = Get-AzureKeyVaultCertificate -VaultName $kvName -Name $certInCertName;
Get-AzureKeyVaultCertificate : Unable to cast object of type 'System.Collections.Generic.Dictionary`2[System.String,System.String]' to type 'System.Collections.Hashtable'.
At line:1 char:22
+ ... rtificate = Get-AzureKeyVaultCertificate -VaultName $kvName -Name $ce ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : CloseError: (:) [Get-AzureKeyVaultCertificate], InvalidCastException
+ FullyQualifiedErrorId : Microsoft.Azure.Commands.KeyVault.GetAzureKeyVaultCertificate
PS C:\Users\tonychou> $certInSecret = Get-AzureKeyVaultSecret -VaultName $kvName -Name $certInCertName;
PS C:\Users\tonychou> $certInCertificate
PS C:\Users\tonychou> $certInSecret
SecretValue : System.Security.SecureString
SecretValueText : MIIXegIBAzCCFzoGCSqGSIb3DQEHAaCCFysEghcnMIIXIzCCBgQGCSqGSIb3DQEHAaCCBfUEggXxMIIF7TCCBekGCyqGSIb3DQEMCgECoIIE9jCCBPIwHAYKKoZIhvcNAQwBAzAOBAgn0z9KUgiVSwICB9AEggTQ+38U79mo15qmAm7r0IgpGlveZFMHwqYt/LmEZOUyTKXv6GWHxkSoy/+dsa2XkVFruWas5WgqksMuwxY
43kum42JCzSHIkEzAbiN3zZNZWM7JDLaXBooR2bpOR49fdGdy44RmQjFGkU7w2cYLMjB+WSBQ9tt2xw4W1fJnv4d3vO44BQ/c2n1aHBZjmobdSrIDtpK8h+aiZyUrNix6wlifthI884h09rlF6ipBDicbgLn4NbpYPzfZlpa304fU9c7h0j/IDpdOi2zZOVT2Q3oc9ouMuSaKBC9CKE3Q99UBwyX/tZjM/A/uuW5nh3KQZ8
IJciW7/odBt3b9venZOHHbAZDns5iIzwop3hzSEDbQTqQ3hffdFEyUexHsq5AP2syveZYWlIrDpe9YJVB
PS C:\Users\tonychou> Get-Module -ListAvailable | ?{$_.Name -eq "Azure"}
Directory: C:\Program Files\WindowsPowerShell\Modules
ModuleType Version Name ExportedCommands
---------- ------- ---- ----------------
Script 5.1.2 Azure {Get-AzureAutomationCertificate, Get-AzureAutomationConnection, New-AzureAutomationConnection, Remove-AzureAutomationConnection...}
We suggest moving to Powershell version 6.0.0 and above
Background: I am creating a script to send out a message to everyone in my Domain. I was able to complete this using Invoke-WMImethod and MSG.exe. However, my supervisor wants a more customizable message to be sent. Like changing Color, font size, font style...etc. Which i have created using PowerShell.
Script:
Invoke-WmiMethod -ComputerName $Computer -Class Win32_Process -Name Create -ArgumentList {"C:\x\x\x\Powershell.exe -File `"\\Server\Share\Folder\Script.ps1`""}
When i run this script against my Computer it works perfectly. However, when i attempt to run it on a remote computer it fails.
I don't understand why.
It's the same exact script that i used with MSG.exe, which worked, but it still doesn't work with a powershell script.
I attempted to copy the script to the remote computers 'C:\' and run it from that file path but it still didn't work.
I've verified the file path to Powershell.exe is the same as the script and that the remote workstation can access the .PS1 Script.
However, the script does run and says it is successful with a Return Value of 0. Example:
__GENUS : 2
__CLASS : __PARAMETERS
__SUPERCLASS :
__DYNASTY : __PARAMETERS
__RELPATH :
__PROPERTY_COUNT : 2
__DERIVATION : {}
__SERVER :
__NAMESPACE :
__PATH :
ProcessId : 8748
ReturnValue : 0
My Suggestion would be to check for the versions on both the machines. The CmdLet you using may not be working on the previous version.
I again have a suggestion to make, you can use the below command to get your work done, if you have powershell Version 3 or above.
$Outputreport = "Test message to send data using port 443"
[System.Net.ServicePointManager]::ServerCertificateValidationCallback = { $true }
$wc = new-object System.Net.WebClient
Invoke-RestMethod -Method Post https://hostnamedotcom/cgi-bin/dir-path/$hostname-filename -Body $Outputreport
I'm trying to install a Tcl program as a service on my Windows machine using the TclDevKit's TclServiceManager. I'm following the guide here step by step and yet I am experiencing a lot of issues.
If I try to use my raw .tcl file to create the service, I get the following error:
Error 1053: The service did not respond to the start or control request in a timely fashion.
I've followed a solution for this issue here to give the program more time to start up before the Service Control Manager terminates it; to no avail.
Then I decided to try and wrap the program using TclApp and see if that worked. Like the guide says, I used the base-tclsvc-win32-ix86.exe prefix file located in my TclDevKit bin directory. Installing the service that way, and then trying to run it resulted in the following error:
Windows could not start the <service name> service on Local Computer.
Error 1067: The process terminated unexpectedly.
There wasn't much information at all that I could find googling this error. The only Stackoverflow post on it is this one. So I tried installing the service manually through the command prompt using <TheProgram>.exe <Service Name> -install and tried running it - still gave me the same error.
Then I tried to see if I could get any useful information by running <TheProgram>.exe <Service Name> -debug and interestingly enough I got the following output:
Debugging <Service Name>.
InitTypes: failed to find the DictUpdateInfo AuxData type
abnormal program termination
Googling InitTypes: failed to find the DictUpdateInfo AuxData type leads me nowhere, however it seems to be something Tcl related.
Finally, if it means anything, the source code for the program I was trying to install as a service is some simple web server code:
proc Serve {chan addr port} {
fconfigure $chan -translation auto -buffering line
set line [gets $chan]
set path [file join . [string trimleft [lindex $line 1] /]]
if {$path == "."} {set path ./index.html}
if {[catch {
set f1 [open $path]
} err]} {
puts $chan "HTTP/1.0 404 Not Found"
} else {
puts $chan "HTTP/1.0 200 OK"
puts $chan "Content-Type: text/html"
puts $chan ""
puts $chan [read $f1]
close $f1
}
close $chan
}
if {![info exists reload]} {
set sk [socket -server Serve 3000]
puts "Server listening on port 3000"
vwait forever
} else {
unset reload
}
To check and see if the source code was the problem, I tried another, simpler example that simply created a file in a particular directory:
set filePath "C:/some/path/here";
set fileName "Test.txt";
set file [open [file join $filePath $fileName] w];
puts $file "Hello, World";
close $file;
Both programs work if you simply source them from tclsh86.exe, but give the above errors if you try and run them as services unwrapped and wrapped respectively.
Any ideas?
In general I'm trying to create mailbox on Exchange Server 2010 remotely using wmic. I have a following environment setup:
Systems are not in the same domain.
System 1 (from where I execute): running Windows 7 x64 System 2 (target system with Exchange on board): running Windows Server 2008 R2. There I have PowerShell script called addmailbox.ps1:
$secure_pwsd = convertto-securestring TESTPASSWORD -asplaintext -force
New-Mailbox -UserPrincipalName TESTMAILBOX#MYDOMAIN.com -Alias SOMEALIAS -Name SOMENAME -OrganizationalUnit Users -Password $secure_pwsd -FirstName SOMEFIRSTNAME -LastName SOMELASTNAME -DisplayName "LASTNAME FIRSTNAME" -ResetPasswordOnNextLogon $false
exit
If I run the script locally from System 2 it works fine, mailbox created as expected, so I tried to run it remotely from System 1 like this
wmic /node:IP /user:DOMAIN\Administrator /password:PASS process call create 'powershell.exe -command ". 'C:\Program Files\Microsoft\Exchange Server\V14\Bin\RemoteExchange.ps1'; Connect-ExchangeServer -auto; C:\scripts\addmailbox.ps1"'
WMIC reported that the remote process created successfully. On System 2 in task manager I can see that the process is running and child PowerShell process also spawned, but both processes are not completed. I suppose PowerShell wait for user input or something. To test, I added the key "-noninteractive" to executing command and catch the following errors
VERBOSE: Connecting to HOSTNAME
[HOSTNAME] Connecting to remote server failed with the following error message : A specified logon session does
not exist. It may already have been terminated. For more information, see the about_Remote_Troubleshooting Help topic.
+ CategoryInfo : OpenError: (System.Manageme....RemoteRunspace:RemoteRunspace) [], PSRemotingTransportExc
eption
+ FullyQualifiedErrorId : PSSessionOpenFailed
Failed to connect to any Exchange Server in the current site.
Read-Host : Windows PowerShell is in NonInteractive mode. Read and Prompt functionality is not available.
At C:\Program Files\Microsoft\Exchange Server\V14\bin\ConnectFunctions.ps1:47 char:18
+ $fqdn=read-host <<<< -prompt "Please enter the Server FQDN where you want to connect"
+ CategoryInfo : InvalidOperation: (:) [Read-Host], PSInvalidOperationException
+ FullyQualifiedErrorId : InvalidOperation,Microsoft.PowerShell.Commands.ReadHostCommand
VERBOSE: Connecting to
New-PSSession : Cannot bind parameter 'ConnectionUri'. Cannot convert value "http:///powershell?serializationLevel=Full
" to type "System.Uri". Error: "Invalid URI: The hostname could not be parsed."
At C:\Program Files\Microsoft\Exchange Server\V14\bin\ConnectFunctions.ps1:229 char:43
+ $session = new-pssession -connectionURI <<<< "http://$fqdn/powershell?serializationLevel=Full" -ConfigurationName Microsoft.Exchange -SessionOption $so #-erroraction silentlycontinue
+ CategoryInfo : InvalidArgument: (:) [New-PSSession], ParameterBindingException
+ FullyQualifiedErrorId : CannotConvertArgumentNoMessage,Microsoft.PowerShell.Commands.NewPSSessionCommand
The term 'New-Mailbox' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the
spelling of the name, or if a path was included, verify that the path is correct and try again.
At C:\scripts\addmailbox.ps1:3 char:12
+ New-Mailbox <<<< -UserPrincipalName TESTMAILBOX#MYDOMAIN.com -Alias SOMEALIAS -Name SOMENAME -OrganizationalUnit Users -Password $secure_pwsd -FirstName SOMEFIRSTNAME -LastName SOMELASTNAME -DisplayName "LASTNAME FIRSTNAME" -ResetPasswordOnNextLogon $false
+ CategoryInfo : ObjectNotFound: (New-Mailbox:String) [], CommandNotFoundException
+ FullyQualifiedErrorId : CommandNotFoundException
I repeat that these commands work fine locally on System 2. Direct specification of the FDQN in PS script file doesn't solve the problem. Please, do not suggest to use PsExec instead of WMIC or establish remote connection using PowerShells. Thanks for the advices!
How could i upload a log file from my local system to a webpage (http://abc..) using powershell script?
Thanks in advance
If you are using HTTP, try something like this:
$sourceFilePath = "c:\MyLocalFolder\LocalLogFileName.log"
$siteAddress = "http://192.168.15.12/DestinationFolder"
$urlDest = "{0}/{1}" -f ($siteAddress, "DestinationLogFileName.log";
$webClient = New-Object System.Net.WebClient;
$webClient.Credentials = New-Object System.Net.NetworkCredential("MyUserName", "MyPassword");
("*** Uploading {0} file to {1} ***" -f ($sourceFilePath, $siteAddress) ) | write-host -ForegroundColor Green -BackgroundColor Yellow
$webClient.UploadFile($urlDest, "PUT", $sourceFilePath);