Powershell equivalent of a conditional operator?

Hi,
I've got a small snippet of Powershell code that works perfectly well, but I'd like to make it better. here it is:
if ($discoveredIssues.Length -gt 0){
$returnHash += @{"IsBatchValid"=$false}
else{
$returnHash += @{"IsBatchValid"=$true}
I don't like the fact that the string literal "IsBatchValid" exists in two places as there's always the chance that someone could change it one place and not the other (very minor quibble, I know).
I was wondering if there was a way to write this such that I don't have the if...then...else. I tried to do this:
$returnHash += @{"IsBatchValid"={if ($discoveredIssues.Length -gt 0){$false}else{$true}}}
but that doesn't work. It just returns "if ($discoveredIssues.Length -gt 0){$false}else{$true}}" rather than the actual result of that expression. I was hoping there might be something like C#'s conditional operator so that I could do something
like this:
    $discoveredIssues.Length -gt 0 ? $false : $true
but sadly not.
Any ideas how I can achieve this? I suspect there isn't a way, but it'd be nice if there were.
thanks
Jamie

$returnHash.IsBatchValid = $discoveredIssues.Length -gt 0
Oh nice. Didn't quite work. Powershell ISE complained:
But it prompted me to go away and change it to this:
$returnHash += @{"IsBatchValid"=$discoveredIssues.Length -eq 0}
which I suppose would have been obvious had I bothered to pay any attention to what I was doing. Always pays to have someone else put eyes on something. thanks mjolinor.
Glad to help.
It wasn't obvious from the code whether $returnHash already exists or not.  I was assuming it did:
$returnHash = @{}
$returnHash.IsBatchValid = $discoveredIssues.Length -gt 0
$returnHash
Name Value
IsBatchValid False
[string](0..33|%{[char][int](46+("686552495351636652556262185355647068516270555358646562655775 0645570").substring(($_*2),2))})-replace " "

Similar Messages

  • Conditional operator question?

    Hello,
    Quick question, are we not allowed to use the conditional operator this way... see code below:
    char volatile ProgString_[] = "\
    {Fan code} \
    12 <Limit11> [C1_ACM2]_[B1] _AND_ \
    bla bla \
    unsigned char UPC_SYSZ_EndOfTable(unsigned long i){ // Find the double '*' in string
    char volatile *u;
    u = &ProgString_[i];
    if(!(strncmp("*", u, 1))){
    i++;
    u = &ProgString_[i];
    if(!(strncmp("*", u, 1))){
    return TRUE;
    else {
    return FALSE;
    else
    return FALSE;
    void UPC_SYSZ_Parse(){
    unsigned char volatile iOCntr = 0;
    unsigned long volatile i;
    for(i=0; i<200; i++){
    (UPC_SYSZ_EndOfTable(i))?(break):(continue); //<<<<< Invalid expression ??
    I would of used the following compact line:
    (UPC_SYSZ_EndOfTable(i))?(break):(continue);    //<<<<< Invalid expression ??
    to periodically test the end of the string by fetching the "EndOfTable() function and evaluating if the double star is detected.
    If detected, I would break out of the for loop, if not then I would continue.
    Is it possible to do it this way?
    thanks for all help!
    r

    Think of it along the lines of each of the operands of the ternary operator must produce a value (which of course break and continue being statements cannot do).
    Based on your brief example here is what I would do
    for(i=0; i<200; i++){
    if (UPC_SYSZ_EndOfTable(i)) break;
    // doesn't make any sense to put more code down here anyway, so no real point to continue}

  • Conditional Operator for Popup Pages!!

    Hi All,
    In my application there are 2 two different pages say 85 and 45. In page 85 i am calling the Iframe in which it will redirect to page 45. Now in that page i.e 45 i have used template as popup. In that i have an IR and HTML regions and a button in IR region. when i click on button then only should show the HTMl Region for that i ahave used conditional operator. But that is not working!!
    So i would like to know wheather conditional will work popup pages. If not let me know the procedure for that!!!!
    Thanks,
    Anoo..

    .. Apart from that, there is no need for your original long list of "if .. else". For a list of possible inputs, you should consider something like this:
    switch(myYear.selection.text)
    case "10": yearSelect=0; break;
    case "11": yearSelect=1; break;
    case "12": yearSelect=2; break;
    case "13": yearSelect=3; break;
    case "14": yearSelect=4; break;
    default: yearSelect=5;
    or, with your input and output, something as simple as
    yearSelect = Number(myYear.selection.text)-10;
    -- but I don't know what your possible range of inputs is. If it's "anything goes", you have to check for a not-in-range and then set it to your default of 5.

  • Conditional operator and nulltype

    hi,
    i have a little problem, it's actually not really a problem, im just curious. i have the following testclass
    public class Test{
      public static void main(String[] args) {
        Double a = false? 1.00: (Double)null; // nullpointer (A)
        Double b = false? 1.00: null;  // works (B)
    }when line (A) is uncommented a NullPointerException is thrown and i have no idea why.
    when i comment out line (A), line (B) works. because the type of the conditional operator is of the other if one of them is NullType.
    so not really a problem because it's better to use (B) but i still want to know why (A) doesn't work.
    Edited by: creichlin on Oct 27, 2008 12:15 PM

    ouch, i am just to stupid. i forgot autoboxing, the NullType is cast to a null Double, then it's autoboxed to a double and then to a Double again.

  • Conditional Operator for else if?

    I used the google compiler on one of my scripts. It worked fine except I am getting hung up on some of the conditional statements it made. Originally I had a series of if else if statements. When changed to Conditional Operator it changes the fuctionality of it. Here we go if anyone can help I will take any tips.
    My version:
    if(myYear.selection.text=="10"){yearSelect=0;}
             else if(myYear.selection.text=="11"){yearSelect=1;}
             else if(myYear.selection.text=="12"){yearSelect=2;}
             else if(myYear.selection.text=="13"){yearSelect=3;}
             else if(myYear.selection.text=="14"){yearSelect=4;}
            else{yearSelect=5;}
    Google version:
    yearSelect="10"==b.selection.text?0:"11"==b.selection.text?1:"12"==b.selection.text?2:"13"==b.selection.text?3:"14"==b.selection.text?4:5,
    Thanks in advance for any advice.
    Brett.

    .. Apart from that, there is no need for your original long list of "if .. else". For a list of possible inputs, you should consider something like this:
    switch(myYear.selection.text)
    case "10": yearSelect=0; break;
    case "11": yearSelect=1; break;
    case "12": yearSelect=2; break;
    case "13": yearSelect=3; break;
    case "14": yearSelect=4; break;
    default: yearSelect=5;
    or, with your input and output, something as simple as
    yearSelect = Number(myYear.selection.text)-10;
    -- but I don't know what your possible range of inputs is. If it's "anything goes", you have to check for a not-in-range and then set it to your default of 5.

  • NEED HELP:To Parse Conditional Operator Within An Expression.

    Hi there:
    I'm having some difficulties to parse some conditoional operator. My requirements is:
    Constants value: int a=1,b=2,c=3
    Input/Given value: 2
    conditional operator expression: d=a|b|c
    Expected result: d=true
    Summary: I like to receive a boolean from anys expressions defined, which check against Input/Given value.Note: The expression are various from time to time, based on user's setup, the method is smart enough to return boolean based on any expression.
    Let me know if you have any concerns.
    Thanks a million,
    selena

    here is a simple example.
    BNF changes
    EXPR ::= OPERATOR
    EXPR ::= OPERATION OPERANT EXPR
    This is as far as I can go, please use it as a template only
    because you need to take into account the precedence using ()
    the logic of the eval was simply right to left so I think it is not what you want
    Cheers
    public interface Expression
         String OR = "|";
         String AND = "&";
         public boolean eval(int value) throws Exception;
    public class ExpressionImpl implements Expression
         public String oper1;
         public String operant;
         public Expression tail;
         /* (non-Javadoc)
          * @see parser.Expression#eval()
         public boolean eval(int value) throws Exception
              int val1 = getValue(oper1);
              if (null == tail)
    System.out.println(val1 + ":" + value);               
                   return (val1 == value);
              else
                   if (OR.equals(operant))
                        return (val1 == value || tail.eval(value));
                   else if (AND.equals(operant))
                        return (val1 == value && tail.eval(value));
                   else
                        throw new Exception("unsupported operant " + operant);
         private int getValue(String operator) throws Exception
              Integer temp = ((Integer)Parser.symbol_table.get(operator));
              if (null == temp)
                   throw new Exception("symbol not found " + operator);
              return temp.intValue();
         public String toString()
              if (null == operant) return oper1;
              return oper1 + operant + tail.toString();
    public class Parser
         public static HashMap symbol_table = new HashMap();
          * recursive parsing
         public Expression parse(String s)
              ExpressionImpl e = new ExpressionImpl();
              e.oper1 = String.valueOf(s.charAt(0));
              if (s.length() == 1)
                   return e;
              else if (s.length() > 2)
                   e.operant = String.valueOf(s.charAt(1));
                   e.tail = parse(s.substring(2));
              else
                   throw new IllegalArgumentException("invalid input " + s);
              return e;
         public static void main(String[] args) throws Exception
              Parser p = new Parser();
              Parser.symbol_table.put("a", new Integer(1));
              Parser.symbol_table.put("b", new Integer(2));
              Parser.symbol_table.put("c", new Integer(3));
              Parser.symbol_table.put("d", new Integer(4));
              Expression e = p.parse("a|b|c&d");
              System.out.println("input " + e.toString());
              System.out.println(e.eval(2));
    }

  • What is the conditional operator for AND, OR .....?

    what is the conditional operator for AND, OR .....? in ABAP language...
    AND, OR .. & is not accepting or recognising.
    Is these feature available in abap ??? if yes, how to use?
    thanks...
    shiva

    Hi,
    Conditional operator for AND and OR are same AND and OR.
    A logical expression consists of comparisons (see expressions 1 to 4 below) and/or selection criteria checks (expression 5) using the operators AND, OR and NOT , as well as the parentheses " (" and ")".
    The individual operators, parentheses, values and fields must be separated by blanks:
    Incorrect:
    f1 = f2 AND (f3 = f4).
    Correct:
    f1 = f2 AND ( f3 = f4 ).
    NOT takes priority over AND, while AND in turn takes priority over OR:
         NOT f1 = f2 OR f3 = f4 AND f5 = f6
    thus corresponds to
         ( NOT ( f1 = f2 ) ) OR ( f3 = f4 AND f5 = f6 )
    The selection criteria comparisons or checks are processed from left to right. If evaluation of a comparison or check proves part of an expression to be true or false, the remaining comparisons or checks in the expression are not performed.
    All data objects that can be converted among each other can be used as operands for logical expressions.
    Check if u are using the AND or OR operator this way.
    IF f1 AND f2.
    ENDIF.
    In this case it will throw error. Here it act as relational operator.
    Regards,
    Prakash

  • SSRS Using Sum and = in a conditional operator

    Hi,
    Still getting to grips with SSRS so any help would be appreciated.
    My aim is to calculate a conditional field using the SSRS expression feature, the datasource is a shared dataset which i can't alter so i can't just go an alter the SQL query or anything.
    In SQL my query would be like this: SELECT COUNT(TotalHours) FROM TableName WHERE TotalHours <= 24
    Is there anyway to combined the Iff and Sum operator's to get a result like the above?
    At present all i managed to come up with is the below but obviously it's not returning the correct amount.
    =IIf(Fields!TotalHours.Value <= "24", Sum(Fields!TotalHours.Value), 0 )
    Please help!
    Edit: Please note that i'm not trying to sum a field based on a condition that relates to another column, i just need a sum of 'TotalHours' that are less than or equal to 24, please also note there is another field called category, each category needs a
    sum of the above.
    Regards,
    Marcus
    Plain_Clueless

    Hi Marcus,
    According to your description, you want to count [TotalHours] when the value of this field is less than 24, right?
    In your scenario, you could use the expression like below:
    =Sum(IIF(Fields!TotalHours.Value<=24,1,0))
    Please note don’t put this expression in the detail rows, you could refer to our test results:
    If you have any question, please feel free to ask.
    Best regards,
    Qiuyun Yu
    Qiuyun Yu
    TechNet Community Support

  • Related to conditional operator

    hai SDNs,
    in select stmt or delete stmt in where clause i have condition like this:
    need the somes values based on condition "A" is in the range 10 - 1000.
    how to write it in where clause...
    what is the operator or any alternative???
    thanking you,

    You should use BETWEEN operator OR you can use RANGES / SELECT-OPTIONS if you are writing this in ABAP.
    SELECT * FROM MARA WHERE MATNR BETWEEN '1' AND '10000'.
    T_RANGES-SIGN = 'BT'.
    T_RANGES-OPTION = 'EQ'.
    T_RNAGES-LOW = '1'.
    T_RANGES-HIGH = '1000'.
    APPEND T_RANGES.
    SELECT * FROM MARA WHERE MATNR IN T_RANGES.
    Regards,
    Ravi
    Note : Please mark all the helpful answers

  • Powershell equivalent to deleting a sccm computer object

    I'm trying to find powershell code that can be used to delete a single SCCM object. The code I have so far is like this:
    $ResourceObject = Get-WmiObject -ComputerName "SCCMSERVER" -Namespace  "ROOT\SMS\site_CFG" -Query "SELECT * FROM SMS_R_SYSTEM WHERE ResourceID='$ResourceID'"
    $ResourceObject.PSBase.Delete()
    Yes, this deletes it from the console (and SMS_R_SYSTEM), but it leaves orphaned ResourceID's everywhere in the database.  Right clicking the object and choosing Delete doesn't leave these orphaned objects.
    Anyone know of a good way to simulate deleting from the GUI through powershell that doesn't leave orphaned ResourceID's everywhere?

    That method is the supported method via the SDK. The records in the SYSTEM_DISC table marked as decommissioned will get removed via the next maintenance task. This is normal operation.
    We had an issue last year where the records were not getting removed properly and it ended up being a policy issue caused by some corrupt packages. If your records are not getting removed you may have a similar issue.
    Daniel Ratliff | http://www.PotentEngineer.com

  • Executing SCVMM PowerShell scripts via C# conditionally works depending on application type

    I suspect that this is the wrong forum but I could not find one that was appropriate.
    The environment is SCVMM 2012 R2. I have a series of PowerShell scripts that are executed via C# code from a variety of applications -- MVC, WCF, console, unit tests. It seems that successful connection to the VMM server is dependent on the type of application
    being used. For example, console apps and WCF apps can connect successfully but the
    same code running in a unit test or standard MVC app throw the following exception:
    {You cannot access VMM management server SC-01. (Error ID: 1604)
    Contact the Virtual Machine Manager administrator to verify that your account is a member of a valid user role and then try the operation again.}
        CategoryInfo: {ReadError: (:) [Get-SCVirtualMachine], CarmineException}
        ErrorDetails: {You cannot access VMM management server SC-01. (Error ID: 1604)
    Contact the Virtual Machine Manager administrator to verify that your account is a member of a valid user role and then try the operation again.}
        Exception: {"You cannot access VMM management server SC-01.\r\nContact the Virtual Machine Manager administrator to verify that your account is a member of a valid user role and then try the operation again."}
        FullyQualifiedErrorId: "1604,Microsoft.SystemCenter.VirtualMachineManager.Cmdlets.GetVMCmdlet"
        InvocationInfo: Command = {Get-SCVirtualMachine}
        PipelineIterationInfo: Count = 0
        ScriptStackTrace: "at <ScriptBlock>, <No file>: line 1"
        TargetObject: null
    I suspect that somehow, each app is running under different credentials but I cannot see how that is possible. Each app exhibits the stated behavior whether running within Visual Studio (w/ IIS Express) [running under my own account] or published to the
    server running under a specific specified account that definitely has permissions to the VMM environment.
    This behavior is easily reproducible with the following code
    -- PS Script as embedded resource
    Get-SCVirtualMachine -VMMServer "SC-01"
    -- C# code to load and execute script
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    using System.Management.Automation;
    namespace LabManagement {
    public class HyperVVirtualMachineManager {
    public IEnumerable<Models.VirtualMachine> GetVirtualMachines() {
    var vms = new List<Models.VirtualMachine>();
    try {
    using (var rs = System.Management.Automation.Runspaces.RunspaceFactory.CreateRunspace()) {
    rs.Open();
    using (var ps = PowerShell.Create()) {
    ps.Runspace = rs;
    var assembly = System.Reflection.Assembly.GetExecutingAssembly();
    var scriptName = "LabManagement.Scripts.GetAllVirtualMachines.ps1";
    using (var s = assembly.GetManifestResourceStream(scriptName)) {
    using (var reader = new System.IO.StreamReader(s)) {
    var script = reader.ReadToEnd();
    ps.AddScript(script);
    var output = ps.Invoke();
    if (ps.Streams.Error.Count > 0) {
    foreach (var item in ps.Streams.Error) {
    // do something
    if (output.Count > 0) {
    foreach (var o in output) {
    // do something
    rs.Close();
    catch (RuntimeException ex) {
    // do something
    return vms;
    -- Console app (Success)
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    namespace VirtualLabManagement.ConsoleTests {
    class Program {
    static void Main(string[] args) {
    // Arrange
    var svc = new LabManagement.HyperVVirtualMachineManager();
    // Act
    var hosts = svc.GetVirtualMachines();
    // Assert
    -- Unit Test (Fails)
    [TestMethod]
    public void TestMethod1() {
    // Arrange
    var svc = new LabManagement.HyperVVirtualMachineManager();
    // Act
    var hosts = svc.GetVirtualMachines();
    // Assert
    Assert.IsNull(hosts);
    As you can see, the code is exactly the same between the different executions but the ability to connect differs.

    Hi Sir,
    I would like to check the following items:
    1. "a variety of applications -- MVC, WCF, console, unit tests." they are all installed on same computer?
    2. VMM server still installed on same computer as these app resides in ?
    (if it is possible please detail the topology of the environment )
    If they are running at same account on same computer , I would suggest you to post this issue into Code UI forum for further assistance :
    https://social.msdn.microsoft.com/Forums/vstudio/en-US/home?forum=vstest
    Best Regards,
    Elton JI
    Please remember to mark the replies as answers if they help and unmark them if they provide no help. If you have feedback for TechNet Subscriber Support, contact [email protected] .

  • 'AND' Conditional operator in smartform

    Hi experts,
    I have  to use AND condition in smartform (text).
    For OR condition there is a standard icon sothat can use.
    But how can we get AND contion in smartform.
    if I am giving AND condition it is showing error
    I have tries in SDN before posting my problem but i couldn't get solution for that
    Please help me out of this problem.

    Hi Saravanan,
    You dont need to give AND condtion. Just give two conditions in the conditions tab. it will work
    Regards
    Shanly

  • PL/SQL Equivalent to the condition "No inline validation errors displayed"

    Hello,
    I've seen this on another thread but can't find it. I need two conditions to be true to show a region: a value is not null and no inline validation errors are showing. Does anyone know the PL/SQL (API call?) to retrieve the number of errors being displayed on screen?

    Malcom,
    You can use the global variable wwv_flow.g_inline_validation_error_cnt for your access.
    So your region displayed condition could be a pl/sql function that would return true or false...like this....
    DECLARE
       l_number_of_errors number := 0;
    BEGIN
       l_number_of_errors := wwv_flow.g_inline_validation_error_cnt;
       If (:P1_test_item is NULL or  l_number_of_errors>0 ) then
             return FALSE;
       else
            return TRUE;
       end if;
    END;So, if the item is null, or there is any inline validation error, the region will not be displayed...

  • Powershell equivalent of DOS %~dp0 command

    Hello Folks!
    Does anyone know of a way to output the directory path of the powershell file being executed is located?  I'm using SCCM to install applications via a script which means the source files (inlcuding the script) will be ran from multiple distribution
    points and I don't want to point to one particular server's source files.
    In Dos or Batch scripts this is done by %~dp0filename.msi.  Is there a way to do this via Powershell?
    Thanks in adavance!!

    If you're using PowerShell version 3.0 or later, this is in an automatic variable called $PSScriptRoot.
    In PowerShell 2.0, that variable didn't exist, but you could get at the same information through $MyInvocation.  For example:
    $scriptRoot = Split-Path -Path $MyInvocation.MyCommand.Path

  • What is the powershell equivalent of unix Export command?

    my unix code is like this
    abc=test1 ; export abc
    xyz=test2 ; export xyz
    i want above script is to be converted into powershell??

    It varies depending on which browser you're using. In Safari, choose Preferences from the Safari menu, click on the Privacy tab, and then on Details.
    (101212)

Maybe you are looking for

  • Enhanced Interface Determination?

    Hi All, I have a scenario where i need to do a header validation . if validation succeeds i have to map source to target data and sent to SAP system. if validation fails i need to map source to error data and sent it to MQ system. I  am using enhance

  • Looking for a nice solution for different cases with nearly same operations

    Hi everybody: I'm looking for a nice solution for the following problem: I'm measuring different data at the same time (with different devices). I would like to save these data all in one array (or cluster?), but I don't know exactly the way to do th

  • Sclaing images without affecting keyline weight

    I'm using InDesign CS3. I place images and apply a Basic Graphics Frame to them (1pt keyline weight). If I then scale the object (say) to 50%, the keyline changes to 0.5pt weight. Is there a preference I can change to keep the keyline at 1pt when sca

  • Calendar Sync/Outlook 2007 Issues

    Help!  I have a 8330 through Verizon and have major calendar sync issues that only seem to be getting worse. I'm using Outlook 2007 running Vista-Business. My Blackberry had been syncing fine for the first few months, but a week ago the calendar sync

  • Can't sync calendar - Zire 72s

    Hi I've reinstalled the operational system (Windows XP Professional) in my computer and since then I've been trying to synchronize my palm (Zire 72s). I'm using the palm desktop 4.1.4 and when I try to sync, it starts ok, running until the calendar.