If Exist Batch Variable Assignment

Set-Variable

Sets the value of a variable. Creates the variable if one with the requested name does not exist.

Syntax

Description

The Set-Variable cmdlet assigns a value to a specified variable or changes the current value. If the variable does not exist, the cmdlet creates it.

Examples

Example 1: Set a variable and get its value

These commands set the value of the desc variable to A description, and then gets the value of the variable.

Example 2: Set a global, read-only variable

This command creates a global, read-only variable that contains all processes on the system, and then it displays all properties of the variable.

The command uses the Set-Variable cmdlet to create the variable. It uses the PassThru parameter to create an object representing the new variable, and it uses the pipeline operator (|) to pass the object to the Format-List cmdlet. It uses the Property parameter of Format-List with a value of all (*) to display all properties of the newly created variable.

The value, "(Get-Process)", is enclosed in parentheses to ensure that it is executed before being stored in the variable. Otherwise, the variable contains the words "Get-Process".

Example 3: Understand public vs. private variables

This command shows how to change the visibility of a variable to Private. This variable can be read and changed by scripts with the required permissions, but it is not visible to the user.

The sample output shows the difference in the behavior of public and private variables.

Required Parameters

-Name

Specifies the variable name.

Type:String[]
Position:1
Default value:None
Accept pipeline input:True (ByPropertyName)
Accept wildcard characters:False

Optional Parameters

-Confirm

Prompts you for confirmation before running the cmdlet.

Type:SwitchParameter
Aliases:cf
Position:Named
Default value:False
Accept pipeline input:False
Accept wildcard characters:False

-Description

Specifies the description of the variable.

Type:String
Position:Named
Default value:None
Accept pipeline input:False
Accept wildcard characters:False

-Exclude

Specifies an array of items that this cmdlet excludes from the operation. The value of this parameter qualifies the Path parameter. Enter a path element or pattern, such as . Wildcards are permitted.

Type:String[]
Position:Named
Default value:None
Accept pipeline input:False
Accept wildcard characters:False

-Force

Forces the command to run without asking for user confirmation.

By default, you can overwrite a variable, unless the variable has an option value of ReadOnly or Constant. For more information, see the Option parameter.

Type:SwitchParameter
Position:Named
Default value:None
Accept pipeline input:False
Accept wildcard characters:False

-Include

Specifies an array of items that this cmdlet includes in the operation. The value of this parameter qualifies the Name parameter. Enter a name or name pattern, such as . Wildcards are permitted.

Type:String[]
Position:Named
Default value:None
Accept pipeline input:False
Accept wildcard characters:False

-Option

Specifies the value of the Options property of the variable.

The acceptable values for this parameter are:

  • None. Sets no options. ("None" is the default.)
  • ReadOnly. Can be deleted. Cannot be not changed, except by using the Force parameter.
  • Constant. Cannot be deleted or changed. Constant is valid only when you are creating a variable. You cannot change the options of an existing variable to Constant.
  • Private. The variable is available only in the current scope.
  • AllScope. The variable is copied to any new scopes that are created.

To see the Options property of all variables in the session, type .

Type:ScopedItemOptions
Parameter Sets:None, ReadOnly, Constant, Private, AllScope, Unspecified
Position:Named
Default value:None
Accept pipeline input:False
Accept wildcard characters:False

-PassThru

Returns an object representing the item with which you are working. By default, this cmdlet does not generate any output.

Type:SwitchParameter
Position:Named
Default value:None
Accept pipeline input:False
Accept wildcard characters:False

-Scope

Specifies the scope of the variable.The acceptable values for this parameter are:

  • Global
  • Local
  • Script
  • A number relative to the current scope (0 through the number of scopes, where 0 is the current scope and 1 is its parent).

Local is the default.

For more information, see about_Scopes.

Type:String
Position:Named
Default value:None
Accept pipeline input:False
Accept wildcard characters:False

-Value

Specifies the value of the variable.

Type:Object
Position:2
Default value:None
Accept pipeline input:True (ByPropertyName, ByValue)
Accept wildcard characters:False

-Visibility

Determines whether the variable is visible outside of the session in which it was created. This parameter is designed for use in scripts and commands that will be delivered to other users. The acceptable values for this parameter are:

  • Public. The variable is visible. (Public is the default.)
  • Private. The variable is not visible.

When a variable is private, it does not appear in lists of variables, such as those returned by Get-Variable, or in displays of the Variable: drive. Commands to read or change the value of a private variable return an error. However, the user can run commands that use a private variable if the commands were written in the session in which the variable was defined.

Type:SessionStateEntryVisibility
Parameter Sets:Public, Private
Position:Named
Default value:None
Accept pipeline input:False
Accept wildcard characters:False

-WhatIf

Shows what would happen if the cmdlet runs. The cmdlet is not run.

Type:SwitchParameter
Aliases:wi
Position:Named
Default value:False
Accept pipeline input:False
Accept wildcard characters:False

Inputs

System.Object

You can pipe an object that represents the value of the variable to Set-Variable.

Outputs

None or System.Management.Automation.PSVariable

When you use the PassThru parameter, Set-Variable generates a System.Management.Automation.PSVariable object representing the new or changed variable. Otherwise, this cmdlet does not generate any output.

Related Links

Batch How To ...

Verify if Variables are Defined

To verify if a variable is defined, we usually check if it has a non-empty value:

IF "%MyVar%"=="" ECHO MyVar is NOT defined

This works, provided the value of MyVar does not contain doublequotes.

In Windows NT 4's CMD.EXE a new IF statement was introduced:

To quote 's on-screen help:

Note:This does require the Command Extensions to be enabled, so make sure you check this before using .

The following code will show if a variable MyVar was defined or not:

IF DEFINED MyVar (ECHO MyVar IS defined) ELSE (ECHO MyVar is NOT defined)

The following code, which works in batch files for all MS-DOS, Windows and OS/2 versions, uses an alternative way to show if a variable is defined or not:

IF "%MyVar%"=="" (ECHO MyVar is NOT defined) ELSE (ECHO MyVar IS defined)

Whereas the method will fail if command extensions are disabled, the second method will fail if MyVar's value contains doublequotes.
Besides, the second method will always fail on the command line in CMD.EXE (though it worked in COMMAND.COM) because undefined variables are treated as literals on the command line.
You may strip MyVar's value of its doublequotes, but then the statement might fail if MyVar's value contains characters like >, <, |, & or even parentheses.
So the safest way (for CMD.EXE) seems to be the method combined with a check if command extensions are enabled:

VERIFY OTHER 2>nul SETLOCAL ENABLEEXTENSIONS IF ERRORLEVEL 1 ECHO Unable to enable extensions IF DEFINED MyVar (ECHO MyVar IS defined) ELSE (ECHO MyVar is NOT defined) ENDLOCAL

 

Hidden or Dynamic Variables

Now let's investigate variables a little further in Windows NT 4 and later.
Type the following commands on the command line, or copy them to a batch file and run that batch file:

IF "%Date%"=="" (ECHO Date is NOT defined) ELSE (ECHO Date IS defined) IF DEFINED Date (ECHO Date IS defined) ELSE (ECHO Date is NOT defined) ECHO Date = %Date% SET Date

The result will look like this:

C:\>IF DEFINED Date (ECHO Date IS defined ) ELSE (ECHO Date is NOT defined ) Date IS defined C:\>IF "06-06-2008" == "" (ECHO Date is NOT defined ) ELSE (ECHO Date IS defined ) Date IS defined C:\>ECHO Date = 06/06/2008 Date = 06-06-2008 C:\>SET Date Environment variable Date not defined

Note my highlighting: the last command, , tells us that the variable Date is not defined, but we can clearly see it is.

Let's modify our test batch file:

CLS IF DEFINED Date (ECHO Date IS defined) ELSE (ECHO Date is NOT defined) ECHO Date = %Date% SET Date PAUSE SET Date=Some Other Value IF DEFINED Date (ECHO Date IS defined) ELSE (ECHO Date is NOT defined) ECHO Date = %Date% SET Date PAUSE SET Date= IF DEFINED Date (ECHO Date IS defined) ELSE (ECHO Date is NOT defined) ECHO Date = %Date% SET Date

Run it again, and the result will look like this:

C:\>IF DEFINED Date (ECHO Date IS defined ) ELSE (ECHO Date is NOT defined ) Date IS defined C:\>ECHO Date = 06/06/2008 Date = 06/06/2008 C:\>SET Date Environment variable Date not defined C:\>PAUSE Press any key to continue . . . C:\>SET Date=Some Other Value C:\>IF DEFINED Date (ECHO Date IS defined ) ELSE (ECHO Date is NOT defined ) Date IS defined C:\>ECHO Date = Some Other Value Date = Some Other Value C:\>SET Date Date=Some Other Value C:\>PAUSE Press any key to continue . . . C:\>SET Date= C:\>IF DEFINED Date (ECHO Date IS defined ) ELSE (ECHO Date is NOT defined ) Date IS defined C:\>ECHO Date = 06/06/2008 Date = 06/06/2008 C:\>SET Date Environment variable Date not defined

Go ahead, run the batch file several times, and try to figure out what is happening and why.

Hint:In Windows NT 4 and later, is one of those variables that are always defined, but don't normally show up in the list when you issue the command without any command line arguments. If you set the variable yourself, then it does show up in the list.
Other "hidden" variables are , , , , , , and . For more details, see the SET page.

It looks like these "hidden" variables are defined, but the command doesn't see them as defined unless their values are set in the CMD.EXE session (or one of its parent sessions).
By "dropping" their values in the CMD.EXE session (), they get back their dynamic (or system) values again.

So now we have a way to check if a "hidden" variable still has its dynamic system value, or a static "custom" value:

SET Date >NUL 2>&1 IF ERRORLEVEL 1 ( ECHO Date still has its dynamic system value ) ELSE ( ECHO Date has been set with a static value )
page last uploaded: 2017-07-06, 12:36

0 thoughts on “If Exist Batch Variable Assignment

Leave a Reply

Your email address will not be published. Required fields are marked *