I have the function below where i pass in two arrays. I would like the script to exit on the first occurrence of an error.
I tried different variations but i can't make the script to stop early.
I have tried to use ($LastExitCode -eq 0) it doesn't seem to work, all the scripts still continue running.
I also tried If ($? -ne "True") it doesn't work either, all the tests don't run at all.
function Run-Coverage {
param($openCoverPath,$testExecutorPath,$dllPath,$output)
& $openCoverPath `
-threshold:100 `
-register:user `
-target:$testExecutorPath `
-targetargs:"$dllPath" `
-output:$output `
}
function Run-Tests
{
param($Dll,$Xmls)
for ($i=0; $i -lt $Dlls.length; $i++)
{
$TestParam = $Dlls[$i]
$resultParam = $Xmls[$i]
$dllPath = -join("`"",$projectBasePath,$TestParam," ","/TestCaseFilter:`"(TestCategory!=RequiresData)`"","`"")
$output = -join($outputPath,$resultParam)
try
{
Run-Coverage -openCoverPath $openCoverPath -testExecutorPath $testExecutorPath -dllPath $dllPath -output $output
}
catch
{
Write-Host "Exiting loop"
break
}
}
}
If you add [CmdletBinding()] as the first line inside the function (above the param() block), you can call the function with added Common parameters like ErrorAction, ErrorVariable etc.
try {
Run-Coverage -openCoverPath $openCoverPath -testExecutorPath $testExecutorPath -dllPath $dllPath -output $output -ErrorAction Stop
}
catch {
throw
}
As #Paolo answered - you can do it easily using $ErrorActionPreference = "Stop" or make it a little bit custom using:
trap {
Write-Host "Exception occured: $($_.Exception.Message)";
#Some action to do with the error
exit 1;
}
I am trying to get my SendGoogleForm script to work. The issue I have at the moment is that the message I am sending with the form is including a powershell script, the problem I have is that the send service is breaking the lines in the code which means I have to manually remove all the extra spaces(see example at bottom).
So I thought that there must be a way to print the powershell code to a file instead and attach it to the email that is sent or fix the spaces issue some other way. It would be good if the answers still are displayed as a regular email like they are today but with the powershell code attached somehow.
/* Send Google Form by Email v2.1 */
/* For customization, contact the developer at amit#labnol.org */
/* Tutorial: http://www.labnol.org/?p=20884 */
function Initialize() {
var triggers = ScriptApp.getProjectTriggers();
for(var i in triggers) {
ScriptApp.deleteTrigger(triggers[i]);
}
ScriptApp.newTrigger("SendGoogleForm")
.forSpreadsheet(SpreadsheetApp.getActiveSpreadsheet())
.onFormSubmit()
.create();
}
function SendGoogleForm(e)
{
try
{
//Här fyller du i mailadresserna för resp avdelning.
var it = "test#test.se";
//Ärende på mailet
var subject = "testt Ny/redigerad anställning";
//Slår ihop alla mailadresser till en.
var email = hr +","+ security +","+ it;
//andra variabler
var bukowskis = "test";
var temporarypass = "Provide a Temporary Password for this user";
var semicolon = ";";
// You may replace this with another email address
//var email = Session.getActiveUser().getEmail();
var s = SpreadsheetApp.getActiveSheet();
var columns = s.getRange(1,1,1,s.getLastColumn()).getValues()[0];
var message = "";
// Only include form fields that are not blank
for ( var keys in columns ) {
var key = columns[keys];
if ( e.namedValues[key] && (e.namedValues[key] != "") ) {
message += key + ' :: '+ e.namedValues[key] + "\n\n";
}
if (key == "Förnamn")
var fornamn = e.namedValues[key];
else if (key == "Efternamn")
var efternamn = e.namedValues[key];
else if (key == "Placering")
var placering = e.namedValues[key];
else if (key == "Titel")
var titel = e.namedValues[key];
else if (key == "Avdelning")
var avdelning = e.namedValues[key];
}
//Lägger till eventuellt namn i ämnesraden.
if(typeof fornamn !== 'undefined'&&typeof efternamn !== 'undefined'){
subject += ", " + fornamn + " " + efternamn ;
message +="New-ADUser -SamAccountName '"+fornamn+"."+efternamn+"' -Name '"+fornamn+" "+efternamn+"' -GivenName '"+fornamn+"' -Surname '"+efternamn+"' -Description '"+test+", "+avdelning+", "+titel+"' -OfficePhone ' ' -EmailAddress '"+fornamn+"."+efternamn+"#test.com' -Path 'OU=Users,OU=test,DC=intern,DC=test,DC=se' -Company 'test' -Department '"+avdelning+"' -Title '"+titel+"' "+semicolon+"$NewPassword = (Read-Host -Prompt '"+temporarypass+"' -AsSecureString) "+semicolon+"Set-ADAccountPassword -Identity '"+fornamn+"."+efternamn+"' -NewPassword $NewPassword -Reset "+semicolon+"Set-ADAccountControl -Identity '"+fornamn+"."+efternamn+"' -Enabled $true";
MailApp.sendEmail(email, subject, message);
}
} catch (e) {
Logger.log(e.toString());
}
}
Example of how the output looks today, not able to just copy to Powershell ISE and run it, sadly.
New-ADUser -SamAccountName 'gadfgdafg.sdfgsdfg' -Name 'gadfgdafg sdfgsdfg'
-GivenName 'gadfgdafg' -Surname 'sdfgsdfg' -Description 'Test, Utlämningen, Alternativ 5' -OfficePhone ' '
-EmailAddress 'gadfgdafg.sdfgsdfg#test.com'
-Path 'OU=Users,OU=test,DC=intern,DC=test,DC=se'
-Company 'test' -Department 'Utlämningen' -Title 'Alternativ 5' ;$NewPassword = (Read-Host -Prompt 'Provide a Temporary Password for this user' -AsSecureString) ;Set-ADAccountPassword -Identity 'gadfgdafg.sdfgsdfg' -NewPassword $NewPassword -Reset ;Set-ADAccountControl -Identity 'gadfgdafg.sdfgsdfg' -Enabled $true
Thanks in advance, I have tried everything I can think of at this point.
When sending e-mails, GMail automatically line-wraps your plain-text messages (at around 78 characters per line). In order to avoid this, you can:
Use another client other than Gmail. Of course, probably not your preferred option, but something to consider.
Get the data through the API. The data you get from it will not be line-wrapped.
Send your message as an HTML message. You can do that with a small modification of your code:
Before
message += key + ' :: '+ e.namedValues[key] + "\n\n";
...
subject += ", " + fornamn + " " + efternamn ;
message +="New-ADUser -SamAccountName '"+fornamn+"."+efternamn+"' -Name '"+fornamn+" "+efternamn+"' -GivenName '"+fornamn+"' -Surname '"+efternamn+"' -Description '"+test+", "+avdelning+", "+titel+"' -OfficePhone ' ' -EmailAddress '"+fornamn+"."+efternamn+"#test.com' -Path 'OU=Users,OU=test,DC=intern,DC=test,DC=se' -Company 'test' -Department '"+avdelning+"' -Title '"+titel+"' "+semicolon+"$NewPassword = (Read-Host -Prompt '"+temporarypass+"' -AsSecureString) "+semicolon+"Set-ADAccountPassword -Identity '"+fornamn+"."+efternamn+"' -NewPassword $NewPassword -Reset "+semicolon+"Set-ADAccountControl -Identity '"+fornamn+"."+efternamn+"' -Enabled $true";
MailApp.sendEmail(email, subject, message);
After
message += key + ' :: '+ e.namedValues[key] + "<br><br>";
...
subject += ", " + fornamn + " " + efternamn ;
message +="New-ADUser -SamAccountName '"+fornamn+"."+efternamn+"' -Name '"+fornamn+" "+efternamn+"' -GivenName '"+fornamn+"' -Surname '"+efternamn+"' -Description '"+test+", "+avdelning+", "+titel+"' -OfficePhone ' ' -EmailAddress '"+fornamn+"."+efternamn+"#test.com' -Path 'OU=Users,OU=test,DC=intern,DC=test,DC=se' -Company 'test' -Department '"+avdelning+"' -Title '"+titel+"' "+semicolon+"$NewPassword = (Read-Host -Prompt '"+temporarypass+"' -AsSecureString) "+semicolon+"Set-ADAccountPassword -Identity '"+fornamn+"."+efternamn+"' -NewPassword $NewPassword -Reset "+semicolon+"Set-ADAccountControl -Identity '"+fornamn+"."+efternamn+"' -Enabled $true";
var htmlBody = "<html><p>" + message + "</p></html>";
MailApp.sendEmail(email, subject, message, {'htmlBody': htmlBody});
The main changes are:
Wrapping your text with HTML code, using a paragraph tag.
Replacing the newlines inside your "message" for <br> tags.
Johan. You're not putting any newline characters into the string, so it's all going to output on a single line. For google-apps-script(js) you can use '/n'. See examples here.
Alternatively, to create the powershell file separately and send it as an attachment, you can add the attachment argument to your MailApp function. You'll have to push the output to a file, which will still require '/n' to break up the lines. You'll also have to store the file somewhere that the form has access to. And you'll need to be sure that the recipient email won't flag the .ps1 fine as potentially malicious. (Which it should be doing. Never run scripts from email attachments!) Attachment example here.
Have fun!
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;
When I deploy with ARM template with both template and parameter file in local folder, it works with no issues. But, same file if in blob container, it prompts me for all parameters. Quite strange and confused. :(
This structure works!
Parameter Set: Deployment via template file and template parameters file
New-AzureRmResourceGroupDeployment -ResourceGroupName -TemplateFile >> -TemplateParameterFile [-Force] [-Mode >>{Incremental | Complete} ] [-Name ] [-StorageAccountName ] [->>TemplateVersion ] [ ]
My above trial is as below and it works:
$TemplateFile = "F:\servicerequestsnippets\FW__Code\Orig\Orig\trial\azuredeploy.json"
$TemplateParameterFile = "F:\servicerequestsnippets\FW__Code\Orig\Orig\trial\azuredeploy.parameters.json"
.
.
.
Test-AzureRmResourceGroupDeployment -ResourceGroupName $ResourceGroupName `
-TemplateFile $TemplateFile `
-TemplateParameterFile $TemplateParameterFile `
-Verbose
But, Parameter file uri approach as below do not work. :(
$TemplateFile = "F:\servicerequestsnippets\FW__Code\Orig\Orig\trial\azuredeploy.json"
$TemplateParametersFile = "https://hbala.blob.core.windows.net/test-container/"
.
.
{
foreach ($blob in $blobs)
{
$TemplateParameterFileLink = $TemplateParametersFile + $blob.Name
write-host $TemplateParameterFileLink
Test-AzureRmResourceGroupDeployment -ResourceGroupName $ResourceGroupName `
-TemplateFile $TemplateFile `
-TemplateParameterFile $TemplateParameterFileLink `
-Verbose
}
}
Note:
a. I even tried TemplateParameterUri but got same Debugmessage as:
cmdlet Test-AzureRmResourceGroupDeployment at command pipeline position 1
Supply values for the following parameters:
(Type !? for Help.)
**administratorLogin:** << *
it is not saying of conflict , and paramfromTemplate.
It would great to get some pointers or what you feel I am missing. Thanks in advance.
Regards,
H Bala
Login-AzureRmAccount
$params = #{SqlServerName="myServer";SqlDatabaseName="myDb";SqlUserName="myDbUser"}
Register-AzureRmAutomationScheduledRunbook `
–Name "AutoExport" `
-ResourceGroupName "myAzureAutomation" `
–AutomationAccountName "myAutomation" `
–ScheduleName "myScedule" `
–Parameters $params `
-ErrorAction Stop;
And when I go on the Azure Portal parameters contain quoted string
Example:
Eventually my Workbook will crash because values expected no quotes. I know, I can remove quotes into script of my Workbook but it seem to me that is not an elegant solution.
What I doing wrong!