Need assistance modifying a PowerCLI script - powershell

I was wondering if someone could please help with the following query. We are using the following script to enable Virtualization Based Security on a per VM level.
https://communities.vmware.com/t5/VMware-PowerCLI-Discussions/Turn-on-Virtualization-based-security-...
The script is running from within VMware Realize Automation / Orchestration in order to enable VBS as part of an specific workflow. The modified script for vRA/vRO is below.
The issue that I am having is that VBS can only be enabled when the VM is powered off, in some cases the workflow takes a little longer to run and by then the VM is running already which will make the task (script) to fail.
That being said, I was looking for some way to improve the script a little bit perhaps by adding something to power off the VM if it's running then execute the code in the script and then bring the VM back on. I feel that with something like this hopefully we will make sure that VBS is enabled when the VM is not running and once VBS is enabled it will turn on the VM to proceed. I have unsuccessfully tried to modify the code but I can't find a way to stop and start the VM successfully. Can someone please help?
Thank you
// Input: inputProperties from vRA
var enableVBS = inputProperties.customProperties.enableVBS
if (enableVBS == "true") {
var name = inputProperties.resourceNames[0]
var vms = VcPlugin.getAllVirtualMachines(null, name)
vm = vms[0]
var bootOpts = new VcVirtualMachineBootOptions()
var flags = new VcVirtualMachineFlagInfo()
var spec = new VcVirtualMachineConfigSpec()
bootOpts.efiSecureBootEnabled = true;
flags.vbsEnabled = true;
flags.vvtdEnabled = true;
spec.firmware = VcGuestOsDescriptorFirmwareType.efi;
spec.nestedHVEnabled = true;
spec.bootOptions = bootOpts;
spec.flags = flags;
vm.reconfigVM_Task(spec)
}

Related

Error running PS in .NetCore app - Cannot perform operation because the runspace is not in the 'Opened' state. Current state of runspace is 'Broken'

I'm trying to implement a .NetCore 3.1 console app which needs to run PowerShell scripts. However, when I try run it, I get the following error -
Cannot perform operation because the runspace is not in the 'Opened' state. Current state of runspace is 'Broken'.
The code that runs the PS script is as below:
using System.Management.Automation;
public async Task<string> RunScript(string scriptToRun)
{
// create a new hosted PowerShell instance using the default runspace.
using PowerShell ps = PowerShell.Create();
// specify the script code to run.
ps.AddScript(scriptToRun);
// execute the script and await the result.
var pipelineObjects = await ps.InvokeAsync().ConfigureAwait(false);
// print the resulting pipeline objects to the console.
var output = new StringBuilder();
foreach (var item in pipelineObjects)
{
output.Append(item.BaseObject.ToString());
}
return output.ToString();
}
Any idea what could be the issue?
Resolved this by creating custom runspace.
Refer to this article - How to run powershell core scripts from net core applications

Pass parameters to script using Start-DSCConfiguration

I have a DSC configuration that looks like this
configuration DBServer
{
param(
[PSCredential]$SqlAdminCredential
)
node "localhost"
{
Script ConfigureSSRS {
SetScript = {
& sqlcmd -S $RSConnection -i $DBCreateFile -U $SQLAdminCredential.UserName -P $SQLAdminCredential.GetNetworkCredential().Password
I'm running it on azure VMs using a JSON template deployment with a DSC extension containing this Properties node:
"Properties": {
"SqlAdminCredential": {
"userName": "PrivateSettingsRef:SQLAdmin",
"password": "PrivateSettingsRef:SQLAdminPass"
},
Those two value are indeed defined in the protectedSettings node:
"SQLAdmin": "[parameters('sqlAuthenticationLogin')]",
"SQLAdminPass": "[parameters('sqlAuthenticationPassword')]"
But I keep getting null reference exceptions in the code I listed above whenever I try to use the credentials. I've tried $using:SqlAdminCredential and I believe yesterday I tried $global:SqlAdminCredential as well.
I'm currently attempting to troubleshoot this but I don't like making a change to my configuration and then spending 15 minutes waiting for a deploy to see if it worked. However, I can't figure out how to pass this credential object parameter using Start-DscConfiguration in order to troubleshoot it on an existing VM. How can I do this?
Bonus points if you can fix my actual problem and tell me how to access $SqlAdimCredential from inside ConfigureSSRS.SetScript
For the moment, I have decided to be poorly behaved and do this:
configuration DBServer
{
param(
[PSCredential]$SqlAdminCredential
)
node "localhost"
{
$adminCreds = $SqlAdminCredential #a hack
Script ConfigureSSRS {
SetScript = {
$SqlAdminCredential = $using:adminCreds
I will wait for a better solution but this appears to be working.
You have the following options:
Use the PSDSCRunAsCredential of the Script Resource if you need the entire script to run under a single user.
Create your own DSC Resource that uses PSCredential Parameters.

Need Helping Editing Perl Script for PowerChute Network Shutdown

I found the perl script on the vmware community. The problem is that within APC's PCNS it will not let you specify parameters to run with the script.
The script requires calling on a host-list file Usage: ./shutdownHostViaSOAPAPICall.pl [HOST_FILE]
So I would like to add the hosts I want to shutdown directly into the script instead of having to call a hostlist file.
Can anyone help with this? Here is the Vsphere thread for reference. And so that you can download the script.
https://communities.vmware.com/docs/DOC-11623
Thanks
Replace
my $host_username = 'fillmein';
my $host_password = 'fillmein';
#### DO NOT EDIT PAST HERE ####
my #hostlist;
my ($file,$request,$message,$response,$retval,$cookie);
&verifyUserInput();
&processFile($file);
With
my $host_username = 'yourusername';
my $host_password = 'yourpass';
#### DO NOT EDIT PAST HERE ####
my #hostlist = ("host1.somedomain", ""hostx.somedomain"");
my ($file,$request,$message,$response,$retval,$cookie);
#&verifyUserInput();
#&processFile($file);
I only have 1 host at each site to shut down so this is a clean solution for me.

Setting environment variable before running published application in citrix

I have a published application in my citrix server that flexes based on an environment variable which needs to be set in the server, after the session starts. Is there an easy way to do this?
The easiest way is to use .vbs script to set environment variable and then launch an application.
For example:
set ws = wscript.createobject("WScript.shell")
set systemEnv = wshShell.Environment("SYSTEM")
systemEnv("YourVariable") = "Your value"
ws.run("notepad.exe"), 0, true
Flags:
0 = Hidden
1 = displayed
True = Waits till command has completed before moving to next
False = Does not wait for command to complete before moving to next

Powershell remoting and page file

I wrote a powershell script that connects to a remote machine with the intent of executing a software rollout on said machine. Basically it connects, maps a drive, copies the rollout from the mapped drive to the target machine, then executes a perl script to install the rollout. If I do those steps manually everything works fine. When I try using my script, the perl script fails on the remote machine saying, "The paging file is too small for this operation to complete".
Can someone explain the considerations I need to take into account when operating remotely? I've tried monitoring memory usage and I don't see anything out of the ordinary. Is the page file OS wide or is there some type of per user configuration my script should be setting when it connects?
I can post snippets of my script if needed, but the script is 426 lines so I think it would be overwhelming to post in its entirety.
I found that the remote shells are managed differently than logging onto the box and executing a powershell session. I had to increase the maximum amount of memory available using one of the commands below:
Set-Item WSMan:\localhost\Shell\MaxMemoryPerShellMB 1024
winrm set winrm/config #{MaxMemoryPerShellMB="1024"}
The default is 150MB which didn't cut it in my case. I can't say that I recommend 1GB, I'm just a developer. I tried upping it until I found what worked for me.
I tried this code to run the puppet client as an administrator but the framework still complains with "Access Denied"
Exe (C:\Users\lmo0\AppData\Local\Temp\Microsoft .NET Framework 4 Setup_4.0.30319\Windows6.1-KB958488-v6001-x64.msu) failed with 0x5 - Access is denied. .
using System;
using System.Diagnostics;
namespace RunAsAdmin
{
class Program
{
static void Main(string[] args)
{
Process proc = new Process();
Process p = new Process();
p.StartInfo.FileName = #"powershell.exe";
p.StartInfo.Arguments = #"invoke-command -computername vavt-pmo-sbx24 -ScriptBlock {&'C:\Program Files (x86)\Puppet Labs\Puppet\bin\puppet.bat' agent --test --no-daemonize --verbose --logdest console}";
p.StartInfo.Verb = "runas";
p.StartInfo.UseShellExecute = false;
p.StartInfo.RedirectStandardOutput = true;
p.StartInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
p.Start();
while (p.HasExited == false) {
Console.WriteLine(p.StandardOutput.ReadLine());
}
Console.ReadLine();
p.WaitForExit();
p.Close();
}
}
}