请帮帮我。我正在尝试使用do-while循环创建PowerShell脚本,如下所示:
我的代码如下:
$var = "welcome to IP address and folder creation world"
echo $var
# create foldername until user type "quit"
$output = (command)
do {
$foldername = Read-Host "enter folder name "
$targetipaddress = Read-Host "enter target ip address "
# create folder name only if it does not exist
function createFolder {
$path = "\\$targetipaddress\C$\$foldername "
If (!(Test-Path $path))
{
New-Item -ItemType Directory -Force $path
}
} # end of function createFolder
# copy contents from a sub folder of a network drive path and
# and paste them onto "C:\" drive path using "targetipaddress" and "foldername"
function copyContents {
Copy-Item S:\sourcefolder\subfolder\*.* \\$targetipaddress\C$\$foldername\ -Recurse
}
} while ($foldername = "quit") # end of do-while loop
答案 0 :(得分:1)
请参阅下面的工作示例,仔细阅读并将其与您自己的相比较。
一些问题/变化。
如果您在使用此代码时出错,请发送输入voor $ source,$ foldername,$ targetipaddress和$ path,我会查看它。
代码:
clear-host #clears your console, optional.
$ErrorActionPreference = "Stop" #prevents al lot of posible disasters from happening.
Write-Host "welcome to IP address and folder creation world" #Powershell way of writing to the console.
$source = "S:\sourcefolder\subfolder\*"
#$source = "C:\source\*" i used this for testing on my local machine.
# create foldername until user type "quit"
While ($true){
"
"#Add some white space between the questions.
$foldername = Read-Host "enter folder name "
If ($foldername -eq "quit") {break} #exit the while loop
$targetipaddress = Read-Host "enter target ip address " #you could use a hostname to.
$path = "\\$targetipaddress\C$\$foldername"
#if connection to targetipaddress fails then abort.
if(!(Test-Connection $targetipaddress -ErrorAction SilentlyContinue)) #look at the ! it means it should be false.
{
Write-Warning "Could not connect to '$targetipaddress'"
continue #goes back to the begining of the while loop.
}
#if path does not exist try to create it.
if(!(Test-Path $path)) #look at the ! it means it should be false.
{
try { New-Item -ItemType Directory -Path (Split-Path -Parent $path) -Name $foldername | Out-null } #Out-null prevenst unwanted console output.
catch {
Write-Warning "Could not create folder '$foldername' on '$targetipaddress'"
continue #goes back to the begining of the while loop.
}
}
#try to copy files.
try { Copy-Item -Path $source -Destination $path -Recurse -Force }
catch {
Write-Warning "An Error occured while copying the files from '$source' to '$path'"
continue #goes back to the begining of the while loop.
}
#if all goes well then tell them ;)
Write-Host "files copied successfully from $source to $path"
}