繁体   English   中英

如何使用PowerShell动态创建文件夹?

[英]How to create folders dynamically using PowerShell?

要求:我正在尝试使用下面的代码在10个服务器中创建BKP文件夹,但是有些方法却没有在服务器中创建新文件夹。

foreach ($instance in Get-Content "C:\servers\List.txt")
{
    $local = Get-Location;
    $final_local = "C:\BKP";

    if (!$local.Equals("C:\"))
    {
        cd "C:\";
        if ((Test-Path $final_local) -eq 0)
        {
            mkdir $final_local;
            cd $final_local;
        }

        ## if path already exists
        ## DB Connect
    }
}

首先 :您使用了错误的测试,应该使用:

if($local.Path -eq "C:\")

equal方法是比较对象的一种方法:

$local | get-member
$local | fl *

注意PowerShell CmdLet返回对象

第二 :如果$local.Path等于"C:\\"$local.Path创建任何内容。


您的代码如下所示:

ForEach ($instance in $(Get-Content "C:\servers\List.txt")) 
{ 
  $local = Get-Location;
  $final_local = "C:\BKP";

  if($local.Path -ne "C:\")
  {
    cd "C:\";
    if((Test-Path $final_local) -eq 0)
    {
      mkdir $final_local;
      cd $final_local;
    }

    ## if path already exists
    ## DB Connect
}

使用此命令创建目录:

ForEach ($instance in Get-Content "C:\servers\List.txt") 

{ 
$local = Get-Location;
$final_local = "C:\BKP";

if(!$local.Equals("C:\"))
{
    cd "C:\";
    if((Test-Path $final_local) -eq 0)
    {
        New-Item -ItemType Directory -Force -Path "$final_local";
        cd $final_local;

    }

    ## if path already exists
    ## DB Connect

}

} 

尝试使用invoke-command,我假设服务器需要凭据,如果对您有用,则可以跳过它。

$credentials = Get-Credential

$create = { $local = Get-Location;
            $final_local = "C:\BKP"

             if(!$local.Equals("C:\")){
                cd "C:\";
                 if((Test-Path $final_local) -eq 0){
                      New-Item -ItemType Directory -Force -Path "$final_local";
                      cd $final_local;
               }
         ## if path already exists
           ## DB Connect
     }
 }
ForEach ($instance in Get-Content "C:\servers\List.txt")  {
Invoke-Command -ScriptBlock $create -ComputerName $instance -Credential $credentials
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM