@@ -30,6 +30,14 @@ namespace Microsoft.Windows.PowerShell.ScriptAnalyzer.BuiltinRules
30
30
#endif
31
31
public class AvoidUsingComputerNameHardcoded : AvoidParameterGeneric
32
32
{
33
+ private readonly string [ ] localhostRepresentations = new string [ ]
34
+ {
35
+ "localhost" ,
36
+ "." ,
37
+ "::1" ,
38
+ "127.0.0.1"
39
+ } ;
40
+
33
41
/// <summary>
34
42
/// Condition on the cmdlet that must be satisfied for the error to be raised
35
43
/// </summary>
@@ -54,29 +62,40 @@ public override bool ParameterCondition(CommandAst CmdAst, CommandElementAst CeA
54
62
55
63
if ( String . Equals ( cmdParamAst . ParameterName , "computername" , StringComparison . OrdinalIgnoreCase ) )
56
64
{
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 )
61
67
{
62
- if ( ! localhostRepresentations . Contains ( computerNameArgument . Extent . Text . ToLower ( ) ) )
68
+ computerNameArgument = GetComputerNameArg ( CmdAst , cmdParamAst . Extent . StartOffset ) ;
69
+ if ( computerNameArgument == null )
63
70
{
64
- return computerNameArgument is ConstantExpressionAst ;
71
+ return false ;
65
72
}
66
-
67
- return false ;
68
73
}
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 )
71
77
{
72
- return cmdParamAst . Argument is ConstantExpressionAst ;
78
+ return ! IsLocalhost ( constExprAst ) ;
73
79
}
74
80
}
75
81
}
76
82
77
83
return false ;
78
84
}
79
85
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
+
80
99
private Ast GetComputerNameArg ( CommandAst CmdAst , int StartIndex )
81
100
{
82
101
int small = int . MaxValue ;
0 commit comments