I'm deploying a monitoring system, and even though it has a large number of plugins, some need to run as a different user to run right.
So I switched to powershell, but the problem is the same, I have some code that give me access denied, because the user has no elevated privileges.
My question how can I run this code as different user, I tried this
$usuario = "myuser#mydomain"
$pass = get-content C:\credential.txt`
$spass = $pass | Convertto-SecureString`
pass = "securepass"`
spass = $pass | ConvertTo-SecureString -AsPlainText -Force`
write-host $pass
$cred = new-object System.Management.Automation.PSCredential -argumentlist $usuario, $spass
$UpdateSession = New-Object -ComObject Microsoft.Update.Session
$UpdateSearcher = ($UpdateSession.CreateupdateSearcher())
$Updates = $UpdateSearcher.Search("IsAssigned=1 and IsHidden=0 and IsInstalled=0").updates
$total = $Updates | measure
$total.count
Then how can I pass the credentials to the variables. The problem access denied come from this line
$Updates = $UpdateSearcher.Search("IsAssigned=1 and IsHidden=0").updates
$args = ' -file path-to-script.ps1'
Start-Process -FilePath powershell.exe -Credential $creds -ArgumentList $args -Verb RunAs
Powershell also has -Command which you can use to call a function or cmdlet instead of another script.
Related
I have two functions, Save Credential to create a .cred file:
$cred = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList ($Username, $PWord)
$cred.Password | Out-File "some\path\$($cred.Username).cred" -Force
and Get Credential to retrieve the password:
$string = Get-Content "some\path\$($Username).cred" | ConvertTo-SecureString
$cred = New-Object System.Management.Automation.PSCredential -ArgumentList $Username, $string
return $cred
I cannot for the life of me figure out how to retrieve the password from the .cred file that I created. The errors I get are:
ConvertTo-SecureString: Input String was not in the correct format
New-Object: Exception calling .actor with 2 arguments. Cannot process argument because the value of argument "password" is null. change the value of argument password to a non-null value
What version are you bound to? I might not be following properly, but it looks like you don't care about the whole credential and just want the password, so couldn't it just be:
#set
$pwd = "replace me"
$securepwd = $pwd | ConvertTo-SecureString -AsPlainText -Force
$encryptedpwd = $securepwd | ConvertFrom-SecureString
Out-File -FilePath C:\temp\Reference.cred -InputObject $encryptedpwd
then
#get
$securepwd = (Get-Content -Path C:\temp\Reference.cred) | ConvertTo-SecureString
#commented out 3 lines shows how to decrypt in case you want to view it/verify it, but isn't necessary
#$Marshal = [System.Runtime.InteropServices.Marshal]
#$Bstr = $Marshal::SecureStringToBSTR($securepwd)
#$pswd = $Marshal::PtrToStringAuto($Bstr)
#$Marshal::ZeroFreeBSTR($Bstr)
$RunAs = New-Object System.Management.Automation.PSCredential ('Domain\Account', $securepwd)
I'm not as good as most folks on here though, just giving it a stab.
Trying to create a Powershell script that installs an application (.exe) with stored credentials (Clixml).
Everything works fine when using:
Start-Process -FilePath "C:\Users\$($env:USERNAME)\Downloads\Software\Software.exe" -ArgumentList '/s' -Credential $credentials
But I would like a more elegant solution:
$startprocessParams = #{
FilePath = "C:\Users\$($env:USERNAME)\Downloads\Software\Software.exe"
ArgumentList = '/s'
Credential = $credentials
Verb = 'RunAs'
PassThru = $true
Wait = $true
}
$proc = Start-Process #startprocessParams
if ($proc.ExitCode -eq 0) {
'Software installed!'
}
else {
"Fail! Exit code: $($Proc.ExitCode)"
}
This works perfectly without the Credential parameter, you then get the "enter credentials/UAC" popup that I would like to avoid. With the Credential parameter I get this error:
Start-Process : Parameter set cannot be resolved using the specified name parameters.
What am I missing here? Appreciate any advice and/or guidance.
EDIT:
I use the following line to import the credentials:
$credentials = Import-Clixml "C:\Users\$Env:USERNAME\AppData\Local\Apps\SOFTWARE\cred.xml"
The credentials is created with a standard:
Get-Credential | Export-Clixml "C:\Users\$Env:USERNAME\AppData\Local\Apps\SOFTWARE\cred.xml"
This works as it should.
you need to set the credentials as PSCredential.
have a look at this solution:
$username = "username"
$password = "password"
$credentials = New-Object System.Management.Automation.PSCredential -ArgumentList #($username,(ConvertTo-SecureString -String $password -AsPlainText -Force))
Start-Process dnscrypt-proxy.exe -WorkingDirectory path_here -Credential ($credentials)
is it stored in PSCredential in the first place?
Start-Process : Parameter set cannot be resolved using the specified name parameters.
The error tells us the set of parameters used is incorrect. Checking the MSDN doc or Get-Help for Start-Process will show that -Credential can not be used with -Verb.
I'm trying to make a script that changes the HostnameAlias for a given dns record.
But only certain users have access to editing these records, for example ADMIN can edit it but CURRENTUSER cannot.
Currently I have this piece of code:
param(
[ValidateNotNull()]
[System.Management.Automation.PSCredential]
$Credential = $(Get-Credential)
)
$Command = "Set-DnsServerResourceRecord -NewInputObject $($NewObject) -OldInputObject $($OldObject) -ZoneName $($ZoneName)"
Start-Process -FilePath PowerShell -NoNewWindow -Credential $Credential -ArgumentList $Command
But i just keep getting Start-Process : This command cannot be run due to the error: The user name or password is incorrect even though I am absolutely sure they are indeed correct.
What am I doing wrong here.
Ps, I have looked at all the related questions, none seem to answer my question.
You can call System.Management.Automation.PSCredential object to specify any credentials you want and run with it in any process
$User = 'yourdomain\youruser'
$Password = 'yourpassword'
$Secure_Password = ConvertTo-SecureString $Password -AsPlainText -Force
$Credential = New-Object System.Management.Automation.PSCredential($User, $Secure_Password)
$Command = "Set-DnsServerResourceRecord -NewInputObject $($NewObject) -OldInputObject $($OldObject) -ZoneName $($ZoneName)"
Start-Process -FilePath PowerShell -NoNewWindow -Credential $Credential -ArgumentList $Command
You can use this:
#Get User credential
$Credential = Get-Credential Domain\UserNameYouWant
#Use System.Diagnostics to start the process as User
$ProcessInfo = New-Object System.Diagnostics.ProcessStartInfo
#With FileName we're basically telling powershell to run another powershell process
$ProcessInfo.FileName = "powershell.exe"
#CreateNoWindow helps avoiding a second window to appear whilst the process runs
$ProcessInfo.CreateNoWindow = $true
#Note the line below contains the Working Directory where the script will start from
$ProcessInfo.WorkingDirectory = $env:windir
$ProcessInfo.RedirectStandardError = $true
$ProcessInfo.RedirectStandardOutput = $true
$ProcessInfo.UseShellExecute = $false
#The line below is basically the command you want to run and it's passed as text, as an argument
$ProcessInfo.Arguments = "The command you want"
#The next 3 lines are the credential for User as you can see, we can't just pass $Credential
$ProcessInfo.Username = $Credential.GetNetworkCredential().username
$ProcessInfo.Domain = $Credential.GetNetworkCredential().Domain
$ProcessInfo.Password = $Credential.Password
#Finally start the process and wait for it to finish
$Process = New-Object System.Diagnostics.Process
$Process.StartInfo = $ProcessInfo
$Process.Start() | Out-Null
$Process.WaitForExit()
#Grab the output
$GetProcessResult = $Process.StandardOutput.ReadToEnd()
# Print the Job results
$GetProcessResult
Just a mistake on my part, forgot to specify domain before username when entering credentials.
Can solve it like this Get-Credential Domain\
We have a program that only updates when being run with the switch /t from an administrator account.
I came up with the CMD prompt version, but I'm new to powershell and having a hard time translating it to Powershell.
The CMD version is:
C:\Windows\System32\runas.exe /savecred /user:ourdomain\ouruseracct "C:\Program Files (x86)\ProjectMatrix\ProjectNotify\ProjectNotify.exe /t"
So far I got:
C:\Windows\System32\runas.exe /user:ourdomain\ouruseracct /savecred "powershell -c start-process -FilePath \"'C:\Program Files (x86)\ProjectMatrix\ProjectNotify\ProjectNotify.exe'\" -verb runAs"
Which runs powershell as admin and starts the program as admin but we need to pass the argument -t or /t to projectnotify.exe when running it.
I believe we need to make use of the -argumentlist but not sure how to word it.
I tried
$t = "-t"
Start-Process -FilePath "C:\Program Files (x86)\ProjectMatrix\ProjectNotify\projectnotify.exe" -ArgumentList $t -Verb runas
Which runs the program but not sure if that's how you pass the argument.
Extra work (troubleshooting):
$Cred = Get-Credential
$ProcInfo = New-Object -TypeName 'System.Diagnostics.ProcessStartInfo'
$ProcInfo.Domain = $Cred.GetNetworkCredential().Domain
$ProcInfo.UserName = $Cred.UserName
$ProcInfo.Password = $Cred.Password
$ProcInfo.FileName = "${Env:ProgramFiles(x86)}\ProjectMatrix\ProjectNotify\ProjectNotify.exe"
$ProcInfo.Arguments = '/t'
$ProcInfo.WorkingDirectory = "${Env:ProgramFiles(x86)}\ProjectMatrix\ProjectNotify"
$ProcInfo.WindowStyle = [System.Diagnostics.ProcessWindowStyle]::Normal
$ProcInfo.Verb = 'RunAs'
$ProcInfo.UseShellExecute = $true
[System.Diagnostics.Process]::Start($ProcInfo)
After some more thought, here's a simpler way (in a single command even):
Start-Job -Credential (Get-Credential) -ScriptBlock {
$Dir = "${Env:ProgramFiles(x86)}\ProjectMatrix\ProjectNotify"
$StartArgs = #{
'FilePath' = "$Dir\ProjectNotify.exe"
'ArgumentList' = '/t'
'Verb' = 'RunAs'
'WindowStyle' = 'Normal'
'WorkingDirectory' = $Dir
'PassThru' = $true
}
Start-Process #StartArgs
} | Wait-Job | Receive-Job
My previous answer is at the bottom of this post now.
References:
about_Splatting
Get-Credential
Start-Process
Start-Job
Extra reading:
Import-CliXml
Export-CliXml
Assuming an on-demand script, you should create a pscredential object if you want to natively run this from powershell:
Launch.cmd
SET "PS=%WINDIR%\System32\WindowsPowerShell\v1.0\powershell.exe"
SET "SCRIPT=%SYSTEMDRIVE%\Path\to\wrapper.ps1"
%PS% -NoProfile -NoLogo -ExecutionPolicy Bypass -File "%SCRIPT%"
wrapper.ps1
$Cred = Get-Credential
# To avoid prompting every time:
#
# if (-not (Test-Path -Path '.\mycred.xml')) {
# Get-Credential | Export-CliXml -Path '.\mycred.xml'
# }
# $Cred = Import-CliXml -Path '.\mycred.xml'
$StartArgs = #{
'FilePath' = "$PSHOME\powershell.exe"
'ArgumentList' = '-NoProfile', '-NoLogo', '-File', '.\runas.ps1'
'Credential' = $Cred
}
Start-Process #StartArgs
runas.ps1
$StartArgs = #{
'FilePath' = "${Env:ProgramFiles(x86)}\ProjectMatrix\ProjectNotify\ProjectNotify.exe"
'ArgumentList' = '/t'
'Verb' = 'RunAs'
}
Start-Process #StartArgs
I know the question asks for arguements, but if you don't them, this works:
Start cmd.exe -Verb RunAs
You can also run this using the 'Run' window or search box:
powershell -command start cmd.exe -verb runas
I have two server as X and Y. I have a powershell script that I am using for having a remote desktop of X on Y. The powershell script that I have to run on Y is --
$hostname = 'X'
$User = 'u-name'
$Password = 'password'
$ProcessInfo = New-Object System.Diagnostics.ProcessStartInfo
$Process = New-Object System.Diagnostics.Process
$ProcessInfo.FileName = "$($env:SystemRoot)\system32\cmdkey.exe"
$ProcessInfo.Arguments = "/generic:TERMSRV/$hostname /user:$User /pass:$Password"
$Process.StartInfo = $ProcessInfo
$Process.Start()
$ProcessInfo.FileName = "$($env:SystemRoot)\system32\mstsc.exe"
$ProcessInfo.Arguments = "$MstscArguments /v $hostname"
$Process.StartInfo = $ProcessInfo
$Process.Start()
When I run this script locally on Y, it does run and opens the server X in Y.
But I want to trigger it from X only to open X in Y. So I Invoke this powershell script from X as --
$pass = ConvertTo-SecureString -AsPlainText test-password -Force
$cred = New-Object System.Management.Automation.PSCredential -ArgumentList test-uname,$pass
$hostn = hostname
$Use = 'u-name'
$Pass = 'password'
Write-Host "$hostname"
$ScriptBlockContent={
Param ($hostname,$User,$Password)
E:\Script\test.ps1 $hostname $User $Password}
Invoke-Command -ComputerName Y -Credential $cred -Scriptblock $ScriptBlockContent -ArgumentList $hostn,$Use,$Pass
When I am invoking this. It does open mstsc.exe on Y but only for some fraction of seconds and doesn't open the server X on Y. Can somebody please help.. !!
Thanks.
You are trying to launch an application with a GUI in a remote powershell session which has no desktop/display. Even if you use the credentials of a logged in user, the things you launch through Invoke-Command will not be visible to the logged-in user's session.
I think that this is possible with PsExec.exe, but I can't confirm.