Trying to launch a script from a script, as a different user - powershell

I've been banging my head against a wall for far too long on this issue.
I'm attempting to launch a script from a GUI script. The idea is that a user will use their non-admin account, and have the script pass off their admin credentials to a script that does the actual work.
I've tried to use Invoke-Command and Start-Process with little to no success. I can either get the script to launch as admin, or pass parameters, but not both. The idea is that I collect a bunch of information about a user (name, job title, phone number etc) in a GUI form and pass those off to a script that will create a new account for that user.
I've tried the following lines to get this to pass off correctly, but I think I need way more eyes on the problem.
Invoke-Command -Credential { .\create-newuser.ps1 -givenname $Givenname -Surname $Surname } -Computername 'LocalHost'
#Many parameters excluded for simplicity.
And
Start-Process -filename pwsh -argumentlist ".\create-newuser.ps1 -Givenname $Givenname -Surname $Surname" -Credential $Creds
#Many parameters excluded for simplicity
Any help or advice would be greatly appreciated.

Related

Add 365 License with Powershell Script in task Scheduler

I'm trying to license my users in office365 with a powershell script in tassk scheduler.
First : I have a script to create some users in my domain controller. This script add content (userprincipalname) in a txt file. Example :
- Create user : John Smith
- The script add this in the txt file : john.smith#domain.com
Second : Another script try to license this user. This script are connecting to MSOLService with this cmdlets :
$LOGIN = "svc-365#domain.com"
$MDP = Get-Content "C:\Script\SVC-365.txt" | ConvertTo-SecureString
$Cred = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $LOGIN,$MDP
$Session = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri https://outlook.office365.com/powershell-liveid/ -Credential $UserCredential -Authentication Basic -AllowRedirection
Connect-MsolService -Credential $UserCredential
Import-PSSession $Session -AllowClobber
$User = Get-Content "C:\Script\CreationMail.txt"
foreach ($i in $User) {
Set-MsolUser -UserPrincipalName $i -UsageLocation "FR"
Set-MsolUserLicense -UserPrincipalName $i -AddLicenses "tenantudl:STANDARDWOFFPACK_FACULTY"
}
This script is perfectly working when I manually execute in powershell ISE, but not working in the task scheduler...
If somebody can help me, I will be grateful to him ! :)
Thanks for help !
Which user runs the script in your task?
With credentials that you have saved as a hash value in a text file it can only be decrypted by the user that made the file.
So if you made that file with your user, but the user that is setup to run the task is not the same, say a service account, it cannot decrypt the password and the login will fail.
As a note, I would highly recommend Microsofts new feature to assign licenses by group membership instead of doing it by scripts as Microsoft changes things an scripts break.
It is in preview right now and require an AD Basic license on your account or higher, you can activate a free trial of the EMS license pack in Azure and and this will be enough to activate the feature.
For TaskScheduler scripts, you need to set it up correctly.
Set the "Program/Scritp" to Powershell.exe
Set the "Add arguments" to -ExecutionPolicy Bypass C:\Temp\AddLicence.ps1
(Optional) If your script requires any params then you will need to add them and your "Add Arguments" field ends up as -ExecutionPolicy Bypass C:\Temp\AddLicence.ps1 -Users C:\temp\users.csv -LicenceType C:\temp\O365.txt
I find the problem ! :D
In my task, it was domain\administrator who run the task but this account havn't the right to connect to office365 and he havn't the admin right on Exchange-online. I was changed this account with another who have the right on 365 and it's WORK !! :D
Thank's for help guys !

Trouble calling powershell script from within powershell with arguments

I have spent the last 4 hours on this issue and would greatly appreciate any input you might have.
I need to call a powershell script with different credentials and pass arguments onto that script.
Following the installation of a program wrapped in WISEScript this script kicks off to gather AD accounts for the machine and remove them from specific AD Security Groups. Unfortunately as the script runs locally I cannot use ActiveDirectory modules in powershell as not all machines in our environment have RSAT.
The initial script is run from an elevated account on the machine:
$creds = New-Object System.Management.Automation.PsCredential("DOMAIN\USER", (ConvertTo-SecureString "Password" -AsPlainText -Force))
$ProfileGUIDS = Get-ChildItem 'hklm:\SOFTWARE\Microsoft\Windows NT\CurrentVersion\ProfileGuid'
$Groups = [ADSI]"LDAP://CN=Group4d_test,OU=GroupMigrationTesting,OU=TestOU,OU=US,DC=DOMAIN",[ADSI]"LDAP://CN=Group3d_test,OU=GroupMigrationTesting,OU=TestOU,OU=US,DC=DOMAIN"
Function Get-DistinguishedName ($strUserName)
{
$searcher = New-Object System.DirectoryServices.DirectorySearcher([ADSI]'')
$searcher.Filter = "(&(objectClass=User)(samAccountName=$strUserName))"
$result = $searcher.FindOne()
if ($result)
{
Return $result.GetDirectoryEntry().DistinguishedName
}
}
forEach ($GUIDkey in $ProfileGUIDS)
{
$GUID = Out-String -InputObject $GUIDKey
$index = $GUID.IndexOf("S-1")
$GUID = $GUID.Substring($index)
$GUID = $GUID.Substring(0,128)
$index = $GUID.IndexOf(" ")
$GUID = $GUID.Substring(0,$index)
$Profile = "hklm:\SOFTWARE\Microsoft\Windows NT\CurrentVersion\ProfileList\$GUID"
$ProfileItems = Get-ItemProperty $Profile
$SAM = $ProfileItems.ProfileImagePath
$index = $SAM.LastIndexOf("\")
$index ++
$SAM = $SAM.substring($index)
$UserDN = Get-DistinguishedName $SAM
$User = [ADSI]"LDAP://$UserDN"
if($User -ne $null)
{
forEach($group in $groups)
{
Right here is where I need to call the 2nd script with different credentials.
This is RemoveUsers.ps1, the script I need to run with different credentials:
param
(
[string]$group = "MyDefaultSAM",
[string]$user = "MyDefaultUser"
)
$Group.remove($User.ADsPath)
I have tried:
start-process powershell.exe -Credential $creds -NoNewWindow -ArgumentList "Start-Process $PSSCriptRoot\RemoveUsers.ps1 -Verb
This will run the script however I cannot specify any arguments
powershell.exe -file "$PSScriptRoot\RemoveUsers.ps1" -user $user -group $group
This calls the script with arguments but does not allow for the -Credentials switch
I have also tried:
$job = Start-Job -ScriptBlock {
powershell.exe -file "$PSScriptRoot\RemoveUsers.ps1" -user $user -group $group
} -Credential $creds
This runs but does not appear to work properly as the users remain in the AD groups.
Any help is appreciated.
Thanks - Jeff
**** UPDATE ****
Thanks for the information. When I add the changes you suggest I receive an error
Invoke-Command : Parameter set cannot be resolved using the specified named parameters
It appears, as I have found online, the -Credential switch cannot be used without the -Computer switch. If I specify $env:COMPUTERNAME or localhost for the computer I receive the error
\RemoveUsers.ps1 is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was
included, verify that the path is correct and try again
I can avoid this issue if I remove the -Credential switch and open the AD group to everyone. At this point I don't need to elevate a new powershell script and can add the command in the same. If I cannot resolve the issue with Invoke-Command this is likely what I will do.
**** UPDATE ****
What I ultimately had to do was use -Authentication Credssp in the argument list as there is an issue with using the AD Module via Invoke-Command. In addition I had to start the Win-RM service, Enable WSMacCredSSP (-role client on each machine and add a DelegateComputer entry and -role server on the server connecting to). Only after the service was started and an entry was made for WSManCredSSP was I able to use the Invoke-Command switch and have the AD Module work correctly.
This of course makes things more complicated and I decided just installing the AD Module on each PC (after finding a way to do it without RSAT) and forgetting about running the command remotely all together. Thanks for your help with the matter.
Thanks
You don't need to run PowerShell scripts with powershell.exe when calling them from another PowerShell script. Simply use the call operator (&). Also, I'd use Invoke-Command for running something inline with different credentials.
Beware that the scriptblock doesn't automatically know about the variables in the rest of your script. You need to pass them into the scriptblock via the -ArgumentList parameter. That is most likely the reason why removal didn't work when you ran RemoveUsers.ps1 as a job.
Something like this should work:
Invoke-Command -ScriptBlock {
& "$PSScriptRoot\RemoveUsers.ps1" -user $args[0] -group $args[1]
} -ArgumentList $user, $group -Credential $creds -Computer $env:COMPUTERNAME
This requires PSRemoting, though (run Enable-PSRemoting as an administrator).

Run powershell as another user

I can't wrap my head around this at all. I have a powershell script that works fine as long as the user has admin rights, because it is moving data to a NAS share that requires write permissions. My issue is I am putting the script in the GPO Startup process. So I need to run the powershell script as another user.
Do I somehow add the new user credentals inside the script itself, or use another process to runas the other user?
I've tried creating another .ps1 script to start the original script, but it didn't work.
I really want to be able to do this in the original script that's doing all the work.
$username = 'domain\user'
$password = 'password'
$cred = New-Object System.Management.Automation.PSCredential -ArgumentList #($username,(ConvertTo-SecureString -String $password -AsPlainText -Force))
Start-Process -FilePath D:\Scripts\Monitor.ps1 -ComputerName localhost -Credential $cred
and I've tried:
Start-Process -FilePath D:\Scripts\Monitor.ps1 -ComputerName (NAS IP Address) -Credential $cred
This works fine inside a powershell script, so how do I get this to run as another user?
& D:\Scripts\monitor.ps1
We have decided to run this as a task under task scheduler at boot up run by a service account that has all the correct permissions. Not what I really wanted but it does work

Powershell script using another user account

I'm not very good with powershell (to be honest, I'm bad !) but I need to do a script which download pictures and store them in a specific shared folder. I can download the pictures easily, but the folder where I need to store them is protected and there's is only one user (created specifically) who has access on it.
So my question is : how can I configure my script to use this user credentials ? I searched on the net, but I can't understand. As I said, I'm not a powershell user, and I use OS X at home, so I'm not even good with Windows rights and permissions. So a clear and easy answer would be really appreciated !
Thank's !
Use the Invoke-Command command with the -Credential and -ScriptBlock parameters to launch a PowerShell ScriptBlock as a different account. I believe that you will also need to enable PSRemoting in order for Invoke-Command command to work, even on the local system.
$Credential = Get-Credential;
$ScriptBlock = { Copy-Item -Path c:\test\test.txt -Destination c:\test2\test.txt; };
Invoke-Command -Credential $Credential -ScriptBlock $ScriptBlock;
A more complicated solution would be to use the Start-Process cmdlet with the -Credential parameter, to kick off an external executable under an alternate credential. If you just want to kick off PowerShell code though, you're better off using Invoke-Command.
$Credential = Get-Credential;
$Executable = 'c:\path\to\file.exe';
Start-Process -FilePath $Executable -Credential $Credential -Wait -NoNewWindow;

set-aduser takes too long

I have written a script to update a lot of users in Active Directory. It is taking about 10 seconds to run the update, and that seems like too long.
Here is my command:
Set-ADUser $userName -StreetAddress $address1 -Server "MyWickedCoolServerName"
I also tried something like this:
Set-ADUser $userName –Replace #{st=$address1} -Server "MyWickedCoolServerName"
As you can see I have to specify the server each time since we don't have the default one set up, could this be causing the issue? Also, I am running this script remotely on my pc which is not on the domain, so I have to use "runas" to run powershell and have access to AD. Could that be causing the issue?
Any suggestions on what I can look at to see where the performance issue is?
Your command will not work, because your computer is not joined to the Active Directory domain. Since you said that your computer is not domain-joined, you will have to use the -Credential parameter of the Set-ADUser command in order to run it successfully.
$Credential = Get-Credential;
Set-ADUser -Identity $userName -StreetAddress $address1 -Server MyWickedCoolServerName -Credential $Credential;