microsoft / PSRule

Validate infrastructure as code (IaC) and objects using PowerShell rules.
https://microsoft.github.io/PSRule/v2/
MIT License
385 stars 49 forks source link

Inconsistent handling of $PWD #249

Closed BernieWhite closed 5 years ago

BernieWhite commented 5 years ago

Description of the issue

$PWD is not always set as expected during PSRule execution.

To Reproduce

Steps to reproduce the issue:

# Synopsis: Test $PWD automatic variable
Rule 'WithPWD' {
    $PWD.ToString() -eq $TargetObject.PWD.ToString()

}
$testObject = [PSCustomObject]@{
    PWD = $PWD
}

$testObject | Invoke-PSRule -Path $ruleFilePath -Name 'WithPWD';

Expected behaviour

$PWD should use the same path before and during PSRule execution.

Module in use and version:

Captured output from $PSVersionTable:

Name                           Value
----                           -----
PSVersion                      6.2.1
PSEdition                      Core
GitCommitId                    6.2.1
OS                             Microsoft Windows 10.0.18362
Platform                       Win32NT
PSCompatibleVersions           {1.0, 2.0, 3.0, 4.0…}
PSRemotingProtocolVersion      2.3
SerializationVersion           1.1.0.1
WSManStackVersion              3.0
LaurentDardenne commented 5 years ago

What drive location do we need: that of Powershell runspace, that of the module containing the rule, that of the script calling Invoke-PsRule ? Is the addition of a specific variable to Psrule feasible (needed?) ?

BernieWhite commented 5 years ago

@LaurentDardenne $PWD is built-in to PowerShell, set to the current working directory. The issue is that the value or $PWD differs between the runspace calling Invoke-PSRule and what a rule sees during rule execution.

It doesn't happen in all cases, but I notice the issue when I was trying to load a file from disk within a rule.

Yeah, the fix is to just set the variable inside the rule runspace to match the calling process.

LaurentDardenne commented 5 years ago

It doesn't happen in all cases, but I notice the issue when I was trying to load a file from disk within a rule.

It is not this case ?

BernieWhite commented 5 years ago

@LaurentDardenne No not in this case. It seems to be related to how the process is run, possibly only affecting PowerShell Core. In this case it was defaulting $PWD to C:\WINDOWS\System32.