How to send selection to external Terminal in vscode? - visual-studio-code

I would like to be able to select text in a file and have it sent to an external terminal. Is this possible?
If not, could it be done via applescript?

I ended up writing my own extension to do this using AppleScript. It was as simple as this:
function activate(context) {
const runIterm = vscode.commands.registerCommand('run-external.iterm', function() {
const editor = vscode.window.activeTextEditor;
let textToPaste;
if (editor.selection.isEmpty) {
textToPaste = editor.document.lineAt(editor.selection.active.line).text;
} else {
textToPaste = editor.document.getText(editor.selection);
}
exec(
`osascript ` +
` -e 'tell app "iTerm"' ` +
` -e 'set mysession to current session of current window' ` +
` -e 'tell mysession to write text "${textToPaste}"' ` +
` -e 'end tell'`
);
});
context.subscriptions.push(runIterm);
}
exports.activate = activate;

Related

Jenkins wont pass the arguments to powershell script as expected

I have below jenkins pipeline script which calls another powershell script with some arguments:
Jenkins script:
def map = setupMap()
def setupMap() {
def map = [:]
if (env.JOB_NAME.startsWith("jen-dev")) {
map['jenkinsCredentialsKey'] = 'dev-jenkins'
map['region'] = 'us-west-1'
map['jenkinsRole'] = 'svc.jenkins'
map['sbAWSAccountID'] = 'accountID'
map['sbBucketname'] = 'sa-codedeploy'
map['AWSAccountID'] = 'id2'
map['CredentialsKey'] = 'gc-dev'
} else {
// noop
}
return map
}
pipeline {
agent {
docker {
image IMAGE_AWSCLI_PS
args '-v /etc/pki:/etc/pki:ro'
}
}
options {
buildDiscarder logRotator(numToKeepStr: '200')
skipDefaultCheckout()
durabilityHint 'PERFORMANCE_OPTIMIZED'
disableResume()
timestamps()
}
stages {
stage('test comment') {
steps {
script {
params = [:]
params['credentials'] = map['jenkinsCredentialsKey']
params['region'] = map['region']
params['role'] = map['jenkinsRole']
params['roleAccount'] = map['sbAWSAccountID']
def sbBucketname = map['sbBucketname']
withAWS(params) {
sh '''
bucketname='''+sbBucketname+'''
# copy the build plan to current directory
aws s3 cp s3://$bucketname/PSScript.ps1 .
'''
}
}
}
}
stage('call PS script') {
steps {
script {
def credentials = map['CredentialsKey']
withAWS(region: 'us-west-1', credentials: credentials) {
sh '''
userID = 'tets'
password = 'password'
pwsh -NonInteractive -File ./PSScript.ps1 $userID $password
'''
}
}
}
}
}
}
Here is my PSScript.ps1 file:
$userIDArg = $args[0];
$passwordArg = $args[1];
function CreateUser($userID, $password) {
$Params = #{
Comment = 'Create a SQL user'
DocumentName = 'AWS-RunPowerShellScript'
Targets = #(
#{
Key = 'InstanceIds'
Values = #(
"i-instanceID"
)
})
Parameters = #{
commands = #(
Write "'$userID $password'" #This line prints empty userid and password
)
}
}
$JsonStr = $Params | ConvertTo-Json -Depth 4
$FileName = 'SSMCommandTempFile-' + $(get-date -f MM-dd-yyyy_HH_mm_ss) + '.json'
$FilePattern = 'file://' + $FileName
$JsonStr | Out-File -FilePath $FileName -Encoding ASCII
aws ssm send-command --document-name "AWS-RunPowerShellScript" --cli-input-json $FilePattern
Remove-Item $FileName
}
CreateUser $userIDArg $passwordArg
So the line where I am printing the userID and password arguments in CreateUser method, prints empty values.
Am I doing something wrong here?
Can you try an alternative, you can define parameters for your script (like a function).
PSScript.ps1 with named parameters:
param($userID, $password)
$Params = #{
Comment = 'Create a SQL user'
DocumentName = 'AWS-RunPowerShellScript'
Targets = #(
#{
Key = 'InstanceIds'
Values = #(
"i-instanceID"
)
})
Parameters = #{
commands = #(
Write "'$userID $password'" #This line prints empty userid and password
)
}
}
$JsonStr = $Params | ConvertTo-Json -Depth 4
$FileName = 'SSMCommandTempFile-' + $(get-date -f MM-dd-yyyy_HH_mm_ss) + '.json'
$FilePattern = 'file://' + $FileName
$JsonStr | Out-File -FilePath $FileName -Encoding ASCII
aws ssm send-command --document-name "AWS-RunPowerShellScript" --cli-input-json $FilePattern
Remove-Item $FileName

Modify terminalservicesprofilepath in Powershell from a machine that is non a member of the domain

I'm calling powershell , to set the terminalservicesprofilepath
on a user i've created, the web server is not a member of the domain that I'm modifying..
I remember writing powershell to do this to modify adnames of users long ago,
but I can't remember how it did it, and my google-fu is failing me
$user = [ ADSI ] "LDAP://CN=abab.ababf,DC=AD,DC=JCSN,DC=org";
$user.psbase.Invokeset( "terminalservicesprofilepath", "\\ad\rds\ProfileAlaska\abab.ababf" );
$user.setinfo();
This is the snippet that does the work I took it from a larger script that worked.
I remember having to login to the remote server first... but how do I do that?
The problem turned out to be that the old stuff to set terminalsservicesprofilepath were too old to accept credentials, so I created a ps-session and wrapped them in invoke commands which did accept credentials.
Here is the complete solution I used, you'll probably have to do some fiddling with the parts that set up the computer.
public void DoRDP( string sAdName, string sRdpPath )
{
//SetTerminalServiceProfilePath();
string s= QueryTerminalServices( WtsApi32.WTSUserConfigTerminalServerProfilePath );
string sPowerShell = "" + "\n" +
//==============================================================================================
//== modify this swtuff to get run once only - EWB
//==============================================================================================
// # enaqble remoting to .ddd, do before new-session - ewb "+ (only needs to be done once)
"Enable-PSRemoting –force" + "\n" +
"Set-ExecutionPolicy Unrestricted" + "\n" +
// add the ad server to teh trusted hosts (only needs to be done once)
"winrm s winrm/config/client '#{TrustedHosts=\"xx.xx.xxx.xxx\"}'"+
// also need to give the app pool idenity user win RM Access, run teh following on the command line (change app pool user name, if in different app pool (it's jus the name of the app pool) - EWB
// https://learn.microsoft.com/en-us/iis/manage/configuring-security/application-pool-identities
// https://msdn.microsoft.com/en-us/library/aa384295(v=vs.85).aspx
// Note: this took like 30 min to have an effect, maybe try bouncing iis and the app pools?
"net localgroup WinRMRemoteWMIUsers__ /add \"ASP.NET v4.0 Classic\""+
//==============================================================================================
"import-module ActiveDirectory; " + "\n" +
#"$Username = 'ad\xxxx'; " + "\n" +
"$Password = 'xxxx'; " + "\n" +
"$pass = ConvertTo-SecureString -AsPlainText $Password -Force" + "\n" +
"$SecureString = $pass; " + "\n" +
//# Users with password securly"+
"$MySecureCreds = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $Username,$SecureString; " + "\n" +
"$s = New-PSSession -ComputerName xxxxx -Credential $MySecureCreds; " + "\n" +
"if ($null -eq $s) \n{ \nthrow \"Error creating the session, it was null\" \n}" + "\n" +
#"Invoke-Command -Session $s -ScriptBlock {$user = [ ADSI ] 'LDAP://CN=" + sAdName + ",OU=xxxx Users,OU=xxxx,OU=xxxx,DC=AD,DC=xx,DC=org'; }; " + "\n" +
#"Invoke-Command -Session $s -ScriptBlock {$user.psbase.Invokeset( 'terminalservicesprofilepath', '" + sRdpPath + "' ); }; " + "\n" +
"Invoke-Command -Session $s -ScriptBlock {$user.setinfo()}; " + "\n" +
"Remove-PSSession $s; " + "\n";
RunScript( sPowerShell );
}
/// <summary>
/// Runs the given powershell script and returns the script output.
/// </summary>
/// <param name = "scriptText" > the powershell script text to run</param>
/// <returns>output of the script</returns>
private string RunScript( string scriptText )
{
try
{
var powerShell = PowerShell.Create().AddScript( scriptText );
var results = powerShell.Invoke();
var resList = results.ToList();
foreach ( dynamic item in resList )
{
if( item == null )
{
log.Trace( "item is null" );
}
else
{
log.Trace( item.ToString() );
}
}
return "";
}
catch ( Exception ex )
{
throw;
}
}

How do I set the Start Action (external program) used by csproj file from powershell

I'm writing a nuget install script in powershell and I want to set the 'Start Action' for the project file (*.csproj). I have access to the Project interface from EnvDTE vai the variable $project.
I know setting the 'Start Action' manually creates a local *.user file in the file system, is there anyway I can do this programmatically from a powershell script via EnvDTE?
This is how I achieved it:
param($installPath, $toolsPath, $package, $project)
function HasStartAction ($item)
{
foreach ($property in $item.Properties)
{
if ($property.Name -eq "StartAction")
{
return $true
}
}
return $false
}
function ModifyConfigurations
{
$configurationManager = $project.ConfigurationManager
foreach ($name in $configurationManager.ConfigurationRowNames)
{
$projectConfigurations = $configurationManager.ConfigurationRow($name)
foreach ($projectConfiguration in $projectConfigurations)
{
if (HasStartAction $projectConfiguration)
{
$newStartAction = 1
$newStartProgram = $fullPath + "bin\" + $name + "\Shell\XXXX.exe"
$newWorkingDirectory = $fullPath + "bin\" + $name + "\Shell\"
write-host "StartAction - " $newStartAction
write-host "StartProgram - " $newStartProgram
write-host "WorkingDirectory - " $newWorkingDirectory
$projectConfiguration.Properties.Item("StartAction").Value = $newStartAction
$projectConfiguration.Properties.Item("StartProgram").Value = $newStartProgram
$projectConfiguration.Properties.Item("StartWorkingDirectory").Value = $newWorkingDirectory
}
}
}
$project.Save
}
write-host "Modifying Configurations..."
ModifyConfigurations

How to escape ` (tick) in inline javascript code?

inlineJs = `
function(){ return 'It won`t compile' }
`
This code wont compile because of ` (tick) in inline javascript code - how I can escape it?
inlineJs = `
function(){ return 'It won\`t compile' }
`
alert inlineJs()
simply escaped by \

Output ssh command to text file in powershell

I am trying to output the following command to a text file in powershell, but I cannot seem to get it working:
ssh -v git#git.assembla.com | Out-File C:\output.txt
As stated in the post below with using native apps, you could try using Start-Process, e.g.
Start-Process ssh "-v git#git.assembla.com" -NoNewWindow -RedirectStandardOutput stdOut.log -RedirectStandardError stdErr.log; gc *.log; rm *.log
Working on the same problem I made a detail post on my blog How to SSH from Powershell Using Putty\Plink but the short version is this bit of code. But sure you try it after installing putty.
Function Invoke-SSHCommands {
Param($Hostname,$Username,$Password, $CommandArray, $PlinkAndPath, $ConnectOnceToAcceptHostKey = $true)
$Target = $Username + '#' + $Hostname
$plinkoptions = "-ssh $Target -pw $Password"
#Build ssh Commands
$remoteCommand = ""
$CommandArray | % {$remoteCommand += [string]::Format('{0}; ', $_) }
#plist prompts to accept client host key. This section will login and accept the host key then logout.
if($ConnectOnceToAcceptHostKey)
{
$PlinkCommand = [string]::Format('echo y | & "{0}" {1} exit', $PlinkAndPath, $plinkoptions )
#Write-Host $PlinkCommand
$msg = Invoke-Expression $PlinkCommand
}
#format plist command
$PlinkCommand = [string]::Format('& "{0}" {1} "{2}"', $PlinkAndPath, $plinkoptions , $remoteCommand)
#ready to run the following command
#Write-Host $PlinkCommand
$msg = Invoke-Expression $PlinkCommand
$msg
}
$PlinkAndPath = "C:\Program Files (x86)\PuTTY\plink.exe"
$Username = "remoteshell"
$Password = "pa$$w0rd"
$Hostname = "Linuxhost"
$Commands = #()
$Commands += "ls"
$Commands += "whoami"
Invoke-SSHCommands -User $Username -Hostname $Hostname -Password $Password -PlinkAndPath $PlinkAndPath -CommandArray $Commands