Skip to content

Commit 86b936f

Browse files
committed
Fixed issues in the original rule, added more testing
1 parent be025c8 commit 86b936f

File tree

2 files changed

+21
-5
lines changed

2 files changed

+21
-5
lines changed

Rules/AvoidUsingComputerNameHardcoded.cs

Lines changed: 16 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,7 @@
1616
using System.ComponentModel.Composition;
1717
using System.Globalization;
1818
using System.Collections.Generic;
19+
using System.Linq;
1920

2021
namespace Microsoft.Windows.PowerShell.ScriptAnalyzer.BuiltinRules
2122
{
@@ -49,11 +50,22 @@ public override bool ParameterCondition(CommandAst CmdAst, CommandElementAst CeA
4950

5051
if (String.Equals(cmdParamAst.ParameterName, "computername", StringComparison.OrdinalIgnoreCase))
5152
{
52-
Ast computerNameArgument = GetComputerNameArg(CmdAst, cmdParamAst.Extent.StartOffset);
53-
List<string> localhostExceptions = new List<string>{ "localhost", ".", "::1", "127.0.0.1" };
54-
if ((null != computerNameArgument) && (!localhostExceptions.Contains(computerNameArgument.Extent.Text)))
53+
List<string> localhostRepresentations = new List<string> { "localhost", ".", "::1", "127.0.0.1" };
54+
Ast computerNameArgument = GetComputerNameArg(CmdAst, cmdParamAst.Extent.StartOffset);
55+
56+
if (null != computerNameArgument)
57+
{
58+
if (!localhostRepresentations.Contains(computerNameArgument.Extent.Text.ToLower()))
59+
{
60+
return computerNameArgument is ConstantExpressionAst;
61+
}
62+
63+
return false;
64+
}
65+
66+
if (null != cmdParamAst.Argument && !localhostRepresentations.Contains(cmdParamAst.Argument.ToString().Replace("\"", "").Replace("'", "").ToLower()))
5567
{
56-
return cmdParamAst.Argument is ConstantExpressionAst || computerNameArgument is ConstantExpressionAst;
68+
return cmdParamAst.Argument is ConstantExpressionAst;
5769
}
5870
}
5971
}

Tests/Rules/AvoidUsingComputerNameHardcodedNoViolations.ps1

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,4 +3,8 @@ Invoke-Command -ComputerName $env:COMPUTERNAME
33
Invoke-Command -ComputerName localhost
44
Invoke-Command -ComputerName .
55
Invoke-Command -ComputerName ::1
6-
Invoke-Command -ComputerName 127.0.0.1
6+
Invoke-Command -ComputerName 127.0.0.1
7+
Invoke-Command -ComputerName:'localhost'
8+
Invoke-Command -ComputerName:"."
9+
Invoke-Command -ComputerName:'::1'
10+
Invoke-Command -ComputerName:"127.0.0.1"

0 commit comments

Comments
 (0)