我正在处理一个在另一台服务器上使用 get-childitem 的脚本,但需要更改它以便它使用另一台服务器上本地帐户的凭据来执行此操作。当我只是使用 Active Directory 来执行此操作时,我使用我的 AD 登录名将任务保存在我们的调度程序中,它在另一台服务器上使用 UNC 路径很好。但我们最近决定将其更改为本地登录,但我收到一条错误消息,试图使用 net use。有谁知道使用 UNC 路径执行此操作的好方法吗?或者,知道为什么以下内容会给出错误消息吗?
function GetSecureLogin(){
$global:username = "stuff"
$global:password = get-content C:\filename.txt | convertto-securestring
}
function Cleanup([string]$Drive) {
try {
$deleteTime = -42
$now = Get-Date
**#this is saying cannot find path '\\name.na.xxx.net\20xServerBackup\V' name truncated**
Get-ChildItem -Path $Drive -Recurse -Force |Where-Object {$_.LastWriteTime -lt $limit} | Remove-Item -Force
}
Catch{
Write-Host "Failed"
}
}
#####################start of script####################
$share = '\\name.na.xxx.net\20xServerBackup\'
$TheDrive = '\\name.na.xxx.net\20xServerBackup\VMs\'
$global:password = ""
$global:username = ""
GetSecureLogin
net use $share $global:password /USER:$global:username
[array]$DriveArray = @(TheDrive)
try{
$i=0
for ($i = $DriveArray.GetLowerBound(0); $i -le $DriveArray.GetUpperBound(); $i++) {
$tempDrv = $DriveArray[$i]
Cleanup $tempDrv
}
}
catch [Exception] {
Write-Host $_.Exception.Message
}
如您所见,我开始使用此链接中的示例和 net use,但使用凭据访问其他服务器并没有达到目的。 powershell unc 路径信用
我按照@robert.westerlund 在上面建议的那样使用 New-PSDrive 以这种方式工作:
$DestPath = split-path "$Drive" -Parent #this gives format without slash at and and makes powerShell *very happy*
New-PSDrive -Name target -PSProvider FileSystem -Credential $global:cred -Root "$DestPath" | Out-Null
$temp1 = Get-ChildItem -Path target:\VMs\ -Recurse -Force | Where-Object { $_.LastWriteTime -lt $limit}
Get-ChildItem -Path $Drive -Recurse -Force | Where-Object { $_.LastWriteTime -lt $limit} | Remove-Item -Force
Remove-PSDrive target
我也必须像这样添加 cred 部分:
$global:cred = new-object -typename System.Management.Automation.PSCredential -argumentlist $global:username, $global:password
这个答案晚了大约 9 年,但我遇到了同样的问题,命令 [get-childitem] 缺少用于远程执行的 -Credential 参数。我正在使用 PowerShell 7.3.1,但我相信如果碰巧你仍然停留在过去,这个变通解决方案将使用 PowerShell 2.0/3.0 工作!
描述:捕获日期并使用 AddDays 方法来控制您要捕获或执行的时间范围。使用 Invoke-command 使用指定的凭据和脚本块远程访问计算机以在本地执行所需的命令。此示例仅显示满足条件的文件,但可以更新以删除它们。
invoke-command -ComputerName $computer -Credential $creds -ScriptBlock {
$date = get-date
$files = get-childitem c:\temp -Recurse
$newfiles = $files | where-object {$date.AddDays(-7) -lt $_.LastWriteTime}
foreach ($file in $newfiles){
write-host "$($file.Name) LastWriteTime: $($file.LastWriteTime)"
}
}