How to debug PowerShell process whithout error message or exception - asp.net-mvc

I am trying to run the following PowerShell script from within my .NET application:
try {
Start-Process "C:\Program Files (x86)\Google\Chrome\Application\chrome.exe" -ArgumentList "--headless --disable-gpu --print-to-pdf=c:\myDir\file.pdf https://www.bing.com"
$x = "Complete"
$x | Out-File C:\myDir\error.txt
}
Catch {
$_ | Out-File C:\myDir\error.txt
}
Simply, the above will create a pdf based upon bing.com website
In my dev environment it runs fine as a PowerShell script. It also runs fine on the production server (again, as a PowerShell script).
The issue occurs when I invoke this PowerShell script from my web app on the production server. My C# code is
var command = "c:\myDir\ps.ps1";
ProcessStartInfo psi = new ProcessStartInfo();
psi.FileName = "powershell.exe";
psi.Arguments = command;
Process process = new Process();
process.StartInfo = psi;
process.Start();
This works fine on my dev machine. It fails on the production server. The error.txt file is written to disc which suggests it's not a permissions issue. However, the content of the error.txt file always shows "complete". It never errors.
So, it appears that the catch in the PowerShell script is never being hit. As such, no error message. There is no exception thrown in the C# code. Regardless, it isn't working.
How can I debug this?
Or, if easier, I'm happy to run the code directly instead of invoking the PowerShell script file but the following also does 'nothing'.
var command = $"\"C:\\Program Files (x86)\\Google\\Chrome\\Application\\chrome.exe\" -ArgumentList \"--no-sandbox --headless --disable-gpu --print-to-pdf={imagePath} {fullUrl}";

I was able to reproduce your problem. It is caused by the fact that web application on your production server is running under the user that is not currently logged in. It is running under identity of assigned application pool. Chrome has known issue of not working correctly if it's launched under the user different from currently logged user. If you check that link, you will see that issue was registered in December 2012 and still is not resolved. You could easily reproduce the problem if launch Chrome under the different user ("Run as different user" in shortcut context menu when called with pressed Shift). In this case Chrome will not open any page and will just show gray screen.
The workaround is to launch Chrome with --no-sandbox switch. Google actually does not recomment this. However if you run Chrome in automated way to access trusted source, I believe it's ok.
So to fix the problem modify start-process in the script in the following way:
start-process "C:\Program Files (x86)\Google\Chrome\Application\chrome.exe" -ArgumentList "--no-sandbox --headless --disable-gpu --print-to-pdf=c:\myDir\file.pdf https://www.bing.com"
UPDATE
I have underestimated the problem at first. Now after additional research and many tried approaches I can propose solution that works.
I didn't manage to fix your current approach of direct launch of powershell and chrome from Web Application. Chrome just fails to start and following errors appear in Event log:
Faulting application name: chrome.exe, version: 64.0.3282.186, time stamp: 0x5a8e38d5
Faulting module name: chrome_elf.dll, version: 64.0.3282.186, time stamp: 0x5a8e1e3d
Exception code: 0x80000003
Fault offset: 0x00000000000309b9
Faulting process id: 0x11524
Faulting application start time: 0x01d3bab1a89e3b4f
Faulting application path: C:\Program Files (x86)\Google\Chrome\Application\chrome.exe
Faulting module path: C:\Program Files (x86)\Google\Chrome\Application\64.0.3282.186\chrome_elf.dll
Report Id: e70a5a36-26a4-11e8-ac26-b8ca3a94ba80
This error occurrs even if you configure application pool to use identity of some existing (ordinary) user that could launch the chrome.
May be it's possible to configure IIS or application pool to prevent these errors but I have not found the way.
My proposal is to switch from starting powershell process from controller action to scheduling a task with Windows task scheduler.
Here are the steps that should be taken to accomplish this task:
On your production server create a user under which the Chrome will be started. I'll refer to created user as 'testuser'.
Login under testuser, start chrome, open some site. Without this step, the flow was not successfully, probably because of missing chrome user account.
Grant "Log on as a batch job" right for testuser. This step is required for successfull execution of scheduled tasks under testuser. The procedure is described in this answer
Add --no-sandbox argument to the script as I described in my initial answer.
Replace the code of Process.Start() with scheduling of the task job.
The easiest way to schedule a task from .Net is via TaskScheduler NuGet. Install it to your application and add following code:
string powerShellScript = #"c:\myDir\ps.ps1";
string userName = #"YOURCOMP\testuser";
string userPassword = "TestPwd123";
using (TaskService ts = new TaskService())
{
TaskDefinition td = ts.NewTask();
td.Triggers.Add(new RegistrationTrigger
{
StartBoundary = DateTime.Now,
EndBoundary = DateTime.Now.AddMinutes(1),
});
td.Settings.DeleteExpiredTaskAfter = TimeSpan.FromSeconds(5);
td.Actions.Add(new ExecAction("powershell.exe", powerShellScript));
ts.RootFolder.RegisterTaskDefinition($#"Print Pdf - {Guid.NewGuid()}", td, createType: TaskCreation.Create, userId: userName, password: userPassword, logonType: TaskLogonType.Password);
}
In above code snippet change the name and password for testuser.
With this approach your script is successfully executed and pdf is printed successfully.
Update by OP
If the above continues to fail, then again, check the Event Viewer logs. In this case, I had an issues with a message similar to The machine-default permission settings do not grant Local Activation permission for the COM Server application with CLSID {20FD4E26-8E0F-4F73-A0E0-F27B8C57BE6F} and APPID Unavailable but it was resolved by granting permissions for the CLSID. Further, try to run the task in task scheduler by itself, such as create a new task to simply launch notepad or similar to make sure that this is working with the account you want to test. In my case, I had to use the administrator account.

I think additional to what CodeFuller said having no sandbox with --no-sandbox option, you should also disable all extensions, sync and bookmarks.
The best is having a Guest session alias "browse without sign-in" with--bwsi option.
What is funny is that during testing I have found out that it is better, got better pdf printout, to disable extensions explicitly with --disable-extensions before doing --bwsi.
I have tested it and for me it works. I'm looking forward for your feedback.
Edit1 and Edit3 - removing try...catch and adding user & password and adding psuser specifics
You are probably on domain so I have adjusting the script to run as different user on domain (the user must have correct rights!)
First create your credentials file with:
Login to user e.g. psuser
Create the password file:
# Encrypt user password and save it to file
Read-Host -AsSecureString | ConvertFrom-SecureString | Out-File 'C:\<your_path>\your_secret_password.txt'
Then run the below improved script with encrypted credentials:
$username = 'psuser' # This needs to be adjusted to correct user you are using
$domain = <your_domain> # adjust to your needs
$encrypted_passwd = get-content 'C:\<your_path>\your_secret_password.txt' | ConvertTo-securestring
# Setting process invocation parameters.
$process_start_info = New-Object -TypeName System.Diagnostics.ProcessStartInfo
$process_start_info.CreateNoWindow = $true
$process_start_info.UseShellExecute = $false
$process_start_info.RedirectStandardOutput = $true
$process_start_info.RedirectStandardError = $true
$process_start_info.UserName = $username
$process_start_info.Domain = $domain
$process_start_info.Password = $encrypted_passwd
$process_start_info.Verb = 'runas'
$process_start_info.FileName = 'C:\Program Files (x86)\Google\Chrome\Application\chrome.exe'
$process_start_info.Arguments = '--no-sandbox --disable-extensions --bwsi --headless --disable-gpu --print-to-pdf=C:\prg\PowerShell\test\chrome_file.pdf https://www.bing.com'
# Creating process object.
$process = New-Object -TypeName System.Diagnostics.Process
$process.StartInfo = $process_start_info
# Start the process
[Void]$process.Start()
$process.WaitForExit()
# synchronous output - captures everything
$output = $process.StandardOutput.ReadToEnd()
$output += $process.StandardError.ReadToEnd()
Write-Output $output
During the script debugging I have encountered these errors:
a) When you want to validate against a AD server but it is not available:
Exception calling "Start" with "0" argument(s): "There are currently no logon servers available to service the logon request"
At C:\prg\PowerShell\test\chrome_print.ps1:56 char:12
+ [Void]$process.Start()
+ ~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : Win32Exception
Exception calling "WaitForExit" with "0" argument(s): "No process is associated with this object."
At C:\prg\PowerShell\test\chrome_print.ps1:58 char:12
+ $process.WaitForExit()
+ ~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : InvalidOperationException
You cannot call a method on a null-valued expression.
At C:\prg\PowerShell\test\chrome_print.ps1:61 char:12
+ $output = $process.StandardOutput.ReadToEnd()
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [], RuntimeException
+ FullyQualifiedErrorId : InvokeMethodOnNull
You cannot call a method on a null-valued expression.
At C:\prg\PowerShell\test\chrome_print.ps1:62 char:12
+ $output += $process.StandardError.ReadToEnd()
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [], RuntimeException
+ FullyQualifiedErrorId : InvokeMethodOnNull
b) Missing domain information in the script:
Exception calling "Start" with "0" argument(s): "The stub received bad data"
At C:\prg\PowerShell\test\chrome_print.ps1:39 char:12
+ [Void]$process.Start()
+ ~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : Win32Exception
Exception calling "WaitForExit" with "0" argument(s): "No process is associated with this object."
At C:\prg\PowerShell\test\chrome_print.ps1:41 char:12
+ $process.WaitForExit()
+ ~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : InvalidOperationException
You cannot call a method on a null-valued expression.
At C:\prg\PowerShell\test\chrome_print.ps1:44 char:12
+ $output = $process.StandardOutput.ReadToEnd()
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [], RuntimeException
+ FullyQualifiedErrorId : InvokeMethodOnNull
You cannot call a method on a null-valued expression.
At C:\prg\PowerShell\test\chrome_print.ps1:45 char:12
+ $output += $process.StandardError.ReadToEnd()
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [], RuntimeException
+ FullyQualifiedErrorId : InvokeMethodOnNull
Prints the pdf
and the stderr messages:
[0313/112937.660:ERROR:gpu_process_transport_factory.cc(1009)] Lost UI shared context.
[0313/112937.662:ERROR:instance.cc(49)] Unable to locate service manifest for metrics
[0313/112937.662:ERROR:service_manager.cc(890)] Failed to resolve service name: metrics
[0313/112938.152:ERROR:instance.cc(49)] Unable to locate service manifest for metrics
[0313/112938.153:ERROR:service_manager.cc(890)] Failed to resolve service name: metrics
[0313/112942.876:INFO:headless_shell.cc(566)] Written to file C:\prg\PowerShell\test\chrom e_file.pdf.
Edit2 Adding windows account impersonation with ASP.NET
Impersonate a windows account with ASP.NET:
ASP.NET user is not passed into the new threads (by default). When you want to invoke PowerShell script it is invoked in other thread with different credentials (you can overcome that with above script when you have a dedicated domain authenticated user for running the above script). By default the script is executed under build-in account NT AUTHORITY\NETWORK SERVICE.
These steps are to overcome it on ASP.NET level:
1) Enable Windows Authentication in IIS
a) Install it first (this is windows 2008 R2 screenshot):
b) enable it on your IIS:
Change it to enabled:
2) Change your site's web.config to correctly handle impersonation
Edit the web.config file in your site’s directory. In order to execute the server side code of the current user's security context (AD).
Find the xml tag: <system.web> and add two new elements to enable the windows authentication
<authentication mode="Windows" />
<identity impersonate="True" />
3) To correctly write code to invoke in-process PowerShell script
You need to adjust your ASP.NET code in a way that you will have powershell Runspace and you will invoke the script inside the Runspace in a pipeline
A quick example:
// You need to create a Runspace. Each other pipeline you create will run in the same Runspace
// Do it only once, all others will be pipelined
RunspaceConfiguration powershellConfiguration = RunspaceConfiguration.Create();
var powershellRunspace = RunspaceFactory.CreateRunspace(powershellConfiguration);
powershellRunspace.Open();
// create a pipeline the cmdlet invocation
using ( Pipeline psPipeline = powershellRunspace.CreatePipeline() ){
// Define the command to be executed in this pipeline
Command script = new Command("PowerShell_script");
// Add any parameter(s) to the command
script.Parameters.Add("Param1", "Param1Value");
// Add it to the pipeline
psPipeline.Commands.Add(script);
try {
// Invoke() the script
var results = psPipeline.Invoke();
// work with the results
} catch (CmdletInvocationException exception) {
// Any exceptions here - for the invoked process
}
}
4) Modify aspnet.config to allow impersonation to cross threads
This step allows you to run as your current, impersonated, user.
You have to modify your servers’s aspnet.config file.
Add two xml elements to the configuration and runtime:
<configuration>
<runtime>
...
<legacyImpersonationPolicy enabled="true" />
<alwaysFlowImpersonationPolicy enabled="false" />
</runtime>
</configuration>

You have to redirect the stdin and stdout so that it sends it from powershell.exe back to the parent process (your web app). I modified your code sample to do this:
var command = "c:\myDir\ps.ps1";
ProcessStartInfo psi = new ProcessStartInfo();
psi.FileName = "powershell.exe";
psi.Arguments = command;
psi.RedirectStandardOutput = true;
psi.RedirectStandardError = true;
Process process = new Process();
process.StartInfo = psi;
process.Start();
process.WaitForExit();
Console.WriteLine(process.StandardOutput);
Console.WriteLine(process.StandardError);

Related

Jenkins Windows Batch Script failing to find COM object

I have a script that updates an Install Shield .ism file (via InstallShield Automation Interface (2015)) with a version and ProductCode.
Dim projFile, projVersion
'check for arguments
If Wscript.Arguments.Count < 2 Then
WScript.Echo "InstallShield Version Utility" & _
vbNewLine & "1st argument is the full path to the .ism file" & _
vbNewLine & "2nd argument is the new version number Major.Minor.Build"
WScript.Quit 1
End If
'get the args
projFile = WScript.Arguments(0)
projVersion = WScript.Arguments(1)
'Create the end-user automation object
Dim ISWIProject
Set ISWIProject = CreateObject("ISWiAuto22.ISWiProject"): CheckError
'Open the project specified at the command line
ISWIProject.OpenProject projFile: CheckError
'change the product code to force major upgrades
Dim guidProductCode
guidProductCode = ISWIProject.GenerateGUID
ISWIProject.ProductCode = guidProductCode
'update the version
ISWIProject.ProductVersion = projVersion
'Save and close the project
ISWIProject.SaveProject: CheckError
ISWIProject.CloseProject: CheckError
WScript.Echo "Updated guid to: " & guidProductCode & ", version to: " & projVersion
Sub CheckError()
Dim message, errRec
If Err = 0 Then Exit Sub
message = Err.Source & " " & Hex(Err) & ": " & Err.Description
WScript.Echo message
WScript.Quit 2
End Sub
I call this script with
cscript //Nologo setInstallShieldVersion.vbs <ISMPath> <VersionNumber>
When I run this via a command line on the machine (with the same user as my Jenkins service), it works fine and runs the script. However when Jenkins runs it via a Windows batch command, it gives the error
setInstallShieldVersion.vbs(17, 1) Microsoft VBScript runtime error: File not found: 'CreateObject'
the script used to work, then I had to update Jenkins (and subsequently rolled it back when the script started failing). Maybe that's part of the issue?
I've tried dumping the environmental variables with SET in both instances, and all the environmental variables are the same (except some Jenkins-specific ones). I've registered the DLL with regsvr32 multiple times. In both instances they are running in 32 bit processes. I've even opened up the permissions on the .dll (ISWiAutomation22.dll). Any other ideas on why it would work when running it one way and not the other?

Windows Etsy: Peer certificate cannot be authenticated with given CA certificates

In an effort to be OAuth'd with Etsy, I have tried countless solutions in C# to at least start the authentication process (ie get the login URL):
eg
mashery.com, http://term.ie/oauth/example/client.php and question #8321034
but the response is always the same:
oauth_problem=signature_invalid&debug_sbs=GET&https%3A%2F%2Fopenapi.etsy.com%2Fv2%2Foauth%2Frequest_token&oauth_consumer_key%3D...my-consumer-key...%26oauth_nonce%3D2de91e1361d1906bbae04b15f42ab38d%26oauth_signature_method%3DHMAC-SHA1%26oauth_timestamp%3D1502362164%26oauth_version%3D1.0%26scope%3Dlistings_w%2520listings_r
and so I'm resorting to the dreaded world of PHP...
On my machine, I've installed the following (Windows 10):
XAMPP (xampp-win32-7.1.7-0-VC14-installer) with default options
JDK (jdk-8u144-windows-i586)
JRE (jre-8u144-windows-i586)
php_oauth.dll ([php_oauth-2.0.2-7.1-ts-vc14-x86.zip][4]) and copying it to C:\xampp\php\ext
[cacert.pem][4], (dated Jun 7 03:12:05 2017) and coping it to the following directories:
C:\xampp\perl\vendor\lib\Mozilla\CA
C:\xampp\phpMyAdmin\vendor\guzzle\guzzle\src\Guzzle\Http\Resources
Apache and Tomcat would not run to begin with from XAMPP because it said that ports 443 and 80 were being used/blocked and so I duly changed these to 444 and 122 in
C:\xampp\apache\conf\extra\httpd-ssl.conf
C:\xampp\apache\conf\httpd.conf
All good so far but when I run the following script in my browser (http://localhost:444/dashboard/etsy.php):
<?php
$base_uri = 'https://openapi.etsy.com';
$api_key = 'my-etsy-api-key';
$secret = 'my-etsy-api-secret';
$oauth = new OAuth($api_key, $secret, OAUTH_SIG_METHOD_HMACSHA1, OAUTH_AUTH_TYPE_URI);
$req_token = $oauth->getRequestToken($base_uri .= "/v2/oauth/request_token?scope=listings_w%20transactions_r", 'oob');
$login_url = $req_token['login_url'];
print "Please log in and allow access: $login_url \n\n";
$verifier = readline("Please enter verifier: ");
$verifier = trim($verifier);
$oauth->setToken($req_token['oauth_token'], $req_token['oauth_token_secret']);
$acc_token = $oauth->getAccessToken($base_uri .= "/v2/oauth/access_token", null, $verifier);
$oauth_token = $acc_token['oauth_token'];
$oauth_token_secret = $acc_token['oauth_token_secret'];
$oauth->setToken($oauth_token, $oauth_token_secret);
print "Token: $oauth_token \n\n";
print "Secret: $oauth_token_secret \n\n";
?>
I get the following error message:
Fatal error: Uncaught OAuthException: making the request failed (Peer
certificate cannot be authenticated with given CA certificates) in
C:\xampp\htdocs\dashboard\etsy.php:8 Stack trace: #0
C:\xampp\htdocs\dashboard\etsy.php(8):
OAuth->getRequestToken('https://openapi...', 'oob') #1 {main} thrown
in C:\xampp\htdocs\dashboard\etsy.php on line 8
I've tried running the script with each thread safe, x86 version of OAuth (http://windows.php.net/downloads/pecl/releases) - stop, restart Apache) but no luck.
I'm at my wits end.
How to I resolve this Peer certificate problem?
Simply disable the SSL on local.
$oauth->disableSSLChecks()
Oauth by default using CURL SSL Certificate. The simple way for local apache server is to disable it. Either configure the SSL for the CURL. It will also resolve the issue for oauth.
as per php documentation
we can set the certificate path simply.
$oauth->setCAPath("F:\xampp\php\extras\ssl\cacert.pem");
print_r($oauth->getCAPath());
You can also set the request engine to curl or php stream if the ssl is already configured.
Official PHP documentation

symfony/yaml backed symfony/config not parsing environment variables

I have recreated a simple example in this tiny github repo. I am attempting to use symfony/dependency-injection to configure monolog/monolog to write logs to php://stderr. I am using a yaml file called services.yml to configure dependency injection.
This all works fine if my yml file looks like this:
parameters:
log.file: 'php://stderr'
log.level: 'DEBUG'
services:
stream_handler:
class: \Monolog\Handler\StreamHandler
arguments:
- '%log.file%'
- '%log.level%'
log:
class: \Monolog\Logger
arguments: [ 'default', ['#stream_handler'] ]
However, my goal is to read the path of the log files and the log level from environment variables, $APP_LOG and LOG_LEVEL respectively. According to The symphony documentations on external paramaters the correct way to do that in the services.yml file is like this:
parameters:
log.file: '%env(APP_LOG)%'
log.level: '%env(LOGGING_LEVEL)%'
In my sample app I verified PHP can read these environment variables with the following:
echo "Hello World!\n\n";
echo 'APP_LOG=' . (getenv('APP_LOG') ?? '__NULL__') . "\n";
echo 'LOG_LEVEL=' . (getenv('LOG_LEVEL') ?? '__NULL__') . "\n";
Which writes the following to the browser when I use my original services.yml with hard coded values.:
Hello World!
APP_LOG=php://stderr
LOG_LEVEL=debug
However, if I use the %env(VAR_NAME)% syntax in services.yml, I get the following error:
Fatal error: Uncaught UnexpectedValueException: The stream or file "env_PATH_a61e1e48db268605210ee2286597d6fb" could not be opened: failed to open stream: Permission denied in /var/www/vendor/monolog/monolog/src/Monolog/Handler/StreamHandler.php:107 Stack trace: #0 /var/www/vendor/monolog/monolog/src/Monolog/Handler/AbstractProcessingHandler.php(37): Monolog\Handler\StreamHandler->write(Array) #1 /var/www/vendor/monolog/monolog/src/Monolog/Logger.php(337): Monolog\Handler\AbstractProcessingHandler->handle(Array) #2 /var/www/vendor/monolog/monolog/src/Monolog/Logger.php(532): Monolog\Logger->addRecord(100, 'Initialized dep...', Array) #3 /var/www/html/index.php(17): Monolog\Logger->debug('Initialized dep...') #4 {main} thrown in /var/www/vendor/monolog/monolog/src/Monolog/Handler/StreamHandler.php on line 107
What am I doing wrong?
Ok you need a few things here. First of all you need version 3.3 of Symfony, which is still in beta. 3.2 was the released version when I encountered this. Second you need to "compile" the environment variables.
Edit your composer.json with the following values and run composer update. You might need to update other dependencies. You can substitute ^3.3 with dev-master.
"symfony/config": "^3.3",
"symfony/console": "^3.3",
"symfony/dependency-injection": "^3.3",
"symfony/yaml": "^3.3",
You will likely have to do this for symfony/__WHATEVER__ if you have other symfony components.
Now in you're code after you load your yaml configuration into your dependency container you compile it.
So after you're lines here (perhaps in bin/console):
$container = new ContainerBuilder();
$loader = new YamlFileLoader($container, new FileLocator(__DIR__ . DIRECTORY_SEPARATOR . '..'));
$loader->load('services.yml');
Do this:
$container->compile(true);
Your IDE's intellisense might tell you compile takes no parameters. That's ok. That's because compile() grabs its args indirectly via func_get_arg().
public function compile(/*$resolveEnvPlaceholders = false*/)
{
if (1 <= func_num_args()) {
$resolveEnvPlaceholders = func_get_arg(0);
} else {
. . .
}
References
Github issue where this was discussed
Pull request to add compile(true)
Using this command after loading your services.yaml file should help.
$containerBuilder->compile(true);
given your files gets also validated by the checks for proper configurations which this method also does. The parameter is $resolveEnvPlaceholders which makes environmental variables accessible to the yaml services configuration.

Add-AzureKeyVaultKey fails with Operation "import" is not allowed

I was able to create Azure key value successfully but I am unable import the PFX file successfully. Here is the command I used:
$securepfxpwd = ConvertTo-SecureString –String '123' –AsPlainText –Force
$key1 = Add-AzureKeyVaultKey -VaultName 'MyKeyVault' -Name 'MyKey' -KeyFilePath 'C:\mycert.io.pfx' -KeyFilePassword $securepfxpwd
Here is the error I am getting:
Add-AzureKeyVaultKey : **Operation "import" is not allowed**
At line:1 char:9
+ $key1 = Add-AzureKeyVaultKey -VaultName 'MyKeyVault' -Name 'MyKey ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : CloseError: (:) [Add-AzureKeyVaultKey], KeyVaultClientException
+ FullyQualifiedErrorId : Microsoft.Azure.Commands.KeyVault.AddAzureKeyVaultKey*
When I used command: Get-AzureRmKeyVault, I got following information for access keys:
*SKU : Standard
Enabled For Deployment? : False
Enabled For Template Deployment? : False
Enabled For Disk Encryption? : False
**Access Policies :**
Tags :*
Here are my questions:
Should I be giving myself permissions to import using Set-AzureRmKeyVaultAccessPolicy?
If so, what would be the parameters for this command to give myself permissions to import the cert?
Just had this issue today.
https://blogs.technet.microsoft.com/kv/2016/09/26/get-started-with-azure-key-vault-certificates/
Set-AzureRmKeyVaultAccessPolicy -VaultName $vaultName -UserPrincipalName $upn -PermissionsToCertificates all
Valid values are get, list, delete, create, import, update, managecontacts, getissuers, listissuers, setissuers, deleteissuers, all
https://learn.microsoft.com/en-us/powershell/resourcemanager/azurerm.keyvault/v2.5.0/set-azurermkeyvaultaccesspolicy

Connecting to Active Directory

I have the following script from a book. When I try to run this, I get nothing output to the screen.
$objADSI = [adsi]""
$domain = $objADSI.distinguishedname
$userContainer = [adsi]("LDAP://cn=users," + $domain)
foreach($child in $userContainer) {
Write-Host $child.samaccountname
}
If I echo $userContainer, I get:
distinguishedName : {CN=Users,DC=company,DC=co,DC=uk}
Path : LDAP://cn=users,DC=company,DC=co,DC=uk
Do I need to run winrm quickconfig on the Active Directory server? The Active Directory server is running Windows Server 2003 standard edition. Or am I getting nothing returned for some other reason?
Change your foreach like this:
foreach($child in $userContainer.children)

Resources