I have a script that runs in Powershell ISE but there is a part of that script that has to run in regular Powershell. The script that needs to run in Powershell has multiple lines.
When I try running the script like this:
<#
Some code runs up here
#>
$script = {
$PW = "Password1";
$PW = $PW | ConvertTo-SecureString -AsPlainText -Force;
Add-SQLAssessmentTask -ManagementGroup "SOME_ID_NUMBER" -SQLServerName $env:computername -WorkingDirectory C:\Temp\SQL -ScheduledTaskUsername domain\user -ScheduledTaskPassword $PW -Verbose;
}
$command = $script.ToString()
#Start-Process powershell -argumentlist $command
Start-Process powershell -argumentlist $script
I get the follow error:
When I run the script like this:
<#
Some code runs up here
#>
$arguments = "$PW = ""Password1""","$PW = $PW | ConvertTo-SecureString -AsPlainText -Force","Add-SQLAssessmentTask -ManagementGroup ""SOME_ID_NUMBER"" -SQLServerName $env:computername -WorkingDirectory C:\Temp\SQL -ScheduledTaskUsername domain\user -ScheduledTaskPassword $PW -Verbose"
Start-Process powershell -argumentlist $arguments
I get this error:
If I run each line in regular Powershell, one at a time, it works fine.
Any suggestions?
$Arguments is supposed to be a script block separated by semi-colons if you want to run multiple commands.
$arguments = {"$PW = ""Password1""";"$PW = $PW | ConvertTo-SecureString -AsPlainText -Force";"Add-SQLAssessmentTask -ManagementGroup ""SOME_ID_NUMBER"" -SQLServerName $env:computername -WorkingDirectory C:\Temp\SQL -ScheduledTaskUsername domain\user -ScheduledTaskPassword $PW -Verbose" }
Start-Process powershell -argumentlist $arguments
Related
I'm trying to run a process with a hardcoded user and pwd however i seem to only be able to specify either the credential or runas, but never both:
$username = "[redacted]"
$password = "[redacted]"
$credentials = New-Object System.Management.Automation.PSCredential -ArgumentList #($username,(ConvertTo-SecureString -String $password -AsPlainText -Force))
# Self-elevate the script if required
# From: https://blog.expta.com/2017/03/how-to-self-elevate-powershell-script.html
if (-Not ([Security.Principal.WindowsPrincipal] [Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole] 'Administrator')) {
if ([int](Get-CimInstance -Class Win32_OperatingSystem | Select-Object -ExpandProperty BuildNumber) -ge 6000) {
$CommandLine = "-noexit -noprofile -File `"" + $MyInvocation.MyCommand.Path + "`" " + $MyInvocation.UnboundArguments
Start-Process Powershell -Verb Runas -ArgumentList $CommandLine # work, but no credential
# Start-Process PowerShell -Cred $credentials -Verb Runas -ArgumentList $CommandLine # both credential and runas, doesnt work.
Exit
}
}
How can i run Start-Process with both credentials and runas?
I have the following commands in a powershell script (within Jenkins):
$Command = "C:\Program Files\Microsoft SQL Server\150\DAC\bin\SqlPackage.exe"
$Parms = "/Action:Script /sf:DB.dacpac /Profile:publish.xml"
$Prms = $Parms.Split(" ")
& "$Command" $Prms
How can I run the SqlPackage.exe as another user?
PS: It is within Jenkins so I can't run the ps1 file or SqlPackage.exe using runas windows dialog.
EDIT:
I think I am very close, so far I have the following script.
$sb = [scriptblock]::create("& ""SqlPackage.exe"" ""/Action:Script /sf:DB.dacpac /Profile:publish.xml /TargetServerName:localdb /op:Publish.sql""")
$Secure_Password = ConvertTo-SecureString -String $parPassword -AsPlainText -Force
$Credential = New-Object -Type PSCredential($parUserId,$Secure_Password)
$Session = New-PSSession -ComputerName ServerName -Credential $Credential
Invoke-Command -Session $Session -ScriptBlock $sb
I am getting the following error:
*** Argument 'Action' has an invalid value: 'Script
/sf:DB.dacpac /Profile:publish.xml
/TargetServerName:localdb /op:Publish.sql'
instead of creating session, use start-process. I would recommend providing complete path to the dacpac file with SourceFile switch along with the Profile switch
$Command = "C:\Program Files\Microsoft SQL Server\150\DAC\bin\SqlPackage.exe"
$Parms = "/Action:Script /sf:DB.dacpac /Profile:publish.xml"
$Secure_Password = ConvertTo-SecureString -String $parPassword -AsPlainText -Force
$Credential = New-Object -Type PSCredential($parUserId,$Secure_Password)
Start-Process -Credentials $credential -FilePath $command -ArgumentList $Parms
I am starting a process with PowerShell using another user with elevated rights.
$username = "username"
$password = "password"
$startWithElevatedRights = "notepad"
$credentials = New-Object System.Management.Automation.PSCredential -ArgumentList #($username,(ConvertTo-SecureString -String $password -AsPlainText -Force))
Start-Process powershell -Credential $credentials -ArgumentList '-noprofile -command &{Start-Process ‘, $startWithElevatedRights, ‘ -Wait -verb runas}'
I know it's bad style to write user credentials to code, but it is used within full automated procedures, so this is necessary.
My problem is, that I cannot wait until the process (last code line) finished. The inner process waits as expected.
I tried the parameter -Wait, * | Wait-Process, * | Out-Null, with return Value (which is always null)
Nothing works.
Is there any solution waiting until the process has exited?
If there is any solution for PowerShell 2.0 it would be the best for my use case.
You can get Process object from Start-Process using PassThru parameter and then wait for it to exit.
$username = "username"
$password = "password"
$startWithElevatedRights = "notepad"
$credentials = New-Object System.Management.Automation.PSCredential -ArgumentList #($username,(ConvertTo-SecureString -String $password -AsPlainText -Force))
$ps = Start-Process -PassThru -FilePath powershell -Credential $credentials -ArgumentList '-noprofile -command &{Start-Process ', $startWithElevatedRights, ' -Wait -verb runas}'
$ps.WaitForExit()
I am trying to figure out how to run powershell script with elevated credentials, and was told the best way to do this was with Start-Process
And this website, http://social.technet.microsoft.com/Forums/windowsserver/en-US/132e170f-e3e8-4178-9454-e37bfccd39ea/startprocess-verb-runas-credential is also good reference
But I am still having trouble.
I created one script for testing purposes, hello.ps1
write-host Hello World
That runs well by itself
Then, I created another script to invoke Hello World with elevated credentials
<#Previously created password file in C:\Script\cred.txt, read-host -assecurestring | convertfrom-securestring | out-file C:\Script\cred.txt#>
$password = get-content C:\Script\cred.txt | convertto-securestring
$credentials = new-object -typename System.Management.Automation.PSCredential -argumentlist "DOMAIN\Username",$password
$script = "C:\script\hello.ps1"
Start-Process powershell -Credential $credentials -verb runas -ArgumentList "-file $script"
And I get error:
At C:\script\my_script.ps1:6 char:14
+ Start-Process <<<< powershell -Credential $credentials -verb runas -ArgumentList "-file $script"
+ CategoryInfo : InvalidArgument: (:) [Start-Process], ParameterBindingException
+ FullyQualifiedErrorId : AmbiguousParameterSet,Microsoft.PowerShell.Commands.StartProcessCommand
EDIT
#Adi Inbar
I updated the code as follows
$password = get-content C:\Script\cred.txt | convertto-securestring
$credentials = new-object -typename System.Management.Automation.PSCredential -argumentlist "DOMAIN\Username",$password
$script = "C:\Script\hello.ps1"
Start-Process powershell -Credential $credentials -ArgumentList "-file $script"
But now a cmd windows pops up and the output is blank, instead of the expected "Hello World"
EDIT
And I read that you must include -FilePath if you include -Credential, but code is still not working :-(
It just pops-up the cmd window and no output is written in powershell_ise.exe GUI
<#Previously created password file in C:\Script\cred.txt, read-host -assecurestring | convertfrom-securestring | out-file C:\Script\cred.txt#>
$password = get-content C:\Script\cred.txt | convertto-securestring
$credentials = new-object -typename System.Management.Automation.PSCredential -argumentlist "DOMAIN\Username",$password
$script = "C:\Script\hello.ps1"
Start-Process -FilePath C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe -Credential $credentials -ArgumentList "-file $script"
-Verb and -Credential are in different parameter sets. They cannot be used together. -Verb runas doesn't run the specified process as a different user (not to be confused with the runas command), it uses UAC to run the process with elevated privileges in the current user's context, like right-clicking and selecting "Run as administrator".
Just get rid of -Credential $credentials, and run the script while logged in with an account that has local admin privileges.
Well, I was able to answer parts of my question, because I still have a bigger question that I will post separately
'noexit' in -ArgumentList keeps the cmd window persistent, but at least it outputs the value, so at least I know the program is working
<#Previously created password file in C:\Script\cred.txt, read-host -assecurestring | convertfrom-securestring | out-file C:\Script\cred.txt#>
$password = get-content C:\Script\cred.txt | convertto-securestring
$credentials = new-object -typename System.Management.Automation.PSCredential -argumentlist "DOMAIN\Username",$password
$script = "C:\Script\hello.ps1"
start-process powershell -Credential $credentials -ArgumentList '-noexit','-File', 'C:\script\hello.ps1'
I have a script for remotely executing commands on other machines, however... when using windows cmd.exe commands It does not write to the file on the remote server. Here is the code.
$server = 'serverName'
$Username = 'userName'
$Password = 'passWord'
$cmd = "cmd /c ipconfig"
########################
########################
$ph = "C:\mPcO.txt"
$rph = "\\$server\C$\mPcO.txt"
$cmde = "$cmd > $ph"
$pass = ConvertTo-SecureString -AsPlainText $Password -Force
$mycred = new-object -typename System.Management.Automation.PSCredential -argumentlist "$Username",$pass
Invoke-WmiMethod win32_process -name create -ComputerName $server -ArgumentList $cmde Credential $mycred
cmd /c net use \\$server\C$ $password /USER:$username
Get-Content $rph
Remove-Item $rph
cmd /c net use \\$server\C$ /delete
As you can see we simply write
$cmde = "$cmd > $ph"
if I use a PowerShell command I use
$cmde = "$cmd | Out-File $ph"
and it works fine. Any advice Appreciated
Why are you doing it the hard way? You can use WMI to get the IP details of a remote computer.
Get-WMIObject -ComputerName "RemoteServer" Win32_NetworkAdapterConfiguration -Filter "IPEnabled=$true" | Out-File $env:TEMP\ipdetails.txt
Now, once you have that file, you can move it using the commands you had in your script.