如何使用变量或函数来记住 Powershell 提示中的输入?
我需要将文件从一个文件夹移动到另一个文件夹。我需要能够选择要移动的文件数量,然后循环直到源文件夹中没有更多文件。在循环之间,需要休息一下。我可能还差得远 到目前为止,我得到了这样的脚本:
$FileCount = (ls $env:C:\users\jenstmar\desktop\*.*).count
Function Source {gci -path (Read-Host -Prompt 'Set Source') -exclude PowerFlyt |}
Function FileNumber {Get-Random -Count 4 (Read-Host -Prompt 'Set number of files to move a time') |}
Function Destination {mi -Destination (Read-Host -Prompt 'Set Destination') -exclude PowerFlyt.ps1 |}
do
{
Source |
FileNumber |
Destination |
sleep -sec 20; .\PowerFlyt.ps1
}
while($FileCount -gt 0)
提前致谢
I need to move files from one folder to another. I need to be able to choose how many files that shall be moved, and then it shall loop until it there's no more files in the source folder. Between the loops, it needs to take a break. I might be way off.
So far I got a script like this:
$FileCount = (ls $env:C:\users\jenstmar\desktop\*.*).count
Function Source {gci -path (Read-Host -Prompt 'Set Source') -exclude PowerFlyt |}
Function FileNumber {Get-Random -Count 4 (Read-Host -Prompt 'Set number of files to move a time') |}
Function Destination {mi -Destination (Read-Host -Prompt 'Set Destination') -exclude PowerFlyt.ps1 |}
do
{
Source |
FileNumber |
Destination |
sleep -sec 20; .\PowerFlyt.ps1
}
while($FileCount -gt 0)
Thanks in advance
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
首先,函数不像宏或代码中内联的东西。函数被调用并将值返回到管道。
因此,您的用法
和定义类似
Function Source {gci -path (Read-Host -Prompt 'Set Source') -exclude PowerFlyt |}
的函数将不起作用。更改不带尾随管道 (
|
) 的函数。要从 read-host 传递变量,请将读取的值保存在变量中:
您现在可以在脚本中的其他函数中访问
$script:source
。对任何其他变量执行相同的操作。First of all, functions are not like macros or something which are inlined in the code. Functions are called and they return valued to the pipeline.
So your usage like
and defining functions like
Function Source {gci -path (Read-Host -Prompt 'Set Source') -exclude PowerFlyt |}
will not work. Change the functions without those trailing pipes (
|
).To pass the variable from read-host, save the read values in variables:
You can now access
$script:source
in other functions in the script. Do the same for any other variable.我想通了。最终结果是这样的:
感谢您的帮助和时间。
I figured it out. The end result was like this:
Thanks for your help and time.