powershell 使用foreach编写在多个驱动器上创建文件的脚本

vxbzzdmp  于 2023-01-26  发布在  Shell
关注(0)|答案(2)|浏览(103)

我尝试编写脚本,在所有不包含sccm的驱动器上自动创建名为no_sms_on_drive.sms的文件,在本例中为j:。当它启动Foreach循环时,我可以获得$dltr变量集,但我收到一个错误,指出-Path具有空值。

##Define no_sms_on_drive.sms on all drives except j:\
### Get all the logical disks with drivetype 3 which is a hard drives
$disks = gwmi win32_logicaldisk -Filter "DriveType='3'"
### Filter out j:\ which contains SCCM 
$NonSMSDrives = $disks | ? { $_.DeviceID -notmatch "[j]:"}
### Create the no sms file on each of the drives
$MakeNonSMSDrives = ForEach($d in $NonSMSDrives){ $dltr = $_.DeviceID | New-Item -Path $dltr -Name "no_sms_on_drive.sms" -ItemType "File" }
jobtbby3

jobtbby31#

Get-WmiObject已经过时了。你应该使用Get-CimInstance。因为你以后不需要这些变量了,我建议你不用它们。

Get-CimInstance -ClassName CIM_LogicalDisk |
    Where-Object {
        $_.DriveType -eq 3 -and
        $_.DeviceID -notmatch 'j'
    } |
        ForEach-Object {
            $Path = Join-Path -Path $_.DeviceID -ChildPath 'no_sms_on_drive.sms'
            New-Item -Path $Path -ItemType 'File' -WhatIf
        }

如果您对输出感到满意,则可以删除-WhatIf参数以实际创建所需的文件。

fcg9iug3

fcg9iug32#

我可以通过使用以下代码来实现此功能

$NonSMSDrives = "Get-PSDrive -PSProvider FileSystem | ? { $_.Name -notlike [jdX]} | Select -ExpandProperty Root"

$MakeNonSMSDrives = "ForEach( $d in $NonSMSDrives){ New-Item -Path $d -Name 'no_sms_on_drive.sms' -ItemType 'File' }"

相关问题