我需要一个简单的 PowerShell 脚本的帮助。我只是这门语言的初学者,所以请原谅我的任何语言错误。
我需要一个脚本,在执行时将文件(与 PowerShell 脚本位于同一目录中)复制到 PC 上的每个用户目录中(除了少数几个)。这适用于 Windows 7 文件夹结构。
代码思路:
- 解析 C:\Users 下的顶级子目录
- 将名为 deploy.properties 的项目复制到 C:\Users\USER_PROFILE_NAME\AppData\LocalLow\Sun\Java\Deployment\ - 如果文件存在则覆盖该文件,如果不存在则创建文件夹结构
- 不要对所有用户、管理员和默认帐户执行此操作
我有一个脚本可以解析用户名,但运行时它会在每个用户名前添加 @。如果子目录不存在,它也无法创建子目录。我觉得这比我想象的要简单得多。
这是我迄今为止得到的代码:
$UserFolders = get-childitem -path "C:\Users" | ?{$_.Psiscontainer} |select-object fullname
$from = ".\deployment.properties"
foreach ($UserFolder in $Userfolders)
$to = "C:\Users\$UserFolder\AppData\LocalLow\Sun\Java\Deployment\deployment.properties"
New-Item -ItemType File -Path $to -Force
Copy-Item $from $to
}
该代码不会从用户目录中生成任何有意义的数据,并且在运行时会出现目录错误。由于目录尚未创建,因此最近添加了“New-Item”行。说实话,我有点不知所措。我对语法还不熟悉,不知道该如何处理。
答案1
这只是我的想法和观点,关于如何做到这一点...我确实对变量名称做了一些修改,以便它们与使用的 cmdlet 相匹配。您不必只是让它对我来说更具可读性。
# I don't have a domain computer to work with so my local
# PC includes the "public" folder you likely want have
# this but nice to include just in case. As well the "Default*"
# is there because I'm on Windows 8.1
# so the upgrade modified the "Default" folder
# to be "Default.migrated" for some reason.
# The "-Exclude" allows you to put in the names of those items (directory names
# or file names) that you want to exclude, it allows wildcard values as well)
# Then as suggested in a comment using -ExpandProperty FullName allows the
# object to be passed as a string instead of a system object which
# adds on extra characters that some other cmdlet may not like.
$userFolder = Get-ChildItem -Path 'C:\Users' -Exclude 'Default*','All Users','Administrator', 'Public' |
Select -ExpandProperty FullName
# just the file I was playing with here
$sFile = '.\text.txt'
foreach ($uf in $userFolder) {
$dest = "$uf\AppData\LocalLow\Sun\Java\Deployment\"
# I want to test for the path to exist first and if it
# does then add the file, if it does not then you
# would create the directory and copy the file.
# I noticed in yours that you created an empty
# file and then copied it. Works the same way.
if (Test-Path $dest) {
Copy-Item -Path $sFile -Destination $dest -Force
}
else {
New-Item -ItemType Directory -Path $dest -Force
Copy-Item -Path $sFile -Destination $dest -Force
}
}
正如前面提到的,我在一台独立的计算机上玩这个,但我得到的命令输出如下:
New-Item -ItemType Directory -Path C:\Users\Shawn\AppData\LocalLow\Sun\Java\Deployment\ -Force
Copy-Item -Path .\text.txt -Destination C:\Users\Shawn\AppData\LocalLow\Sun\Java\Deployment\ -Force
如果您想先测试一下,还可以通过将命令括在双引号中来让它输出将执行的命令:
"Copy-Item -Path $sFile -Destination $dest -Force"