Powershell 5.0 Invoke-Command Start Service with Credential - powershell

We have a problem with a Service on a Server. So we decided to write a PS-Script that a "normal" User without Admin privileges can start this Service. I have practiced now 2 Day's on this little Script. I'm a newbie (Apprentice) in PS but im glad that it works when I run it as an Admin. But why the heck not as an User?
I have generated the "Secure" Password as follow:
"P#ssword1" | ConvertTo-SecureString -AsPlainText -Force | ConvertFrom-SecureString | Out-File "C:\Temp\Password.txt"
I took the SecureString and pasted it in my Script that looks like this:
$User = "DOMAIN\USER"
$PwHash = "01000000d08c9ddf0....."
$MyCredential=New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $User, ($PWHash | ConvertTo-SecureString)
Invoke-Command -ComputerName "MyServer" -ScriptBlock {Get-Service -Name "MyService" | Set-Service -Status Running} -Credential ($MyCredential)
The failure pops up by the $MyCredential row:
ConvertTo-SecureString: Key in specific Status is not valid.
I have nowhere read that for an ConvertTo... cmd are Admin rights needed.
Enable-PSRemoting is active on the specific Server.
Thanks for your time and engagement
Dirty.Stone

IMHO, you're going about this all wrong. This is an example of the kind of task you would use JEA (Just Enough Admin) for. Create a constrained, delegated session on the target server, configured with a function for starting or restarting that service and running under a local account that has permission to control the service, and then grant the non-admin users permission to use that session.

Related

Pick an account after Connect-MicrosoftTeams

I'd like to write a PowerShell script which will update Teams members from input list/object. However if I run Connect-MicrosoftTeams command (to authenticate/connect to cloud service) for the first time I am asked to pick an account to use for login. This is an issue since I would like this script to be run as scheduled job. Is there a way how to avoid this when running Connect-MicrosoftTeams command ? Commands I am using:
$credential = Get-Credential
Connect-MicrosoftTeams -Credential $credential
I tried to use "-AccountId "email#address.com" but that didn't help. Of course later I will change Get-Credential to username and encrypted password
EDIT
If I run Connect-MicrosoftTeams -Credential $credential on other computer, where I've never been logged in with my account, instead of "Pick an account" window, I get credential window for username and password:
As commented, this is certainly a dissapointment, but Single-Sign-On cannot be enabled in Microsoft Teams.
See the discussion here
This should achieve what you're trying to do.
Credits to: https://www.jaapbrasser.com/quickly-and-securely-storing-your-credentials-powershell/
Save Credentials
$Credential = Get-Credential
$Credential | Export-CliXml -Path "<File path/name to save credentials"
Connect using saved credentials through MS Teams PowerShell
$Credential = Import-CliXml -Path "<path of exported credential>"
Connect-MicrosoftTeams -AccountId "<email>" -Credential $Credential
For that I always use this from Jaap Brasser:
https://www.jaapbrasser.com/quickly-and-securely-storing-your-credentials-powershell/
At the end I used other module 'AzureAD' and command 'Add-AzureADGroupMember':
# 'password' | ConvertTo-SecureString -AsPlainText -Force | ConvertFrom-SecureString $Password = "01000000d08c9..." | ConvertTo-SecureString
$Credentials = (New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList "user#domain.com", $Password)
Connect-AzureAD -Credential $Credentials
$AZ_USER=Get-AzureADUser -Filter "UserPrincipalName eq 'user#domain.com'"
$AZ_GROUP=Get-AzureADGroup -Filter "DisplayName eq 'teams_name'"
Add-AzureADGroupMember -ObjectId $AZ_GROUP.ObjectId -RefObjectId $AZ_USER.ObjectId
then I have to wait couple hours until Active Directory and Teams got synchronized and users were added to AD groups / Teams teams. It's not ideal, but it works with saved credentials and with no user interaction.

Permissions required to use Move-VM remotely in Hyper-v 2016

I am attempting to run the PowerShell command "move-vm" remotely but I am getting permissions errors that I can't seem to get past.
My move-vm command looks like this:
move-vm -ComputerName SorceHost -Name $vm.name -DestinationHost $DestHost -IncludeStorage -DestinationStoragePath d:\vms -DestinationCredential $cred -Credential $cred
and I am defining the credentials like this
$username = ".\PSAPIUser"
$password = Get-Content 'C:\key\PSAPIAUTH.txt' | ConvertTo-SecureString
$cred = new-object -typename System.Management.Automation.PSCredential `
-argumentlist $username, $password
Both the source and destination are on the same AD domain, and I have created a domain admin account specifically for this function. I have added the domain admins group to the local groups 'Hyper-V administrators' 'administrators' on the source and destination hosts. When I issue the command I get:
move-vm : You do not have the required permission to complete this task. Contact the administrator of the authorization policy for the computer 'SourceHost'.
There are various articles out there about how to do this in 2012, however, its my understanding that the process has changed significantly in 2016 due to the depreciation of something called authorisation manager.
Does anyone have any experience on how to configure permissions to allow remote Hyper-V management with PowerShell specifically in 2016?
Thanks in advance.
Edit:
$cred = Get-Credential
$cred
UserName Password
-------- --------
PSAPIuser#domain.net System.Security.SecureString
move-vm : You do not have the required permission to complete this task. Contact the administrator of the authorization policy for the computer
Managing Hyper-V remotely uses something called Constrained Delegation. Imagine the scenario.
You are on the host Man1, and you are issuing a command to Hyp-001 to move a VM to Hyp-002. So you have Man1 issuing commands to Hyp-001, which is fine as it can use your credentials, but when Hyp-001 passes commands to Hyp-002 it has no credentials to pass, hence you get the error
move-vm : Virtual machine migration operation failed at migration source.
Failed to establish a connection with host 'ng2-vps-011.hyperslice.net': No credentials are available in the security package
to get around this you need to give specific permissions that allows hosts to run specific services on each other, within AD delegation.
From PowerShell it would look like this:
Set-ADObject -Identity $HostDeetsArra.Disname -ADD #{"msDS-AllowedToDelegateTo"="$service1/$Disname","$Service1/$HostName"}
#$disnam = distignushed name, $Service1 is the service 'cifs' $hostanme is the FQDN
In 2016 you also need this:
Set-ADAccountControl -Identity $HostDeetsArra.Disname -TrustedToAuthForDelegation $true
My source for this information is below
https://www.altaro.com/hyper-v/free-powershell-script-configure-constrained-delegation-hyper-v/

Why can I pass credentials to a regular user but not a local administrator?

So basically I've been working forever on a PS remote self help script that originally was thought to be simple: Restart the spooler service, clear the queue, and print a test page on the default printer. Getting there however hasn't been so easy, due to security issues. After some hours, I was able to get my local user test account to accept the credentials of my domain administrator. I thought all was well, until I tried to replicate it on a local administrator's account, in which event access was denied. This is sort of important, because the majority of the accounts we will be deploying the script on are local admins. I suspect it may be a UAC issue, but I have no idea what I should do to work around the problem. Here's what I'm working with currently:
$v = [bool](([System.Security.Principal.WindowsIdentity]::GetCurrent()).groups -match "S-1-5-32-544")
If ($v = "False")
{
$password = "ElPassword" | ConvertTo-SecureString -asPlainText -Force
$username = "Domainname\Username"
$credential = New-Object System.Management.Automation.PSCredential($username,$password)
invoke-command {Stop-Service spooler} -comp $env:ComputerName -cred $credential
Remove-Item C:\Windows\System32\spool\PRINTERS\* -Force
invoke-command {Start-Service spooler} -comp $env:ComputerName -cred $credential
$printer = Get-WmiObject -Query " SELECT * FROM Win32_Printer WHERE Default=$true"
$PrintTestPage = $printer.PrintTestPage() } Else
{ Stop-Service spooler
$printer = Get-WmiObject -Query " SELECT * FROM Win32_Printer WHERE Default=$true"
Start-Service spooler
$PrintTestPage = $printer.PrintTestPage() }
The first thing this does is check if the current PS session is being run as admin; seeing as the users don't actually see the PowerShell window or script, and we recently started using the RMM tool, I'm still trying to figure out under what conditions the tool runs PS elevated - the documentation says that it runs with the credentials of the logged in user, but that doesn't seem to be the case, as an hour with their support team told me that the reason the script wasn't doing it's job on any admin accounts was because it wasn't being elevated. Anyways, after the check, it either passes credentials for the commands or it doesn't. This script seems to handle every scenario but that of a local admin account running PS non elevated. In that event, it simply denies me access where the exact same creds give me access on a regular user account. I'm not sure how to even approach this problem, so any help is appreciated.

win32_process create fails with Unknown failure for service account user

I have a windows service account user, using which i'm trying to create a background process using the WMI win32_proces. But fails with Unknown Failure.
(Tried this with administrator, nonadmin, domain admin, domain nonadmin users. works fine)
$process = [WMICLASS]"\\$computername\ROOT\CIMV2:win32_process"
$processinfo = $process.Create("powershell.exe -WindowStyle Hidden test.ps1")
Write-Host $processinfo.returncode
As explained in this msdn blog post: Win32_Process.Create fails if user profile is not loaded, the WMI call is hardcoded to access the users profile through the registry.
If the user profile is not already loaded in HKU, WMI tries to load it into the registry using RegLoadKey.
This fails unless the user account in question have the following privileges on the local machine:
SeRestorePrivilege
SeBackupPrivilege
So, either
Grant these privileges to the account in question
Call LoadUserProfile for the user in question prior to calling Win32_Process.Create
Or use Start-Process instead of WMI!
# Set up service account credentials
$Username = "domain\svcaccount"
$Password = "7oPs3çürEûN1c0deZ"
$Credential = New-Object pscredential -ArgumentList $Username,$(ConvertTo-SecureString $Password -AsPlainText -Force)
# Establish a session on the remote machine
$RemoteSession = New-PSSession -ComputerName $computername -Credential $Credential
# Launch the process with Start-Process -LoadUserProfile
Invoke-Command -Session $RemoteSession {
Start-Process 'powershell.exe' -LoadUserProfile:$true -Argumentlist 'test.ps1' -WindowStyle Hidden
}
# Cleanup
Remove-PSSession -Session $RemoteSession
Remove-Variable -Name Username,Password,Credential
To Mathias suggestions in below comments:
Start-Process works in background only when invoked through interactive prompt. If run from a .ps1 script, the process created through start-process exits if the .ps1 script exits.
Inside your script. You can create a New-PSsession and then pass this session to invoke-command to trigger start-process.
But again to use New-PSsession and ExitPSSession, you must have Enable-PSRemoting and other setting enabled if you are lacking permissions. http://blogs.msdn.com/b/powershell/archive/2009/11/23/you-don-t-have-to-be-an-administrator-to-run-remote-powershell-commands.aspx

Add-AzureAccount -credential not working as I'd hoped

4 days ago (on 4th August 2014) there was a new release of Azure Powershell that included a new -Credential parameter on the Add-AzureAccount cmdlet. I'm trying to use it but I'm clearly doing something wrong.
First I store my password in a file:
read-host -assecurestring | convertfrom-securestring | out-file C:\temp\securestring.txt
Then try and use it in Add-AzureAccount
$password = cat C:\temp\securestring.txt | convertto-securestring
$username = "dhdom1\jamiet" #yes, this is the correct username
$mycred = new-object -typename System.Management.Automation.PSCredential -argumentlist $username,$password
Add-AzureAccount -credential $mycred
The call to Add-AzureAccount fails:
Add-AzureAccount : user_realm_discovery_failed: User realm discovery
failed: The remote server returned an error: (404) Not Found.
I know that "dhdom1\jamiet" is the correct account. Anyone any idea why this might be failing? TIA
You should use the organizational account you use to log in to the Azure Portal with. So, it might look like jamiet#yourorganizationalaccountname.com, or something like that.
open azure powershell window
type Add-AzureAccount then enter
a login screen will be popuped to him then enter this credential outlook
by this, this credentials are stored in this PowerShell window, then run all other scripts from this specific window.