@@ -30,6 +30,14 @@ namespace Microsoft.Windows.PowerShell.ScriptAnalyzer.BuiltinRules
3030#endif
3131 public class AvoidUsingComputerNameHardcoded : AvoidParameterGeneric
3232 {
33+ private readonly string [ ] localhostRepresentations = new string [ ]
34+ {
35+ "localhost" ,
36+ "." ,
37+ "::1" ,
38+ "127.0.0.1"
39+ } ;
40+
3341 /// <summary>
3442 /// Condition on the cmdlet that must be satisfied for the error to be raised
3543 /// </summary>
@@ -54,29 +62,40 @@ public override bool ParameterCondition(CommandAst CmdAst, CommandElementAst CeA
5462
5563 if ( String . Equals ( cmdParamAst . ParameterName , "computername" , StringComparison . OrdinalIgnoreCase ) )
5664 {
57- List < string > localhostRepresentations = new List < string > { "localhost" , "." , "::1" , "127.0.0.1" } ;
58- Ast computerNameArgument = GetComputerNameArg ( CmdAst , cmdParamAst . Extent . StartOffset ) ;
59-
60- if ( null != computerNameArgument )
65+ Ast computerNameArgument = cmdParamAst . Argument ;
66+ if ( computerNameArgument == null )
6167 {
62- if ( ! localhostRepresentations . Contains ( computerNameArgument . Extent . Text . ToLower ( ) ) )
68+ computerNameArgument = GetComputerNameArg ( CmdAst , cmdParamAst . Extent . StartOffset ) ;
69+ if ( computerNameArgument == null )
6370 {
64- return computerNameArgument is ConstantExpressionAst ;
71+ return false ;
6572 }
66-
67- return false ;
6873 }
69-
70- if ( null != cmdParamAst . Argument && ! localhostRepresentations . Contains ( cmdParamAst . Argument . ToString ( ) . Replace ( "\" " , "" ) . Replace ( "'" , "" ) . ToLower ( ) ) )
74+
75+ var constExprAst = computerNameArgument as ConstantExpressionAst ;
76+ if ( constExprAst != null )
7177 {
72- return cmdParamAst . Argument is ConstantExpressionAst ;
78+ return ! IsLocalhost ( constExprAst ) ;
7379 }
7480 }
7581 }
7682
7783 return false ;
7884 }
7985
86+ private bool IsLocalhost ( ConstantExpressionAst constExprAst )
87+ {
88+ var constExprVal = constExprAst . Value as string ;
89+ if ( constExprVal != null )
90+ {
91+ return localhostRepresentations . Contains < string > (
92+ constExprVal ,
93+ StringComparer . OrdinalIgnoreCase ) ;
94+ }
95+
96+ return false ;
97+ }
98+
8099 private Ast GetComputerNameArg ( CommandAst CmdAst , int StartIndex )
81100 {
82101 int small = int . MaxValue ;
0 commit comments