gpt4 book ai didi

powershell - 在 Get-ChildItem PowerShell 语句中排除子文件夹

转载 作者:行者123 更新时间:2023-12-03 00:13:17 26 4
gpt4 key购买 nike

我一直在尽最大努力更熟悉 PowerShell,将其作为自动化许多常规任务的一种方式,以消除人为错误。我支持基于 Web 的应用程序,我目前的目标是创建一个脚本,将应用程序从一台服务器迁移到另一台服务器。到目前为止,我已经获得了在新服务器上安装应用程序的脚本,从旧服务器复制配置文件,并在进行任何其他更改之前备份所有文件。我需要做的最后一件事是搜索配置目录和所有子文件夹以替换主机名、IP 地址和目录位置的所有实例(如果新服务器上的驱动器号发生变化)有一个文件夹称为 X:\Website\Tools\Database\Upgrade,其中包含客户曾经使用过的每个版本的文件夹,该文件夹内是数据库升级脚本。我无权更改此文件夹中的任何内容,坦率地说,我并不真正关心更改 X:\Website\tools 中的任何内容。

我已将脚本的这一部分编写如下:

#Replace all instances of hostname, IP address, and drive letter
$path = "\\$newip\$newdriveletter$\Website"
$exclude = @("$path\tools\*")
$files = get-childitem $path\*.* -recurse -exclude $exclude
$files | %{
(gc $_) -replace $oldhost, $newhost -replace $oldip, $newip -replace
"${olddriveletter}:\Website", "${newDriveLetter}:\Website" | set-content
$_.fullname
}

当我这样做时,它会替换我想要它替换的所有内容,但它仍然抛出以下错误:
gc : Access to the path 
'\\10.5.17.60\E$\Website\Tools\Database\Upgrade\6.2.0' is denied.
At C:\Folder\Powershell\Migrate.ps1:72 char:6
+ (gc $_) -replace $oldhost, $newhost -replace $oldip, $newip -repl ...
+ ~~~~~
+ CategoryInfo : PermissionDenied:
(\\10.5.17.60\E$...e\Upgrade\6.2.0:String) [Get-Content],
UnauthorizedAccessException
+ FullyQualifiedErrorId :

我还读到 -exclude 参数在 PowerShell 中几乎损坏,并且不适用于排除文件夹。建议是这样格式化:
#Replace all instances of hostname, IP address, and drive letter
$path = "\\$newip\$newdriveletter$\Website"
$files = get-childitem $path\*.* -recurse | select-object -expandproperty
fullname | where-object{$_ -notlike "\\tools\\"}
$files | %{
(gc $_) -replace $oldhost, $newhost -replace $oldip, $newip -replace "${olddriveletter}:\Website", "${newDriveLetter}:\Website" | set-content $_.fullname
}

不幸的是,当我运行它时,出现错误:
Set-Content : Cannot bind argument to parameter 'Path' because it is null.
At C:\Folder\Powershell\Migrate.ps1:72 char:151
+ ... \WebAccess", "${newDriveLetter}:\Website" | set-content $_.fullname

所以基本上我已经实现了最终目标,但我真的很想这样做而不会出现任何错误。如果人们开始运行它并看到红色,他们可能会吓坏了。所以我认为必须有一种方法来排除甚至查看这些文件夹。可能是一个 If 语句,但我不太确定如何格式化它。有什么建议?

最佳答案

如果你只是跑

get-childitem $path\*.* -recurse -exclude $exclude 

您应该会看到它仍在返回您尝试排除的文件夹。这是因为 get-childitem -exclude 不适用于容器。

而是尝试
$files = get-childitem $path\*.* -recurse | where-object{$_.fullname -notlike $exclude}

关于powershell - 在 Get-ChildItem PowerShell 语句中排除子文件夹,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43725818/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com