Powershell - 为什么不能在我的脚本中使用这个变量?

Powershell - 为什么不能在我的脚本中使用这个变量?

为什么我不能在我的脚本中使用这个变量?

我运行带有参数“Untitled1.ps1 -filePath C:\scripts\test01 -logPath C:\scripts”的脚本,结果是

步骤1 C:\scripts\test01 C:\scripts

步骤2 C:\scripts\test01 C:\scripts

步骤3“$arg2”

为什么步骤3没有显示结果“步骤3 C:\

脚本-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

答案1

我认为问题出在这一行:

$action = {$arg2}

因为从我在 PowerShell 上读到的内容来看,它应该${arg2}只用括号内的变量名来书写,而调用与上面相同的行只会返回变量名称的字符串。请记住,花括号仅表示复杂的名称。

$action = ${arg2}

答案2

我在 {} 中使用了 $Env:,成功了!感谢大家的建议。

(我的成果是运行脚本
.\StartMonitoring.ps1 -filePath C:\scripts\test01 -logPath C:\scripts\log 并使用参数 $logPath 进入 {} 。)

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}

參考文獻:如何监视文件夹并在创建或编辑文件时触发命令行操作?

相关内容