Windows cmd.exe output in PowerShell - powershell

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.

Related

Powershell run exe as different user

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

Powershell - Within Powershell ISE run multiple line script in Powershell

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

Can't copy files using xcopy when running batch file with powershell from remote

I'm trying to run a batch file to copy files from a remote computer (A) to a local Computer (B) - The two computers are in a workgroup and have full access to one another. I'm running the batch file with PowerShell script from the remote computer (A).
The batch file contain this command:
XCOPY \\buildagent01\C$\agent\_work\2\a\Bin\JobServer \\Automation\C$\QA\VLast\Backend\WinServices\JobServer
If I run this XCOPY command from the remote or local computer directly in the command prompt - the files are being copied, If I use powershell to run the batch file (Version.bat) that contains this command - 0 files are being copied...
this is how the PowerShell looks like:
#Predefine necessary information
$Username = "aaaa"
$Password = "*****"
$ComputerName = "Automation"
$Script = {\\Automation\C$\QA\Version.bat $args[0] $args[1] $args[2] $args[3] $args[4]}
$Binaries_Directory_Path = "\\buildagent01\C$\agent\_work\2\a\Bin\JobServer"
$QA_Fold = "\\Automation\C$\QA"
$Exclude = "\\Automation\C$\QA\Exclude.txt"
$Deployed_version_sufix = "1"
$BackupFoldPrefix = "BackupTo"
$Backup_Fold = $BackupFoldPrefix+$Deployed_version_sufix
#Create credential object
$SecurePassWord = ConvertTo-SecureString -AsPlainText $Password -Force
$Cred = New-Object -TypeName "System.Management.Automation.PSCredential" -ArgumentList $Username, $SecurePassWord
#Create session object with this
$Session = New-PSSession -ComputerName $ComputerName -credential $Cred
#Invoke-Command
$Job = Invoke-Command -Session $Session -Scriptblock $Script -ArgumentList $Binaries_Directory_Path,$QA_Fold,$Backup_Fold,$Exclude,$Deployed_version_sufix
echo $Job
#Close Session
Remove-PSSession -Session $Session

How to set an executable to run with administrator rights in powershell

I need a help
I have trouble to set a script in powershell that give DOMAIN adminsitrator rights to an User to an executable . Because I need to install a program in many desktops, plus I need to check if the program is already installed.
This seams to be easy but I know how to program in shell script not much powershell.
$SPAdmin = "DOMAIN\ADMIN"
$Password="FooBoo"|ConvertTo-SecureString -AsPlainText -Force
$Credential = new-object -typename System.Management.Automation.PSCredential -argumentlist $SPAdmin, $Password
Get-WmiObject -Class Win32_Service -ComputerName "Server" -Filter "Name='ServiceName'" -Credential $Credential
$name = "CagService"
if (Get-Service $name -ErrorAction SilentlyContinue)
{
Write-Host "O Servico do Agente conhecido como $name ja esta Instalado na Maquina com Hostname: $env:computername"
sleep 5
}
Else
{
$storageDir = $pwd
$source = "https://source"
$destination = "$storageDir\agent.exe"
Invoke-WebRequest $source -OutFile $destination
$exec = New-Object -com shell.application
$exec.shellexecute($destination);
}
Is there any reason that you can't simply do:
Start-Process powershell -Verb runAs
From a PS console? That launches a new ps window with admin privileges....
PowerShell: Running a command as Administrator

Powershell command fails with "Invalid namespace" only when running as script, not in console

The following script fails on the last line with Get-WmiObject : Invalid namespace:
$password = ConvertTo-SecureString "password" -AsPlainText -Force
$cred= New-Object System.Management.Automation.PSCredential ("domain\user", $password )
Write-Host "Entering PS Session..."
Enter-PSSession -Computer hyperVServer -Credential $cred
Start-Sleep -s 5
$server = "servername"
$query = "SELECT * FROM Msvm_ComputerSystem WHERE ElementName='" + $server + "'"
$VM = get-wmiobject -query $query -namespace "root\virtualization" -computername "."
However, when I enter this one-by-one into the console, it runs without issue.
I've added the Start-Sleep due to some timing issues... the session takes a few seconds to actually open. Any ideas why that line would fail only when this is running as a script?
Enter-PSSession is intended only for interactive use. If you want to run commands on a remote system in a script (non-interactively), you'll need to use Invoke-Command instead. Please run Get-Help Invoke-Command -Full for more details.
Not sure why it works in one and not the other, but I assuming it's something to do with your remote session. Here's a list of commands that do not require a remote session, but rather just take a computer name. http://technet.microsoft.com/en-us/library/dd819505.aspx
$password = ConvertTo-SecureString "password" -AsPlainText -Force
$cred= New-Object System.Management.Automation.PSCredential ("domain\user", $password )
$server = "servername"
$query = "SELECT * FROM Msvm_ComputerSystem WHERE ElementName=$server"
$VM = get-wmiobject -query $query -namespace "root\virtualization" -computername hyperVServer -credential $cred
Edited your query concat too.