2017-08-23 51 views
1

我試圖運行Powershell腳本,該腳本僅在.txt文件的文件內容與不同文件夾中的文件夾名稱匹配時才運行。我不知道我是否過於複雜的腳本,但任何幫助將不勝感激。當文件內容與文件夾名稱不匹配時運行powershell腳本

$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 
} 
+0

因此,如果文件內容引用文件夾中的文件本身不在,那麼一定要發生什麼?你有文件樣本嗎?我在腳本中看不到任何邏輯? – Matt

+0

@Matt是的。如果文件內容不等於另一個結構中的文件夾名稱,它應該運行代碼。 'Get-ChildItem $ from -recurse |複製項目目標$到 #gets文件內容 '$ Text = Get-Content -path'c:\ test folder \ archive \ new \ content.txt'' #rewrites item 'Rename-item - 路徑'C:\測試文件夾\檔案\新'-NewName $文字 }' – Isaac

+0

我想我現在變得更好了。腳本有什麼問題?我可以看到這是一個問題'如果($ Archive -notin $ Content)' – Matt

回答

0

Get-Content | Out-String將輸出一個字符串的對象而不是一個字符串數組。

例有3條線路的文本文件:

(Get-Content -path Example.txt | Out-String).count 
1 
(Get-Content -path Example.txt).count 
3 

這意味着,當你做磁盤陣列上的文本文件,使用Out-String-in/-contains,基本上是做-eq後的比較。

正如馬特在評論中所建議的,您可以使用通配符或正則表達式運算符來查找較大字符串內的名稱。

$Content = Get-Content -path "c:\Test Folder\Content\content.txt" -Raw 
$Archive = Get-ChildItem -path "c:\Test Folder\Archive\" -Name 

If($Content -notmatch $Archive){ 

或者,假設檔案名稱是文件中的一行。您可以擺脫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){ 
相關問題