@@ -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,37 +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
- var constExprAst = computerNameArgument as ConstantExpressionAst ;
63
- if ( null != constExprAst )
68
+ computerNameArgument = GetComputerNameArg ( CmdAst , cmdParamAst . Extent . StartOffset ) ;
69
+ if ( computerNameArgument == null )
64
70
{
65
- var constExprVal = constExprAst . Value as string ;
66
- if ( null != constExprVal )
67
- {
68
- return ! localhostRepresentations . Contains < string > (
69
- constExprVal ,
70
- StringComparer . OrdinalIgnoreCase ) ;
71
- }
72
-
71
+ return false ;
73
72
}
74
-
75
- return false ;
76
73
}
77
74
78
- if ( null != cmdParamAst . Argument && ! localhostRepresentations . Contains ( cmdParamAst . Argument . ToString ( ) . Replace ( "\" " , "" ) . Replace ( "'" , "" ) . ToLower ( ) ) )
75
+ var constExprAst = computerNameArgument as ConstantExpressionAst ;
76
+ if ( constExprAst != null )
79
77
{
80
- return cmdParamAst . Argument is ConstantExpressionAst ;
78
+ return ! IsLocalhost ( constExprAst ) ;
81
79
}
82
80
}
83
81
}
84
82
85
83
return false ;
86
84
}
87
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
+
88
99
private Ast GetComputerNameArg ( CommandAst CmdAst , int StartIndex )
89
100
{
90
101
int small = int . MaxValue ;
0 commit comments