PowerShell Start-Process with user in local Administrator does not start elevated PowerShell cmd - powershell-2.0

I have created a password file for the account with Administration privileges with the following script:
$passwd = Read-Host "Enter password" -AsSecureString
$encpwd = ConvertFrom-SecureString $passwd
$encpwd > "C:\Users\b_steya\Documents\password_b_steya.bin"
Then, in another powershell script I try to run an elevated PowerShell cmd
$encpwd = Get-Content "C:\Users\b_steya\Documents\password_b_steya.bin"
$passwd = ConvertTo-SecureString $encpwd
$cred = new-object System.Management.Automation.PSCredential 'main\b_steya',$passwd
Start-Process PowerShell -Cred $cred -ArgumentList '-noexit','-File','C:\Users\b_steya\Documents\TestAddIISAppPool.ps1'
When executing the second script, I get the following error message:
Import-Module : Process should have elevated status to access IIS
configuration data.
What am I doing wrong? The user "main\b_steya" is added to the local Administrators group of the machine, on wich the script is executed.
Best regards
Yannik

When your second script is executed is it done so from an administrator (runas administrator) powershell session? Even though the user is part of the local admin group you still often need to have the initial process elevated.

Related

Gitlab-Runner Windows service: build with administrative priviledges

Problem
gitlab-runner in Powershell on build server finishes successfully (vb6.exe, devenv.com, msbuild.exe) if running in local terminal started with "run as administrator", whereas ending up in errors while running as Windows service configured as local administrator
Desired Behavior
building projects (vb6.exe, devenv.com, msbuild.exe) with administrative privileges via gitlab-runner as Windows service on isolated build server
Configuration
Windows Server 2019, Gitlab-Runner v.14.3.2 64bit, powershell mode, service running with local administrator account
Visual Studio (VS) builds need adminstrator privileges for interopability between VB6 UI (VS VB98) and VB6/C# (VS 2019) projects. During building VS writes in Windows Registry if interopt-mode in sub-project of VS solution has been selected (administrator permissions therefore mandatory).
Try outs
installed gitlab-runner as service recommended by https://docs.gitlab.com/runner/install/windows.html
temporary deactivated User Account Control with no success
adapted gitlab-ci.yml to call vb6.exe, devenv.com and msbuild.exe with Powershell command Start-Process -Verb runAs -Wait devenv.com ..., but ended up in errors for devenv.com because Start-Process seems to accept only applications with *.exe as file ending. devenv.exe is working but not returning/closing new terminal session by Start-Process which ends up in a hanging gitlab-ci-build-script. Additionally, terminal messages of the build script are not visible anymore because they are running in a new terminal session created by Start-Process.
Deactivating gitlab-runner service and starting via Windows auto-start-folder: running Powershell-Script: Start-Process -FilePath D:\development\gitlab-runner\gitlab-runner -ArgumentList 'run --working-directory D:\development\gitlab-runner --config D:\development\gitlab-runner\config.toml --service gitlab-runner --syslog' -Verb runAs -Wait, but configured user needs to login on every system start which is not the desired behavior of the build server.
gitlab-runner.exe/vb6.exe/devenv.exe/msbuild.exe - right click - properties - compatibility - change settings for all users - checkbox: run as administrator for all user activated - did not change the described behavior
gitlab-ci.yml
stages:
- deploy
variables:
PLATFORM: 'x86'
CONFIGURATION: 'Release'
myproject:
stage: deploy
when: manual
tags: [deploying]
script:
- Start-Process MSBuild.exe -Wait -Verb runAs -Argument 'AutomatedSetupBuild.proj'
- Start-Process devenv.com -Wait -Verb runAs -ArgumentList ".\mysolution.sln /Rebuild `"$CONFIGURATION|$PLATFORM`" /Project .\myproject\myproject.vbproj /ProjectConfig `"$CONFIGURATION|$PLATFORM`" /Log"
- Start-Process vb6.exe -Wait -Verb runAs -ArgumentList "/make `".\vbproject.vbp`" /out `"$env:TEMP/vb6-buildoutput.log`""
What works for me is to give the user I intend to install the runner as right to log on as a service. Go to Control Panel -> Administrative Tools -> Local Security Policy -> Security Settings -> Local Policies -> User Rights Assignment -> Log on as a service . You need to add the user you installed gitlab-runner to the list, including the local domain, and then install the runner according to https://docs.gitlab.com/runner/install/windows.html, also using the full username with domain.

ASP.NET PowerShell scripts don't run

I write the script directly.(Import-Module ActiveDirectory). It does not work.
Error Message:
(Failed to generate proxies for remote module 'ActiveDirectory'. Files cannot be loaded because running scripts is disabled on this system. Provide a valid certificate with which to sign the files).
Please, tell me the solution.
Also I've tried to execute the command Set-ExecutionPolicy Unrestricted in both cmd 32 and cmd 64.
var shell = PowerShell.Create();
shell.Commands.AddScript("New-Item -Path 'C:\\Distrib\\file.txt' -ItemType 'File'");
This script works:
(PowerShell powerShellInstance = PowerShell.Create())
{powerShellInstance.AddCommand(AppDomain.CurrentDomain.BaseDirectory + \\Powershell\\test.ps1");
test.ps1 does not work:
(New-Item -Path 'C:\\Distrib\\file.txt' -ItemType 'File')
This is not a PowerShell code issue. It is an environment setting.
If you are doing this in an enterprise, then your org has set the policy in your machine for a reason.
Though what JPBlanc would work, unless you have the ability to change this setting by your org admins at the machine level, then you can't change it anyway. You can change it for your user or process level. There are several levels to set for EP and this is well documented.
Set-ExecutionPolicy
Set-ExecutionPolicy
[-ExecutionPolicy] <ExecutionPolicy>
[[-Scope] <ExecutionPolicyScope>]
[-Force]
[-WhatIf]
[-Confirm]
[<CommonParameters>]
Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope LocalMachine
Get-ExecutionPolicy -List
Scope ExecutionPolicy
----- ---------------
MachinePolicy Undefined
UserPolicy Undefined
Process Undefined
CurrentUser RemoteSigned
LocalMachine RemoteSigned
There is little to no reason to ever use unrestricted for day to day PowerShell use case, especially at the machine level. I always recommend CurrentUser or Process.
So, create a new Powershell shortcut to startup using the CurrentUser or Proces scope using the RemoteSigned (which is the current default in Windows 10 even at the machine level).
Even when calling this thru code, use the CurrentUser or Process scope and RemoteSigned.

Unable to start process from powershell

Folks
I am trying to invoke a batch script from a power shell file and the invocation works fine if executed manually.
Start-Process C:\USR\test.bat
However i created a service in C# which is able to delete and write logs using the powershell script however it simply ignores this step and nothing happens. Is it because this script is invoked by a windows service ?
if (Test-Path \\xxxsharepathfullper\FileWatcher\target\watcher.mon) {
echo "File removed" >> C:\USR\logger.txt
Start-Process C:\USR\test.bat
Remove-Item \\xxxsharepathfullper\FileWatcher\target\watcher.mon
}
else {
}
Execution policy is unrestricted
Check access rights on a share, maybe your admin user don't have rights to access it.
You can try run the process as administrator and log any error:
Start-Process -FilePath "C:\USR\test.bat" -RedirectStandardError "testError.txt" -verb RunAs

Creating a shortcut of the running script and making link executable in PowerShell console

Then saving the link in C:\Users\Public\Desktop for easy access.
How do I go about doing this?
Basically the original PowerShell script will have to create a shortcut link to itself and save it in Public\Desktop folder and has to be executable in PowerShell once clicked (not open in notepad)
Any help is greatly appreciated.
you will have to run it in an elevated console :
"greetings from PS !"
$mypath=$MyInvocation.myCommand.definition
$app="%windir%\system32\WindowsPowerShell\v1.0\powershell.exe"
$WshShell = New-Object -ComObject WScript.Shell
$Shortcut = $WshShell.CreateShortcut("C:\Users\Public\Desktop\autogenerated.lnk")
$Shortcut.TargetPath = $app
$Shortcut.Arguments ="-noexit -file $mypath"
$Shortcut.Description ="autogenerated shortcut from ps"
$Shortcut.Save()

Can we register PSSessionConfiguration on remote machine?

Is it possible to register a PS session configuration for machine A from machine B.
Cmdlet "Register-PSSessionConfiguration" works locally only??
First you need to enable PowerShell Remoting on the PC You Want to Access Remotely
In the PowerShell window, type the following command, and then hit Enter:
Enable-PSRemoting -SkipNetworkProfileCheck -Force
Set-Item WSMan:\localhost\Client\TrustedHosts *
Restart-Service WinRM
Test-WsMan $env:computername
If you’re on a home network where you want to go ahead and trust any PC to connect remotely, you can type the following cmdlet in PowerShell (again, you’ll need to run it as Administrator).
Set-Item wsman:\localhost\client\trustedhosts *
Or
Set-Item wsman:\localhost\client\trustedhosts 10.0.0.22
Or
Set-Item wsman:\localhost\client\trustedhosts '10.0.0.22,10.0.0.23'
Register a PSSessionConfiguration
To connect 'Computer1' let us register a session configuration on the server using a domain account.
Just type the following cmdlet and then hit Enter:
Invoke-Command -ComputerName Computer1 -ScriptBlock {Register-PSSessionConfiguration -Name SessionName -RunAsCredential 'domain\mydomainaccount' -Force }
Now I'll use this session configuration the next time I want to run a command on the remote computer.
Invoke-Command -ComputerName 'Computer1' -ScriptBlock { Get-ChildItem-Path \\Computer1\c$ } -ConfigurationName SessionName

Resources