0

why can't use this variable in my script?

i run script with parameter "Untitled1.ps1 -filePath C:\scripts\test01 -logPath C:\scripts" and result is

step1 C:\scripts\test01 C:\scripts

step2 C:\scripts\test01 C:\scripts

step3 "$arg2"

Why step3 not show result " step3 C:script

script - Untitled1.ps1

Param

(

[CmdletBinding()]

[string]$filePath,

[string]$logPath

)





Write-Host step1 $filePath $logpath



function Test-Script

{



Param

(

[Parameter(Position=0)]

[string]$arg1,



[Parameter(Position=1)]

[string]$arg2

)



Write-Host step2 $arg1 $arg2



### DEFINE ACTIONS AFTER AN EVENT IS DETECTED

$action = {$arg2}

Write-Host step3 $action

}



Test-Script $filePath $logPath

2 Answers2

3

I believe the problem is in the line:

$action = {$arg2}

Because from what I read up on PowerShell, that it should be written ${arg2} with just the variable name inside the brackets, while calling the same line as above will simply return a string of the variable's name. Remember the curly braces only denote a complex name.

$action = ${arg2}
0

i use $Env: in {} it's work! Thanks all, for the suggestions.

(my achievement is run script
.\StartMonitoring.ps1 -filePath C:\scripts\test01 -logPath C:\scripts\log and use parameter $logPath into {} .)

Param
        (
            [string]$filePath,
            [string]$logPath
        )

    $Env:EnvlogPath = "$logPath"

### SET FOLDER TO WATCH + FILES TO WATCH + SUBFOLDERS YES/NO
    $watcher = New-Object System.IO.FileSystemWatcher
    $watcher.Path = "$filePath"
    $watcher.Filter = "*.*"
    $watcher.IncludeSubdirectories = $true
    $watcher.EnableRaisingEvents = $true  

### DEFINE ACTIONS AFTER AN EVENT IS DETECTED
    $action = { $path = $Event.SourceEventArgs.FullPath
                $changeType = $Event.SourceEventArgs.ChangeType
                $logline = "$(Get-Date), $changeType, $path"
                Add-content "$Env:EnvlogPath\log.txt" -value $logline
              }    
### DECIDE WHICH EVENTS SHOULD BE WATCHED 
    Register-ObjectEvent $watcher "Created" -Action $action
    Register-ObjectEvent $watcher "Changed" -Action $action
    Register-ObjectEvent $watcher "Deleted" -Action $action
    Register-ObjectEvent $watcher "Renamed" -Action $action
    while ($true) {sleep 1}

ref: How to monitor a folder and trigger a command-line action when a file is created or edited?