Ansible not running command or script in powershell elevated mode - windows

I have tried 3 different task methods to get Ansible to execute a powershell command or a ps1 script with the command in an elevated Administrator shell. I am a DOMAIN Admin and the computer is domain joined. All other powershell module tasks prior to this one work with my domain admin SA account. The command in the problem task is Import-Module -Name DellBIOSProvider -Verbose -Force. When I test this locally under my DOMAIN admin account it fails at the operation of ..New-PSDrive.. could not be created, please run with Administrator privileges. So to get it working I have to run powershell as Admin (system32) and the Import-Module command completes the New-PSDrive operation without fail. But Ansible is not executing the command or ps1 script in elevated mode it seems even with me using become_method become and become_user for local-admin execution.
I have searched for days on how to get this to work. I found one other person that describes my problem on github but the conversation was then moved to private Github issue and I found this info on stackoverflow Powershell script in elevated mode . None of these implementations work. The output of Get-PSDrive should show the DellSmBIOS PS drive after successful import so that subsequent tasks can use the new ps-drive for pwrsh configuration calls but the it is not there because Ansible is running it under my domain admin sa account.
Output when attempting to import module with my domain admin account in pwrsh:
PS C:\Users\arichardson.sa> Import-Module -Name DellBIOSProvider -Verbose -Force
VERBOSE: Loading module from path 'C:\Program Files\WindowsPowerShell\Modules\DellBIOSProvider\2.6.0\DellBIOSProvider.psd1'.
VERBOSE: Populating RepositorySourceLocation property for module DellBIOSProvider.
VERBOSE: Loading module from path 'C:\Program Files\WindowsPowerShell\Modules\DellBIOSProvider\2.6.0\DellBIOSProvider.psm1'.
VERBOSE: Exporting function 'Set-Dell1stBootdevice'.
VERBOSE: Exporting function 'Get-DellBiosSettings'.
VERBOSE: Exporting function 'Clear-DellAdminPassword'.
VERBOSE: Exporting function 'Set-DellAutoOnForSelectDays'.
VERBOSE: Importing function 'Clear-DellAdminPassword'.
VERBOSE: Importing function 'Get-DellBiosSettings'.
VERBOSE: Importing function 'Set-Dell1stBootdevice'.
VERBOSE: Importing function 'Set-DellAutoOnForSelectDays'.
VERBOSE: Loading module from path 'C:\Program Files\WindowsPowerShell\Modules\DellBIOSProvider\2.6.0\DellBIOSProvider.dll'.
VERBOSE: Starting PS provider DellSmbiosProv
VERBOSE: .NET Version: 4.0.30319.42000
VERBOSE: Performing InitializeDefaultDrives operation on the 'DellSmbiosProv'provider.
VERBOSE: Performing operation New-PSDrive for the provider DellSmbiosProv.
WARNING: Please execute this program with "Administrator" privileges.
Import-Module : PS drive DellSmbios could not be created.
At line:1 char:1
+ Import-Module -Name DellBIOSProvider -Verbose -Force
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : OpenError: (DellSmbios:PSDriveInfo) [Import-Module], InvalidOperationException
+ FullyQualifiedErrorId : DefaultDriveInitFailed,Microsoft.PowerShell.Commands.ImportModuleCommand
VERBOSE: Exporting function 'Clear-DellAdminPassword'.
VERBOSE: Exporting function 'Get-DellBiosSettings'.
VERBOSE: Exporting function 'Set-Dell1stBootdevice'.
VERBOSE: Exporting function 'Set-DellAutoOnForSelectDays'.
VERBOSE: Importing function 'Clear-DellAdminPassword'.
VERBOSE: Importing function 'Get-DellBiosSettings'.
VERBOSE: Importing function 'Set-Dell1stBootdevice'.
VERBOSE: Importing function 'Set-DellAutoOnForSelectDays'.
PS C:\Users\arichardson.sa>
Output when executing from Elevated shell:
PS C:\Windows\system32> Import-Module -Name DellBIOSProvider -Verbose -Force
VERBOSE: Loading module from path 'C:\Program Files\WindowsPowerShell\Modules\DellBIOSProvider\2.6.0\DellBIOSProvider.psd1'.
VERBOSE: Populating RepositorySourceLocation property for module DellBIOSProvider.
VERBOSE: Loading module from path 'C:\Program Files\WindowsPowerShell\Modules\DellBIOSProvider\2.6.0\DellBIOSProvider.psm1'.
VERBOSE: Exporting function 'Set-Dell1stBootdevice'.
VERBOSE: Exporting function 'Get-DellBiosSettings'.
VERBOSE: Exporting function 'Clear-DellAdminPassword'.
VERBOSE: Exporting function 'Set-DellAutoOnForSelectDays'.
VERBOSE: Importing function 'Clear-DellAdminPassword'.
VERBOSE: Importing function 'Get-DellBiosSettings'.
VERBOSE: Importing function 'Set-Dell1stBootdevice'.
VERBOSE: Importing function 'Set-DellAutoOnForSelectDays'.
VERBOSE: Loading module from path 'C:\Program Files\WindowsPowerShell\Modules\DellBIOSProvider\2.6.0\DellBIOSProvider.dll'.
VERBOSE: Starting PS provider DellSmbiosProv
VERBOSE: .NET Version: 4.0.30319.42000
VERBOSE: Performing InitializeDefaultDrives operation on the 'DellSmbiosProv'provider.
VERBOSE: Performing operation New-PSDrive for the provider DellSmbiosProv.
VERBOSE: Category 'Passwords' does not contain any supported attributes.
VERBOSE: Category 'BIOSSetupAdvancedMode' does not contain any supported attributes.
VERBOSE: Category 'StealthModeControl' does not contain any supported attributes.
VERBOSE: Category 'AdvancedConfigurations' does not contain any supported attributes.
VERBOSE: Category 'ThermalConfiguration' does not contain any supported attributes.
VERBOSE: To get more help about the Dell Command PowerShell provider, type Get-Help DellBIOSProvider.
VERBOSE: Exporting function 'Clear-DellAdminPassword'.
VERBOSE: Exporting function 'Get-DellBiosSettings'.
VERBOSE: Exporting function 'Set-Dell1stBootdevice'.
VERBOSE: Exporting function 'Set-DellAutoOnForSelectDays'.
VERBOSE: Importing function 'Clear-DellAdminPassword'.
VERBOSE: Importing function 'Get-DellBiosSettings'.
VERBOSE: Importing function 'Set-Dell1stBootdevice'.
VERBOSE: Importing function 'Set-DellAutoOnForSelectDays'.
PS C:\Windows\system32>
Output showing my user account is an admin:
C:\Users\arichardson.sa>net user arichardson.sa /DOMAIN
The request will be processed at a domain controller for domain xxxx.xxxx.xxxx
User name arichardson.sa
Full Name
Comment
User's comment
Country/region code 000 (System Default)
Account active Yes
Account expires Never
Password last set 3/20/2022 10:00:43 PM
Password expires Never
Password changeable 3/20/2022 10:00:43 PM
Password required Yes
User may change password Yes
Workstations allowed All
Logon script
User profile
Home directory
Last logon 9/1/2022 11:35:56 AM
Logon hours allowed All
Local Group Memberships
Global Group memberships *RADIUS-NAC *Enterprise Admins
*Domain Users *Domain Admins
The command completed successfully.
C:\Users\arichardson.sa>net localgroup Administrators
Alias name Administrators
Comment Administrators have complete and unrestricted access to the computer/domain
Members
-------------------------------------------------------------------------------
Administrator
AMERICA\Domain Admins
local-admin
The command completed successfully.
C:\Users\arichardson.sa>

Turns out, Ansible creates a new PS session with each task so I ended up just having a single Ansible task that executes one powershell script which contains all the cmdlets within and it worked.

Related

PowerShell: Cmdlet Connect-MicrosoftTeams not found although the binary is loaded

I do have a problem getting the MicrosoftTeams module loaded in PowerShell. I downloaded and imported the module with AllSigned authorization (no errors):
PS C:\WINDOWS\system32> Install-Module -Name MicrosoftTeams
PS C:\WINDOWS\system32> Import-Module MicrosoftTeams
Checking, whether the Module is loaded correctly, I also printed the available modules where it is displayed with the current version number:
PS C:\WINDOWS\system32> get-module -listavailable
Verzeichnis: C:\Program Files\WindowsPowerShell\Modules
ModuleType Version Name ExportedCommands
---------- ------- ---- ----------------
Script 1.0.1 Microsoft.PowerShell.Operation.V... {Get-OperationValidation, Invoke-OperationValidation}
Binary 1.1.4 MicrosoftTeams {Add-TeamUser, Connect-MicrosoftTeams, Disconnect-Microsof...
Binary 1.0.0.1 PackageManagement {Find-Package, Get-Package, Get-PackageProvider, Get-Packa...
Script 3.4.0 Pester {Describe, Context, It, Should...}
Script 1.0.0.1 PowerShellGet {Install-Module, Find-Module, Save-Module, Update-Module...}
Script 2.0.0 PSReadline {Get-PSReadLineKeyHandler, Set-PSReadLineKeyHandler, Remov...
Now, I wanted to connect to the Teams using the cmdlet Connect-MicrosoftTeams which is explicitly listed as one of the exported cmdlets in this imported module. But somehow, PowerShell does not find the command:
PS C:\WINDOWS\system32> Connect-MicrosoftTeams
Connect-MicrosoftTeams : Die Benennung "Connect-MicrosoftTeams" wurde nicht als Name eines Cmdlet, einer Funktion,
einer Skriptdatei oder eines ausführbaren Programms erkannt. Überprüfen Sie die Schreibweise des Namens, oder ob der
Pfad korrekt ist (sofern enthalten), und wiederholen Sie den Vorgang.
In Zeile:1 Zeichen:1
+ Connect-MicrosoftTeams
+ ~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : ObjectNotFound: (Connect-MicrosoftTeams:String) [], CommandNotFoundException
+ FullyQualifiedErrorId : CommandNotFoundException
[Excuse the German: It reads: The name was not recognized as cmdlet or name of a function. But you probably know the message if you use PS]
Now, my question is: How can I get PS to recognize the command and how do I find out where the error lies? Is there a command to list the currently running scripts and available commands? Or is there a possibility to force the script to be executed?
I can see the output shows you have installed the module successfully. However, it seems to have some problem. I suggest you re-install it to see how it goes:
Run Windows PowerShell as an administrator
Run the command Uninstall-Module MicrosoftTeams,close PowerShell and re-open a new
elevated PowerShell session
Run the command Install-Module MicrosoftTeams,related doc.
https://learn.microsoft.com/en-us/microsoftteams/teams-powershell-install
After it is installed successfully,please Close PowerShell and re-open a new elevated PowerShell session as an administrator,run Connect-MicrosoftTeams again and see whether it works now. If the same issue persists,attach the screenshot of the entire output for further check.
I had to install the "Skype for Business Online, Windows PowerShell Module" to get Connect-MicrosoftTeams
https://www.microsoft.com/en-us/download/details.aspx?id=39366

How to deploy SSIS project with encrypted data?

We have a SSIS project where one of the packages is connecting to a REST API. We use the HTTP connection manager (with username/password) and a script component to open the connection manager and parse the response. Protection level for all packages are EncryptSensitiveWithUserKey. Everything works in Visual Studio, and can be deployed with Deployment Wizard to the SSIS-DB. In the SSIS-DB we can run the package, and also change connection manager password/username via environments.
But we are not able to achieve this via our normal automated deployment: Check-in to TFS and use VSTS-buildserver with Powershell scripts. When running the package from SSIS-db we get:
Failed to decrypt protected XML node "DTS:Property" with error 0x80070002 "The system cannot find the file specified.".
You may not be authorized to access this information. This error occurs when there is a cryptographic error. Verify that the correct key is available.
We (believe we) know how SSIS protection levels and encryption works, and the cause is obvious: The SSIS file is encrypted with user key, and the Deployment Wizard (run by developer!) decrypts/re-encrypts with the SSIS-catalog key. But the build server does not have the user key, hence the decryption-step is invalid.
However, we would expect that this should not be an issue, since the password is replaced by the SSIS-environment, but is gives the above error.
We have tried all protection levels:
DontSaveSensitive: Package can't run in either VS/SSISDB.
EncryptSensitiveWithPassword: Passwords are unsupported in the PowerShell $folder.DeployProject command. Same method as here.
With EncryptSensitiveWithUserKey mode, you can try to setup build/release agent on your machine and change service account to your account, then deploy through this agent.
I am encountering the same problem now with Azure DevOps and the SSIS DevOps tasks targeting SQL Server 2016.
I suspect that using the Microsoft.SQLServer.Management.IntegrationServices assembly behaves differently to the ISDeploymentWizard executable.
I have found that this issue occurs for sensitive package parameters only and not project parameters so one solution is to replace your sensitive package parameters with project parameters.
The issue would occur when running the package with the sensitive package parameter from the catalog but in some cases the package would run without issue when executed as a child package.
I also found that some packages would report successful package execution but looking at the event messages the Failed to decrypt protected XML node "DTS:Property" with error 0x80070002 would be present.
An alternative solution is to execute the ISDeploymentWizard from the command line. This does require that the target catalog folder already exists as the wizard will not create it. Therefore a step is needed before this to create the catalog folder if it does not already exist.
PowerShell script below should work for SQL Server 2016 as is:
### Variables
$targetServer = "localhost"
$targetCatalogFolder = "IsDeploymentWizard"
$sourceFolder = "C:\Users\mhept\source\repos\SsisDeploy\AzureDevOpsSensitiveInChildPackage"
### Ensure Target Catalog Folder Exists
Add-Type -AssemblyName "Microsoft.SQLServer.Management.IntegrationServices, Version=13.0.0.0, Culture=neutral, PublicKeyToken=89845dcd8080cc91, processorArchitecture=MSIL"
$ssisNamespace = "Microsoft.SqlServer.Management.IntegrationServices"
# Create a connection to the server
$sqlConnectionString = "Data Source=" + $targetServer + ";Initial Catalog=master;Integrated Security=SSPI;"
$sqlConnection = New-Object System.Data.SqlClient.SqlConnection $sqlConnectionString
# Create the Integration Services object
$integrationServices = New-Object $ssisNamespace".IntegrationServices" $sqlConnection
# Get the Integration Services catalog
$catalog = $integrationServices.Catalogs["SSISDB"]
$catalogFolder = $catalog.Folders[$targetCatalogFolder]
if($null -eq $catalogFolder){
# Create the target folder
Write-Host "Creating Catalog Folder $targetCatalogFolder"
$catalogFolder = New-Object $ssisNamespace".CatalogFolder" ($catalog, $targetCatalogFolder, "")
$catalogFolder.Create()
}
$targetCatalogPath = "/SSISDB/$targetCatalogFolder"
$ispacs = Get-ChildItem -Path $sourceFolder -Filter "*.ispac" -Recurse
$isDeploymentWizard = Get-ItemPropertyValue -Path "HKLM:\SOFTWARE\Microsoft\Microsoft SQL Server\130\SSIS\Setup\DeploymentWizardPath" -Name "(default)"
foreach($ispac in $ispacs) {
$projectName = $ispac.BaseName
$sourcePath = $ispac.FullName
Write-Host "Deploying $projectName ..."
Start-Process -Wait -FilePath $isDeploymentWizard -ArgumentList "/Silent", "/SourceType:File", "/ModelType:Project", "/SourcePath:$sourcePath", "/DestinationServer:$targetServer", "/DestinationPath:$targetCatalogPath/$projectName"
Write-Host "Successfully deployed $projectName"
}

Neo4j 3.0.4 Enterprise trial version failed to start in Windows

Neo4j 3.0.4 enterprise version, while trying to install-service or start its show below error. Have tried in different machine also, how to resolve this ?
E:\Neo4j\neo4j-enterprise-3.0.4\bin>neo4j.bat install-service -verbose
VERBOSE: Neo4j Root is 'E:\Neo4j\neo4j-enterprise-3.0.4'
VERBOSE: Neo4j Server Type is 'Enterprise'
VERBOSE: Neo4j Version is '3.0.4'
VERBOSE: Neo4j Database Mode is ''
VERBOSE: Install command specified
VERBOSE: Neo4j Windows Service Name is neo4j
VERBOSE: Java detected at 'C:\Program Files\Java\jdk1.8.0_92\jre\bin\java.exe'
VERBOSE: Executing C:\Program Files\Java\jdk1.8.0_92\jre\bin\java.exe -version
VERBOSE: Java version response: java version "1.8.0_92"
Java(TM) SE Runtime Environment (build 1.8.0_92-b14)
Java HotSpot(TM) 64-Bit Server VM (build 25.92-b14, mixed mode)
VERBOSE: Java Version detected as 1.8.0_92
VERBOSE: Neo4j Windows Service Name is neo4j
VERBOSE: Reading JVM settings from neo4j-wrapper.conf
Invoke-Neo4j : Method invocation failed because [System.Object[]] doesn't contain a method named 'contains'.
At line:1 char:221
+ try { Unblock-File -Path 'E:\Neo4j\neo4j-enterprise-3.0.4\bin\Neo4j-Management\*.*' -ErrorAction 'SilentlyContinue' } catch {};Import-Module 'E:\Neo4j\neo4j-enterprise-3.0.4\bin\Neo4j-Management.psd1'; Exit (Invoke-Neo4j <<<< install-service -verbose)
+ CategoryInfo : NotSpecified: (:) [Write-Error], WriteErrorException
+ FullyQualifiedErrorId : Microsoft.PowerShell.Commands.WriteErrorException,Invoke-Neo4j
The Merge-Neo4jJavaSettings.ps1 file in the bin/Neo4j-Management folder has a syntax error in line #68:
If (-not $Source.contains($thisSetting)) {
Should be
If (-not $Source -contains $thisSetting) {
For the record, this is occurring for me with the Community edition, so it appears to be a problem with both versions.

Unable to set certificate friendly name through PowerShell (access is denied)

I'm trying to update a (root) certificate's friendly name through PowerShell.
The certificate I'm trying to update is highlighted in the screenshot below (taken from certmgr.msc):
Here's the PowerShell code (largely taken from here):
Set-Location cert:
cd .\CurrentUser\Root
$cert = gci .\02FAF3E291435468607857694DF5E45B68851868
$cert.FriendlyName = "UserTrust CA"
(I've verified the thumbprint with the certificate properties in certmgr.msc to make sure it's the same certificate).
The last line will result in the following error:
Exception setting "FriendlyName": "Access is denied.
"
At line:1 char:7
+ $cert. <<<< FriendlyName = "UserTrust CA"
+ CategoryInfo : InvalidOperation: (:) [], RuntimeException
+ FullyQualifiedErrorId : PropertyAssignmentException
I've tried the following things so far:
Running PowerShell as administrator
Changing the execution policy using: Set-ExecutionPolicy Unrestricted
Other information:
PowerShell version is 2.0 (running on Windows 7 Enterprise x64)
I'm running the x64 version of PS
DEP and UAC are disabled
My account is part of the Administrators group
I'm a complete PowerShell n00b ;-)
PS version output:
$PSVersionTable.PSVersion
Major Minor Build Revision
----- ----- ----- --------
2 0 -1 -1
You need to update your version of Powershell to 3.0 or 4.0.
See Get-ChildItem for Certificate
I have Powershell 4.0 and I was able to change the FriendlyName without problems. This was visible in certmgr.msc after a restart.
You can download Powershell 4.0 here.
If you are a Powershell beginner it's probably better to use Get-ChildItem instead of gci for improved readability. Also, cd is an alias of Set-Location so it's better to choose one or the other in your script to avoid confusion.

The specified module was not loaded 'PSWindowsUpdate'

Description: I am running/executing powershell from a ruby script (.rb) file
exec "powershell.exe Import-Module PSWindowsUpdate"
I downloaded the PSWindowsUpdate module from "Windows Update PowerShell Module" and copied the files to the following location:
%WINDIR%\System32\WindowsPowerShell\v1.0\Modules
When I run the above I get the following error:
Z:\Desktop>ruby windows_patch.rb
Import-Module : The specified module 'PSWindowsUpdate' was not loaded because
no valid module file was found in any module directory.At line:1 char:1
+ Import-Module PSWindowsUpdate
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : ResourceUnavailable: (PSWindowsUpdate:String) [I
mport-Module], FileNotFoundException
+ FullyQualifiedErrorId : Modules_ModuleNotFound,Microsoft.PowerShell.Comm
ands.ImportModuleCommand
However, when I run this via Powershell it runs fine and dandy.
I'm using:
Windows 7 x64
PowerShell v4
Ruby v2.1.5
The result of exec "powershell.exe ruby -e 'puts $:'" is:
C:/Ruby21/lib/ruby/site_ruby/2.1.0
C:/Ruby21/lib/ruby/site_ruby/2.1.0/i386-msvcrt
C:/Ruby21/lib/ruby/site_ruby
C:/Ruby21/lib/ruby/vendor_ruby/2.1.0
C:/Ruby21/lib/ruby/vendor_ruby/2.1.0/i386-msvcrt
C:/Ruby21/lib/ruby/vendor_ruby
C:/Ruby21/lib/ruby/2.1.0
C:/Ruby21/lib/ruby/2.1.0/i386-mingw32
I ran powershell.exe $env:PSModulePath which gave me:
\vmware-host\Shared Folders\Documents\WindowsPowerShell\Modules;C:\Program Files (x86)\WindowsPowerShell\Modules;C:\Windows\system32\WindowsPowerShell\v1.0\M
odules\
I then copied the folder to C:\Program Files (x86)\WindowsPowerShell\Modules
I then got:
Import-Module : The specified module 'PSWindowsUpdate' was not loaded because
no valid module file was found in any module directory.At line:1 char:39
Next, I then ran:
PS C:\Users\Justin.Schuhmann> Set-ExecutionPolicy -Scope LocalMachine
cmdlet Set-ExecutionPolicy at command pipeline position 1
Supply values for the following parameters:
ExecutionPolicy: Unrestricted
Execution Policy Change
The execution policy helps protect you from scripts that you do not trust. Changing the execution policy might expose
you to the security risks described in the about_Execution_Policies help topic at
http://go.microsoft.com/fwlink/?LinkID=135170. Do you want to change the execution policy?
[Y] Yes [N] No [S] Suspend [?] Help (default is "Y"):
This solved the issue, I don't have a permanent solution yet as this is only temporary. When setting

Resources