2013-07-28 105 views

回答

4

%HOMESHARE%可能僅僅是未定義的(它並未在所有情況下定義)。 %DATE%%TIME%是AFAIK在CMD之外不可用的動態變量(對於例如%CD%%ERRORLEVEL%也是如此)。

+1

+1:雖然我們在這,同樣也適用於'%RANDOM%','%HIGHESTNUMANODENUMBER% ','%CMDEXTVERSION%%'和'%CMDCMDLINE%' - 雖然後面的看起來很明顯;-) –

2

@Ansgar Wiechers當然是正確的,我認爲我將代碼提供給以下函數,該函數也試圖替換(某些)CMD.EXE特定變量。

public static string ExpandEnvironmentVariables(string str) 
    { 
     // Environment.ExpandEnvironmentVariables() does this as well, but we don't rely on that. 
     if (str == null) 
      throw new ArgumentNullException("str"); 

     // First let .NET Fx version do its thing, because then: 
     // 
     // - Permission checks, etc. will already be done up front. 
     // - Should %CD% already exists as a user defined variable, it will already be replaced, 
     // and we don't do it by the CurrentDirectory later on. This behavior is consistent with 
     // what CMD.EXE does. 
     // Also see http://blogs.msdn.com/b/oldnewthing/archive/2008/09/26/8965755.aspx. 
     // 
     str = Environment.ExpandEnvironmentVariables(str); 

     // The following is rather expensive, so a quick check if anything *could* be required at all 
     // seems to be warrented. 
     if (str.IndexOf('%') != -1) 
     { 
      const StringComparison comp = StringComparison.OrdinalIgnoreCase; 
      var invariantCulture = CultureInfo.InvariantCulture; 
      var now = DateTime.Now; 

      str = str.Replace("%CD%", Environment.CurrentDirectory, comp); 
      str = str.Replace("%TIME%", now.ToString("T") + "," + now.ToString("ff"), comp); 
      str = str.Replace("%DATE%", now.ToString("d"), comp); 
      str = str.Replace("%RANDOM%", s_random.Next(0, Int16.MaxValue).ToString(invariantCulture), comp); 

      // Debatable, but we replace them anyway to make sure callers don't "crash" because 
      // them not being unexpanded, and becase we "can". 

      str = str.Replace("%CMDEXTVERSION%", "2", comp); // This is true at least on XP to Server 2008R2 
      str = str.Replace("%CMDCMDLINE%", Environment.CommandLine, comp); 

      uint nodeNumber; 
      if (!NativeMethods.GetNumaHighestNodeNumber(out nodeNumber)) 
      { 
       nodeNumber = 0; 
      } 

      str = str.Replace("%HIGHESTNUMANODENUMBER%", nodeNumber.ToString(invariantCulture), comp); 
     } 

     return str; 
    } 

GetNumaHighestNodeNumber P中的定義/調用如下:

[DllImport(KernelDll)] 
    [return: MarshalAsAttribute(UnmanagedType.Bool)] 
    public static extern bool GetNumaHighestNodeNumber([Out] out uint HighestNodeNumber);