Running PowerShell script for Exchange 2010 remotely using WMIC - powershell-2.0

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!

Related

Unable to run PowerShell Write-EventLog within a DOCKERFILE

In my DOCKERFILE I'm running some PowerShell script which creates a custom event log (on Windows Server), then writes an entry. [I should add that I'm currently doing this only for debug purposes.]
The script/command which creates the event log appear to execute without any problems, but an exception is thrown when writing to the log using...
RUN powershell.exe -command Write-EventLog -LogName "my_log_name" -Source "my_source" -Message "EventLog created by DOCKERFILE." -Category 0 -EventID 0 -EntryType Information
The following exception is thrown...
Write-EventLog : A positional parameter cannot be found that accepts argument
'created'.
At line:1 char:1
+ Write-EventLog -LogName my_log_name -Source my_source -EntryType Messag ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidArgument: (:) [Write-EventLog], Parameter
BindingException
+ FullyQualifiedErrorId : PositionalParameterNotFound,Microsoft.PowerShell
.Commands.WriteEventLogCommand
I also tried wrapping "EventLog created by DOCKERFILE." in parentheses but then it complained about the word by.
Why does it seem unable to parse "EventLog created by DOCKERFILE." as a string argument, but is instead parsing the words within the string?
UPDATE
Even if I wrap the command in double-quotes and the individual strings in single quotes, I get the same error.
UPDATE 2
Removing the quotes and escaping the spaces doesn't work either.
You need to use ` to escape the spaces:
RUN powershell.exe -command Write-EventLog -LogName my_log_name -Source my_source -Message EventLog` created` by` DOCKERFILE. -Category 0 -EventID 0 -EntryType Information
See: https://docs.docker.com/engine/reference/builder/#escape
This works for me from cmd (except for the unknown source). I'm not sure if docker has issues with single quotes. Double quotes are special in cmd. Note that new-winevent has replaced write-eventlog.
powershell write-eventLog my_log_name my_source 0 information 'EventLog created by DOCKERFILE.' -category 0

how do i fix pycharm terminal environment variable path not recognized, i'm trying to get hold of my env. variable using "env" on pycharm terminal

enter image description herethis the error message i got please help!
'''
(venv) PS C:\Users\HP\PycharmProjects\rain-alert> env
env : The term 'env' 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 line:1 char:1
env
+ CategoryInfo : ObjectNotFound: (env:String) [], CommandNotFoundException
+ FullyQualifiedErrorId : CommandNotFoundException
'''

How to install a TFS 2017 agent on Windows Server using Powershell Script?

I am trying to install the VSTS build agent on a Windows Server 2016 using the below Powershell script but the script fails with the below error.
$tfsUrl=”http://vwmaztfsapp:8080/tfs/Collection”
$pool = ”Cli Execution”
$username = ”dev.local\svc_tfsAcc”
$password = ”MyPassword”
$AgentName = "Aut1"
CD "$AgentFolder\vsts-agent-win7-x64-2.122.1-Aut6\"
# configure agent to run as a Windows service that logs on as a domain account
& .\config.cmd --unattended -–url "$tfsUrl" --auth "integrated" -–pool "$pool" -–agent "$AgentName" --work "$AgentFolder\$AgentName" –-runAsService -–windowsLogonAccount "$username" –-windowsLogonPassword "$password"
Error below -
PS C:\Agents\vsts-agent-win7-x64-2.122.1-Aut6> C:\Agents\vsts-agent-win7-x64-2.122.1-Aut6\InstallAgent.ps1
config.cmd : Unrecognized command-line input arguments: 'unattended'. For usage refer to: .\config.cmd --help or ./config.sh --help
At C:\Agents\vsts-agent-win7-x64-2.122.1-Aut6\InstallAgent.ps1:49 char:1
+ & .\config.cmd --unattended -–url "$tfsUrl" --auth "integrated" -–poo ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (Unrecognized co...onfig.sh --help:String) [], RemoteException
+ FullyQualifiedErrorId : NativeCommandError
Is there something that I am missing?
I need to install the agent on multiple servers and that's the reason I want to automate this process.
Update
I was using command without "" such as:
.\config.cmd --unattended --url https://dev.azure.com/patricklu2020 --auth pat --token n2upx6epgl4srovzgp6is5wytjfkspvv6uvxxxx --pool default --agent myAgent --work D:\agent_work
If you want to configure as a service, you need to configure the agent from an elevated PowerShell window, this is required.
I would suggest you directly run the command from an elevated powershell window first, and then check if you are able to configure the agent correctly.
This kind of error maybe caused by passing arguments incorrectly. Kindly verify it.

Error when using Tags during certificate import through Azure PowerShell

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

TFS Build Solution failure: UnauthorizedAccess Microsoft.PowerShell.Commands.ImportModuleCommand

I'm attempting to set up our first build agent for TFS 2017 On-Premise. I've taken a 2012 R2 server, installed the agent and Visual Studio 2017. The agent appears in TFS with the correct capabilities. I've taken one of the default templates for building ASP.net projects and made the minimum changes possible to it. On the first run, I can see the first few steps of getting sources and updating NuGet packages complete successfully. However the build solution step fails, and I'm struggling to understand what the issue may be.
The build log shows the following:
2017-11-15T13:16:10.3583612Z ##[section]Starting: Build solution
2017-11-15T13:16:10.3583612Z ==============================================================================
2017-11-15T13:16:10.3583612Z Task : Visual Studio Build
2017-11-15T13:16:10.3583612Z Description : Build with MSBuild and set the Visual Studio version property
2017-11-15T13:16:10.3583612Z Version : 1.119.0
2017-11-15T13:16:10.3583612Z Author : Microsoft Corporation
2017-11-15T13:16:10.3583612Z Help : [More Information](https://go.microsoft.com/fwlink/?LinkID=613727)
2017-11-15T13:16:10.3583612Z ==============================================================================
2017-11-15T13:16:10.8588602Z Import-Module : AuthorizationManager check failed.
2017-11-15T13:16:10.8588602Z At line:1 char:453
2017-11-15T13:16:10.8588602Z + . ([scriptblock]::Create('if (!$PSHOME) { $null = Get-Item -LiteralPath ''variab ...
2017-11-15T13:16:10.8588602Z + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
2017-11-15T13:16:10.8588602Z + CategoryInfo : SecurityError: (:) [Import-Module], PSSecurityException
2017-11-15T13:16:10.8588602Z + FullyQualifiedErrorId : UnauthorizedAccess,Microsoft.PowerShell.Commands.ImportModuleCommand
2017-11-15T13:16:10.9677474Z Invoke-VstsTaskScript : The term 'Invoke-VstsTaskScript' is not recognized as the name of a cmdlet, function, script
2017-11-15T13:16:10.9677474Z file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct
2017-11-15T13:16:10.9677474Z and try again.
2017-11-15T13:16:10.9677474Z At line:1 char:786
2017-11-15T13:16:10.9677474Z + ... tlyContinue' ; Invoke-VstsTaskScript -ScriptBlock ([scriptblock]::Create('. ''\\ ...
2017-11-15T13:16:10.9677474Z + ~~~~~~~~~~~~~~~~~~~~~
2017-11-15T13:16:10.9677474Z + CategoryInfo : ObjectNotFound: (Invoke-VstsTaskScript:String) [], CommandNotFoundException
2017-11-15T13:16:10.9677474Z + FullyQualifiedErrorId : CommandNotFoundException
2017-11-15T13:16:10.9677474Z
2017-11-15T13:16:10.9989971Z ##[error]Exit code 1 returned from process: file name 'C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe', arguments '-NoLogo -Sta -NoProfile -NonInteractive -ExecutionPolicy Unrestricted -Command ". ([scriptblock]::Create('if (!$PSHOME) { $null = Get-Item -LiteralPath ''variable:PSHOME'' } else { Import-Module -Name ([System.IO.Path]::Combine($PSHOME, ''Modules\Microsoft.PowerShell.Management\Microsoft.PowerShell.Management.psd1'')) ; Import-Module -Name ([System.IO.Path]::Combine($PSHOME, ''Modules\Microsoft.PowerShell.Utility\Microsoft.PowerShell.Utility.psd1'')) }')) 2>&1 | ForEach-Object { Write-Verbose $_.Exception.Message -Verbose } ; Import-Module -Name '\\hidden-unc-path\_tasks\VSBuild_71a9a2d3-a98a-4caa-96ab-affca411ecda\1.119.0\ps_modules\VstsTaskSdk\VstsTaskSdk.psd1' -ArgumentList #{ NonInteractive = $true } -ErrorAction Stop ; $VerbosePreference = 'SilentlyContinue' ; $DebugPreference = 'SilentlyContinue' ; Invoke-VstsTaskScript -ScriptBlock ([scriptblock]::Create('. ''\\hidden-unc-path\_tasks\VSBuild_71a9a2d3-a98a-4caa-96ab-affca411ecda\1.119.0\VSBuild.ps1'''))"'.
2017-11-15T13:16:10.9989971Z ##[section]Finishing: Build solution
Looks like your PowerShell execution mode is set to require signed scripts to execute. The agent requires local unsigned scripts to run:
From an admin PowerShell console, run:
Set-ExecutionPolicy -ExecutionPolicy RemoteSigned
- scope LocalMachine
Then restart the agent.

Resources