代码之家  ›  专栏  ›  技术社区  ›  websch01ar

使用带有凭据的删除项

  •  3
  • websch01ar  · 技术社区  · 15 年前

    下面的代码将构建PSCredential对象:

    $password = New-Object System.Security.SecureString
    "passwordhere".ToCharArray() | ForEach-Object { $password.AppendChar($_) }
    $cred = New-Object System.Management.Automation.PSCredential("domain\username",$password)
    $cred
    

    Remove-Item -LiteralPath $path -Force -Credential $cred
    

    有什么想法吗?

    2 回复  |  直到 15 年前
        1
  •  6
  •   Keith Hill    15 年前

    我不清楚这些文件是本地的(您在服务器上运行脚本)还是远程的(在另一台机器上)。如果本地用户尝试使用后台作业运行命令,并传入凭据以启动作业:

    $job = Start-Job { Remove-Item -LiteralPath $path -force } -cred $cred 
    Wait-Job $job
    Receive-Job $job
    

    如果它们是远程的,请尝试使用远程处理:

    Invoke-Command -computername servername `
                   -scriptblock { Remove-Item -LiteralPath $path -force } `
                   -Cred $cred
    

    注意:这要求您在远程计算机上执行Enable PSRemoting。

    一般来说,在脚本中输入原始密码不是一个好主意。您可以使用DPAPI以加密的方式存储密码,以后,只有该用户帐户才能解密密码,例如:

    # Stick password into DPAPI storage once - accessible only by current user 
    Add-Type -assembly System.Security 
    $passwordBytes = [System.Text.Encoding]::Unicode.GetBytes("Open Sesame") 
    $entropy = [byte[]](1,2,3,4,5) 
    $encrytpedData = [System.Security.Cryptography.ProtectedData]::Protect( ` 
                           $passwordBytes, $entropy, 'CurrentUser') 
    $encrytpedData | Set-Content -enc byte .\password.bin 
    
    # Retrieve and decrypted password 
    $encrytpedData = Get-Content -enc byte .\password.bin 
    $unencrytpedData = [System.Security.Cryptography.ProtectedData]::Unprotect( ` 
                           $encrytpedData, $entropy, 'CurrentUser') 
    $password = [System.Text.Encoding]::Unicode.GetString($unencrytpedData) 
    $password 
    
        2
  •  0
  •   Underverse    8 年前

    删除项目可能因授权而失败。或者,找到每个文件的引用并用.Delete()点击它,或者将所有文件移动到回收站。

    foreach ($svr in $computers) 
    {
        Invoke-Command -ComputerName $svr { 
    
        $folderitems = Get-ChildItem $cachefolder -Recurse
    
        # Method 1: .Delete
        foreach ($cachefolderitem in $cachefolderitems)
        {
            if ($cachefolderitem -like "*.ini")
            {
                $cachefolderitem.Delete()
            }
        }
    
       # Method 2: Move all matching files to the recycle bin
       Move-Item "$cachefolder\*.ini" 'C:\$Recycle.Bin' -Force 
    }