run a command in a powershell script as another user - powershell

Im a low level IT technician working on a swiss knives like powershell script.
So far, I was able to make it work using only user privileges.
But I want to add a function that when you feed it with an address mac, it tells you if there is already an IP reservation on a given scope of the DHCP.
The command works just fine :
Get-DhcpServerv4Lease -ComputerName xxx.xxx.xxx.xxx -ScopeId xxx.xxx.xxx.xxx | findstr "#mac"
The issue im facing is that I want to run the script with user privilege, and the command above needs admin privilege.
So I wrote the command using a Start-Job -credential to feed him admin credential but nothing happens in the foreground.
Start-Job -Credential $Credentials -ScriptBlock ${function:dhcp}
function dhcp
{
$result = Get-DhcpServerv4Lease -ComputerName xxx.xxx.xxx.xxx -ScopeId xxx.xxx.xxx.xxx | findstr "#mac"
$result | Out-File -FilePath C:\temp\result.txt
}
I thought it was due to user environment/PS session given the fact that I run the script as newbieGuy and the command above as admin_newbieGuy so I tried to use Out-file cmdlet so I can get the result of the request on a directory every user have access to.
But the .txt is not even created.
I also tried using Invoke-command but I have the WinRM error and I can't modify the way this is setup in my organization.
Im running out of options guys, If you can give me a hint that would be great.

Related

Powershell, RunAs vs Credential

So I have not found anything that explains why this code will run when you open PowerShell as "Administrator", entering your domain admin credential. Whereas when you open PowerShell with no admin privilege and using the -credential Domain\DomainAdminUser, then entering your password when prompted and I get error. Why is this?
Error: Get-WinEvent: The parameter is incorrect.
I'm asking because I have a menu script which I can run it as admin using my domain admin credential but the gpresult command will not work because of "invalid pointer" and reason being is, my domain account is not part of the authenticated user.
So to make it easy, I need to run my menu script without admin rights and use the -credential switch for certain commands within the menu script.
cls
$logname = "Security"
$Id = "4634"
$Id2 = "4624"
Get-WinEvent -ComputerName $env:COMPUTERNAME -Credential Domain\DomainAdminuser #{logname=$logname;Id=$Id,$Id2;starttime=[datetime]::Today} |
Select-Object TimeCreated, Id, #{n="Message";e={($_.message).Split(" ")[0..4] -join " "}} | Format-Table -Wrap

Run a powershell script from one computer to the next

I already have code written to connect to another computer in my house and pull music files from the C drive. However, I am trying to find out how to keep this code, but modify it in a way that I can use it to run code on the second computer, then save it to a text file.
foreach ($server in Get-Content .\serverList.txt){
psexec \\$server -u username-p password cmd /c dir c:\*.mp3 /s > c:\Powershell\$server.txt
}
You could write a book on PowerShell Remoting (several people have) but it's reasonably straightforward.
On both computers run Enable-PSRemoting to configure all the settings. Then on the originating computer (the one making the remote call) run Set-Item WSMan:\localhost\Client\TrustedHosts -Value '*' (if you are security conscious replace the * with the IP of the remote PC).
Then you can run the all-powerful Invoke-Command to do all sorts of awesome stuff remotely. Unless you're on a domain or there's an identical user on the remote PC you'll need to provide credentials which means either prompting for them or saving them, but if I go into too much detail we'll both be here all day. Pretty easy to find the answers on Google.
$cred = Get-Credential
foreach ($server in Get-Content .\serverList.txt) {
Invoke-Command $server -Credential $cred -ScriptBlock { Get-ChildItem C:\*.mp3 -Recurse } | Out-File C:\Powershell\$server.txt
}

Powershell command to export IIS websites and app pools of a remote server

I have the command which exports websites of the current logged in server (as below). I need the command to export websites of a different server.
%windir%\system32\inetsrv\appcmd list site /config /xml > c:\websites.xml
try with Invoke-Command
Note the syntax you have is for a dos command. The following should get you on track. Of course there is credentials you may have to pass in.
Remoting must be enabled on the remote servers Run Enable-PSRemoting -Force on each server.
Invoke-Command -Computer remoteserver -ScriptBlock {
& $Env:Windir\system32\inetsrv\appcmd.exe list site /config /xml
} | Out-File c:\websites.xml -Append
Note that the 'powershell' way of getting sites as powershell objects is shown here: https://stackoverflow.com/a/25091831/1165140

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.

How to write a powershell script to initiate user profile creation on server 2008

I'm trying to automate application installation on new server instances, but I'm running into an issue when the user I'm impersonating hasn't logged onto the system before.
It seems there are some necessary files or registry entries created during profile creation at first logon that the application needs to access when installing.
My question is primarily how I can use powershell to automate the initition of a domain account profile on a Server 2008 instance?
My initial extremely hacky thought was to initiate an rdp session from a connection file using mstsc.exe, wait for the initial setup to complete, then log the user off, but I'm thinking there has to be a cleaner way.
Also, these processes must all be run locally from the machine using a local user account that has admin rights.
You could try running psexec from within PowerShell to create the user profile on the remote system before you start the install process.
psexec.exe \\Server.domain.com cmd
exit
I know this is an old thread but it was one of the results when I was looking for a way to create a user profile on several remote machines on a domain. Here's how I finally did it, though it is likely not the most efficient method:
Import-Module ActiveDirectory
$scriptblock = {}
$Cred = Get-Credential $env:userdomain\$env:username
$comps = Get-ADComputer -Filter "Name -like 'WS*'" | Select Name -expandproperty Name
foreach ($comp in $comps)
{
Invoke-Command -ComputerName $Comp -Scriptblock ${Scriptblock} -Credential $Cred -Authentication CredSSP
}