Thursday, April 25, 2019

How to get environment variables of the current logged on user, when running scheduled tasks or powershell as the System Account (NtAuthority\System)


While running a scheduled task that I needed to run as the local System account, I noticed that any environment variables were not accessible the normal method inside of Powershell, which was quite the kink. I need access to the logged on user credentials and the documents folder path and there is very little if anything available via search engines that document this, so here we are.

New-PSDrive HKU Registry HKEY_USERS;
$user = get-wmiobject -Class Win32_Computersystem | select Username;
$sid = (New-Object System.Security.Principal.NTAccount($user.UserName)).Translate([System.Security.Principal.SecurityIdentifier]).value;
$val = (Get-Item "HKU:\$sid\Software\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders");
$myDocPath = $val.GetValue("Personal");




If you follow the instructions via this link, you can open powershell as the NTAuthority\System account to test/troubleshoot, etc.
http://powershell-guru.com/powershell-tip-53-run-powershell-as-system/

Enjoy.

Monday, April 22, 2019

Getting and setting IPMI settings through powershell

We had an issue where some servers had IMPI enabled and some did not, in order to get uniformity on > 200 servers, a quick script was developed to read and then set them all to the same value. The racadm commands documented syntax is poor at best unless you want to read through the 200+ plus page manual linked at the bottom of this. Enjoy.


#get command to read values, enable=enabled means that IPMI is enabled

cls

$servers = get-content("\\xxx\c$\Temp\Security Patches\Servers\serversComplete(E2013)-Alphabetical.txt"); # read in a list of servers

foreach ($server in $servers)
{
    $results = Invoke-Command -ComputerName $server -ScriptBlock { racadm get iDRAC.IPMILan }
    foreach ($result in $results)
    {
        if ($result.StartsWith("Enable="))
        {
            Write-Host $server ", IPMI setting is set to: " $result;
        }
    }
}


 # sets ipmi to disabled 
cls

$servers = get-content("\\xxx\c$\Temp\Security Patches\Servers\serversComplete(E2013)-Alphabetical.txt"); # read in a list of servers

foreach ($server in $servers)
{
    $results = Invoke-Command -ComputerName $server -ScriptBlock { racadm set iDRAC.IPMILan.Enable 0 } # 0 to disable, 1 to enable
       Write-Host $server;
       Write-Host $results;
       Write-Host “”;
Write-Host “”;
}


All commands