我的Powershell脚本没有太多运气,所以任何帮助都会很棒!我尝试做的是从包含用户名行的测试文件中引用,并将其与A1列上的Excel电子表格进行比较。如果存在,则应该删除用户名。
$users = Get-Content "E:\temp\test.txt"
foreach ($user in $users) {
set-aduser $user -fax " "
$answer1 = read-host "Please Make a Selection"
if ($answer1 -eq 1){
$location="Melbourne"
}
if ($answer1 -eq 2){
$location="Sydney"
}
if ($answer1 -eq 3){
$location="Adelaide"
}
if ($answer1 -eq 4){
$location="Brisbane"
}
if ($answer1 -eq 5){
$location="Perth"
}
$ExcelPath = 'E:\temp\FX MFD UserPIN.xlsx'
$Excel = New-Object -ComObject Excel.Application
$Excel.Visible = $true
$ExcelWorkBook = $Excel.Workbooks.Open($ExcelPath)
$ExcelWorkSheet = $Excel.WorkSheets.item("$location")
$Range = $ExcelWorkSheet.Range("A1").EntireColumn
$Search = $Range.find($user)
If($Search.value() -contains $user)
{
Write-Host "User FOUND, removing now"
$Search.value() = ""
}
else {
Write-Host "User NOT FOUND"
}
}
错误代码是这样的:
You cannot call a method on a null-valued expression.
At E:\temp\testsest.ps1:35 char:12
+ If($Search.value() -contains $SearchString)
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [], RuntimeException
+ FullyQualifiedErrorId : InvokeMethodOnNull
如何更换 $ Search 以获取 $ user ?
答案 0 :(得分:3)
Range.Find()
returns Nothing if no match is found.
因此,在检查是否匹配之前,您必须检查$Search
中是否存在空值。
if ($Search -ne $null) {
if ($Search.value -contains $user)
{
Write-Host "User FOUND, removing now"
$Search.value = ""
}
else {
Write-Host $Search.value," what did we find?!"
}
}
else {
Write-Host "User NOT FOUND"
}
另外,value
不是方法,它是属性,所以不要使用圆括号。
答案 1 :(得分:0)
谢谢Vesper。我做了一些更改,可以确认它现在有效。
if ($Search -ne $null) {
if ($Search.text -contains $user)
{
Write-Host "User FOUND, removing now"
$Range.replace($Search,"")
}
else {
Write-Host $Search.text," what did we find?!"
}
}
else {
Write-Host "User NOT FOUND"
}