我只是不喜欢以下语法:
if (Test-Path $path) { ... }
Run Code Online (Sandbox Code Playgroud)
和
if (-not (Test-Path $path)) { ... }
if (!(Test-Path $path)) { ... }
Run Code Online (Sandbox Code Playgroud)
特别是在检查"不存在"这种常见用途时,括号太多且不易读.有什么更好的方法呢?
更新:我目前的解决方案是使用别名exist,并not-exist为解释在这里.
PowerShell存储库中的相关问题:https://github.com/PowerShell/PowerShell/issues/1970
当您使用PowerShell中的.NET对象时,它需要一个文件名,它似乎总是相对于C:\Windows\System32.
例如:
[IO.File]::WriteAllText('hello.txt', 'Hello World')
Run Code Online (Sandbox Code Playgroud)
......会写C:\Windows\System32\hello.txt,而不是C:\Current\Directory\hello.txt
为什么PowerShell会这样做?这种行为可以改变吗?如果无法更改,我该如何解决?
我已经尝试了Resolve-Path,但这只适用于已经存在的文件,并且它总是太冗长而无法一直进行.
我有通过 SSIS 进程任务调用的以下 PowerShell 脚本来检查文件是否被锁定 - 如何修改以便它首先检查文件是否存在。
如果不存在,则以 999 退出
如果它确实存在但被锁定,则以 999 退出
如果它确实存在并且未被锁定,则以 0 退出
$file = "\\xxxxxx\xxxx\xxxxx\xxxxxxxxx\task_status.log"
try { [IO.File]::OpenWrite($file).close();exit 0 } catch { exit 999}
Run Code Online (Sandbox Code Playgroud)powershell ×3