I've been racking my brain on this one and can't seem to figure it out. I don't see any extra quotes anywhere. Am I running into an issue with parsing the quotes?
The string starting:
At C:\scripts\365-export.ps1:288 char
:51
+ $execute = read-host -Prompt "Are you Sure?: (y/n) <<<< "
is missing the terminator: ".
At C:\scripts\365-export.ps1:297 char
:9
+ MainMenu <<<<
+ CategoryInfo : ParserError: (
if ($execute ...u}
}
MainMenu:String) [], ParseException
+ FullyQualifiedErrorId : TerminatorExpectedAtEndOfString
Here are lines 288 through 297
$execute = read-host -Prompt "Are you Sure?: (y/n)"
if ($execute -ieq y) {New-MailboxSearch $searchname $endD $estimate $excludedupes $force $iph $recipient $keyword $sender $sourcebox $startD $statusmail $targetbox
} else {SConfMenu}
#END OF COMMAND EXECUTION
} else {
MainMenu}
}
MainMenu
I'm not sure if this will help but I've placed the script in pastebin here:
http://pastebin.ca/2532441
Any help is appreciated.
After adding the recommended quotes at ($execute -ieq "y"), I'm receiving this error now...
The string starting:
At C:\scripts\365-export.ps1:289 char
:21
+ if ($execute -ieq "y <<<< ") {New-MailboxSearch $searchname $endD $estimate $
excludedupes $force $iph $recipient $keyword $sender $sourcebox $startD $statu
smail $targetbox
is missing the terminator: ".
missing " # ($execute -ieq y)
if ($execute -ieq "*y"*)
The issue was found earlier in the code.
There was a problem with a variable that needed to be quoted with single quotes instead of double quotes.
Related
I have bellow script
$ErrorActionPreference = "Stop";
while($true) {
try {
Write-Host "Step 1";
Dir C:\arts #Error
Write-Host "Step 2";
exit 0
break;
}
catch {
"Error in " + $_.InvocationInfo.ScriptName + " at line: " + $_.InvocationInfo.ScriptLineNumber + ", offset: " + $_.InvocationInfo.OffsetInLine + ".";
$Error
exit 1
break;
}
}
It stops on Dir C:\arts line and that is good for me. As I understood it happens cos I have line $ErrorActionPreference = "Stop"; at the beginning.
I also have some docker params
Param(
[Parameter(Mandatory=$True,ParameterSetName="Compose")]
[switch]$Compose,
[Parameter(Mandatory=$True,ParameterSetName="ComposeForDebug")]
[switch]$ComposeForDebug,
[Parameter(Mandatory=$True,ParameterSetName="StartDebugging")]
[switch]$StartDebugging,
[Parameter(Mandatory=$True,ParameterSetName="Build")]
[switch]$Build,
[Parameter(Mandatory=$True,ParameterSetName="Clean")]
[switch]$Clean,
[parameter(ParameterSetName="Compose")]
[Parameter(ParameterSetName="ComposeForDebug")]
[parameter(ParameterSetName="Build")]
[parameter(ParameterSetName="Clean")]
[ValidateNotNullOrEmpty()]
[String]$Environment = "Debug"
)
If I put $ErrorActionPreference = "Stop" line before docker params I will have error Cannot convert value "System.String" to type "System.Management.Automation.SwitchParameter". Boolean parameters accept only Boolean values and numbers, such as $True, $False, 1 or 0.
In case if I put $ErrorActionPreference = "Stop"; line after docker params, script is continued to run and that is not that I want.
I do not know what I need to do here, so I will be grateful for any help
$ErrorActionPreference doesn't work with command line utilities like docker as they don't throw exceptions in PowerShell. You would have to use returncode/errorlevel or parse the output to handle those type of errors. Useful automatic variables:
$?
Contains the execution status of the last operation. It contains
TRUE if the last operation succeeded and FALSE if it failed.
$LastExitCode
Contains the exit code of the last Windows-based program that was run. Same as %errorlevel% in cmd.
If you detect an error, you can throw an exception to stop the script or use something like exit to stop the script. Example:
function Test-Error {
$ErrorActionPreference = "Stop"
Write-Host Before
ping -n 1 123.123.123.123
#If last command was not successfull.
#You can also have checked $lastexitcode, output etc.
if($? -eq $false) {
#Throw terminating error
#throw "Error"
#Or since we've chosen to stop on non-terminating errors, we could use:
Write-Error -ErrorId $LASTEXITCODE -Message "Ping failed"
}
Write-Host After
}
Test-Error
Output:
Before
Pinging 123.123.123.123 with 32 bytes of data:
Request timed out.
Ping statistics for 123.123.123.123:
Packets: Sent = 1, Received = 0, Lost = 1 (100% loss),
Test-Error : Ping failed
At line:22 char:1
+ Test-Error
+ ~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [Write-Error], WriteErrorException
+ FullyQualifiedErrorId : 1,Test-Error
If you're creating a advanced function, you could set the default ErrorAction for the scope of the cmdlet like this:
function Test-Error {
[CmdLetBinding()]
param(
$Name = "World"
)
#If -ErrorAction is not specified by the user, use Stop for the scope of the function
if(-not $MyInvocation.BoundParameters.ContainsKey("ErrorAction")) { $ErrorActionPreference = "Stop" }
"Hello $Name ! My ErrorAction is: $ErrorActionPreference"
}
PS > $ErrorActionPreference
Continue
PS > Test-Error -ErrorAction Ignore
Hello World ! My ErrorAction is: Ignore
PS > Test-Error
Hello World ! My ErrorAction is: Stop
I am using two files to send messages with Mailgun. They are:
email_sender.rb
message_text.rb
The code for the first one is:
require './message_text.rb'
fromLabel = "Email Guy"
fromAddress = "digital#mail.*****.com"
toAddress = "info#*****.net"
subject = "An Invitation"
cmd = "curl -s --user 'api:key-*****' https://api.mailgun.net/v3/mail.*****.com/messages -F from='" + fromLabel + " <" + fromAddress + ">' -F to='" +toAddress + "' -F subject='" + subject + "' -F text='" + $message + "'"
wasGood = system (cmd)
The code for the second file is:
$message = "Line One Text."
+ "\n" + "\n" + "And Line Two Text!"
When I test sending an email, the message that arrives in my test account inbox is as follows.
Line One Text.
If you run the code with ruby -w, that is: with warnings enabled, it warns: warning: possibly useless use of + in void context, with the according line number, pointing to:
$message = "Line One Text."
+ "\n" + "\n" + "And Line Two Text!"
Which is a polite way of Ruby saying: "well, it's not a syntax error, but it does not make sense to me."
Try it with
$message = "Line One Text.
And Line Two Text!" # or: "Line One Text.\n\nAnd Line Two Text!"
So I got it working by putting everything on a single line.
$message = "Line One Text!" + "\n" + "\n" + "Line Two Text!"
In my Powershell script, I use "rmtshare.exe" to get information about share level permission. The "rmtshare.exe" can run perfectly under CMD environment with following command:
rmtshare.exe \\fs-sw-206\"C&C FQT"
However, when I bring it to powershell environment. I can't figure out how to escape the space and the ampersand. Here is what I have tried so far which it is not working:
$rmtShare = "C:\rmtshare.exe"
$ServerName = "fs-sw-206"
$ShareName = "C&C FQT"
Invoke-Expression ($rmtShare + " " + "\\" + $ServerName + "\" + $ShareName)
The script above will give error message from the CMD, it said "if a sharename or path contains spaces, it should be enclosed in quotes".
If I changed the last line to this:
Invoke-Expression ($rmtShare + " " + "\\" + $ServerName + "\" + "'"+'"'+"'" + $ShareName +"'"+'"'+"'")
The error message was from Powershell itself, it said "The ampersand (&) character is not allowed". NOTE: if there is no ampersand, it works. So, now I am stuck because I need to escape both characters at the same time.
Please offer your solution.
You may need to download the rmtshare.exe to test out yourself. Download site: (https://www.symantec.com/connect/downloads/remove-folder-share-remote-computer)
so, here is the code in Powershell that overcame the problem - escape space and ampersand in same time in powershell script that execute CMD
$s = " "
$q = '"'
$Verbatim = '--%'
$rmtShare = "C:\rmtshare.exe"
$ServerName = "fs-sw-206"
$ShareName = "C&C FQT"
Invoke-Expression ($rmtShare +$s+$Verbatim+$s+"\\"+$ServerName+"\"+$q+$ShareName+$q)
There should be other solutions as well. Please post if you know it.
This question already has answers here:
Can I get "&&" or "-and" to work in PowerShell?
(13 answers)
Closed 9 years ago.
What would be the equivalent statement of CMD's:
dir && cd ..
in Powershell?
I tried:
dir -and cd ..
but it throws error:
Get-ChildItem : A parameter cannot be found that matches parameter name
'and'.
At line:1 char:5
+ dir -and (cd ..)
+ CategoryInfo : InvalidArgument: (:) [Get-ChildItem], ParameterBindingException
+ FullyQualifiedErrorId : NamedParameterNotFound,Microsoft.PowerShell
.Commands.GetChildItemCommand
There is not a direct equivalent in PowerShell of cmd.exe && which means "only execute right-hand side if the left-hand side succeeds." However you could write a short function to do the equivalent:
function IfTrue([ScriptBlock] $testExpression, [ScriptBlock] $runExpression) {
if ( & $testExpression ) { & $runExpression }
}
For example:
IfTrue { get-childitem "fileThatExists.txt" -ea SilentlyContinue } { "File exists..." }
If you want for the $testExpression to produce output, the IfTrue function can be written as follows:
function IfTrue([ScriptBlock] $testExpression, [ScriptBlock] $runExpression) {
& $testExpression
if ( $? ) { & $runExpression }
}
Bill
How about this?
dir; if ($?) {cd ..}
Running get-help about_automatic_variables | more explains:
$? Contains the execution status of the last operation. It contains
TRUE if the last operation succeeded and FALSE if it failed.
In PS, dir is just an alias for get-ChildItem; cd likewise for Set-Location.
edit: Same question here, including an answer straight from the horse's mouth.
I need to echo a series of elements of an array in PowerShell, but provide various delimiters between the elements, so I'm using;
Add-Content -Path $tempInputDir\testoutput.log -value ($($fields[0]) + " "+
$($fields[1]) + " " + $($fields[2]) + " " + $($fields[3]) + " "+
$($fields[15]) + " " + $($fields[17]))
}
I need to be able to add tabs and space characters, as you can see from the code above I've just done this by physically adding tabs and spaces in between double quotes, but I'm sure this will cause problems down the line.
What's the correct way to echo these characters to a file? I read somewhere that "'t" could be used, but that doesn't seem to work?
You can use `t for a tab character in a double quoted string. You can also simplify the above to:
"$($fields[0]) $($fields[1]) $($fields[2]) $($fields[3]) $($fields[15]) $($fields[17])" | Add-Content $tempInputDir\testoutput.log
To join the nominated fields together with tabs:
[string]::join("`t", (0..3,15,17 | % {$fields[$_]}))