![Powershell - 为什么不能在我的脚本中使用这个变量?](https://linux22.com/image/1572131/Powershell%20-%20%E4%B8%BA%E4%BB%80%E4%B9%88%E4%B8%8D%E8%83%BD%E5%9C%A8%E6%88%91%E7%9A%84%E8%84%9A%E6%9C%AC%E4%B8%AD%E4%BD%BF%E7%94%A8%E8%BF%99%E4%B8%AA%E5%8F%98%E9%87%8F%EF%BC%9F.png)
为什么我不能在我的脚本中使用这个变量?
我运行带有参数“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}