[英]Run a powershell script when file contents do not match folder names
I'm trying to run a Powershell script that only runs when the file contents of a .txt file match the name of a folder in a different folder. 我正在尝试运行Powershell脚本,该脚本仅在.txt文件的文件内容与其他文件夹中的文件夹名称匹配时才运行。 I don't know if I over complicated the script, but any help would be greatly appreciated.
我不知道我是否使脚本过于复杂,但是任何帮助将不胜感激。
$From = "c:\test folder\content"
$To = "c:\test folder\archive\new"
$Content = Get-Content -path "c:\Test Folder\Content\content.txt" | Out-String
$Archive = Get-ChildItem -path "c:\Test Folder\Archive\" -name | Out-String
If($Archive -notin $Content){
#gets child items and copies them to a new folder
Get-ChildItem $From -recurse | Copy-Item -destination $To
#gets content of file
$Text = Get-Content -path 'c:\test folder\archive\new\content.txt'
#renames the item
Rename-item -Path 'c:\test folder\archive\new' -NewName $Text
}
Get-Content | Out-String
Get-Content | Out-String
is going to output an object of one string rather than an array of strings. Get-Content | Out-String
将输出一个字符串而不是字符串数组的对象。
Example Text file with 3 lines: 3行文本文件示例:
(Get-Content -path Example.txt | Out-String).count
1
(Get-Content -path Example.txt).count
3
This means that when you do the array compare after using Out-String
on the text file with -in
/ -contains
is basically doing -eq
. 这意味着在对带有
-in
/ -contains
的文本文件使用Out-String
之后执行数组比较时,基本上就是-eq
。
As Matt suggests in the comments you could use wildcard or regex operators to look for the name inside the larger string. 正如Matt在评论中建议的那样,您可以使用通配符或正则表达式运算符在较大的字符串中查找名称。
$Content = Get-Content -path "c:\Test Folder\Content\content.txt" -Raw
$Archive = Get-ChildItem -path "c:\Test Folder\Archive\" -Name
If($Content -notmatch $Archive){
Alternatively, with the assumption that the Archive name is a row in the file. 或者,假设存档名称是文件中的一行。 You could get rid of the
Out-String
and just use Get-Content
to get the array of strings and use the array comparisons. 您可以摆脱
Out-String
而只需使用Get-Content
获取字符串数组并使用数组比较。
$Content = Get-Content -path "c:\Test Folder\Content\content.txt"
$Archive = Get-ChildItem -path "c:\Test Folder\Archive\" -Name
If($Archive -notin $Content ){
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.