Net view - get Just ' Share Name' - powershell

I need to get all of the shares name in some storage's.
Im using Net view $StorageName and it's show The result in a Table format :
Share name Type Used as Comment
----------------------------------------------------------------------------
Backups Disk
CallRecordings Disk
Download Disk System default share
home Disk Home
homes Disk System default share
Installs Disk
Justin Disk Copy of files from Justin laptop
michael Disk
Multimedia Disk System default share
Network Recycle Bin 1 Disk [RAID5 Disk Volume: Drive 1 2 3 4]
Public Disk System default share
Qsync Disk Qsync
Recordings Disk System default share
Sales Disk Sales Documents
SalesMechanix Disk
Server2012 Disk Windows Server 2012 Install Media
Usb Disk System default share
VMWareTemplates Disk
Web Disk System default share
The command completed successfully.
Thats good, but I need Just the Share Name.
I need Help please.
Thanke You!

Here is one way you could do it with the net view output:
(net view $StorageName | Where-Object { $_ -match '\sDisk\s' }) -replace '\s\s+', ',' | ForEach-Object{ ($_ -split ',')[0] }
Basically that is saying find the lines that have Disk surrounded by whitespace just in case something else might have Disk in the name. Then replace multiple spaces with a comma. Then, for each of those lines, split again by the comma and take the first value which would be the share name.
If you are on a Windows 8/2012 or newer system (and attempting to enumerate shares on other Windows systems), you could use a CIM session along with Get-SmbShare instead of net view which would return the results as objects and allow you to select the fields you want in the native PowerShell way.
For example:
$cimSession = New-CimSession $StorageName
Get-SmbShare -CimSession $cimSession | Select Name
Name
----
Admin
ADMIN$
C$
IPC$
J$
print$
Public
Software

Another option for parsing the net view output that relies on positioning rather than regular expression matching. personally I feel it's a bit easier to read and just as reliable.
function get-shares {
param($server)
$rawShares = net view \\$server
$shares = $rawShares[7..($s.Count - 3)]
$shares | . {process{$_.substring(0,($_.indexof(" ")))}}
}

Related

Powershell check for any SD \ CF cards (may be multiple), then copy JPG's and CR2 files to different directories

Goal: I want to automate copying files (JPG and \ or CR2) from multiple SD \ CF cards into my files into my photo storage system.
Problem: I'm more comfortable in Bash than Powershell but WSL2 doesn't yet support USB drives easily.
Question: How can I check if one or more SD \ CF cards are plugged in and check if certain folders are present? In this case, [drive]:\DCIM\100CANON. I've found this question but I can't quite get it working. Ideally, I want to be able to store the output inside a variable that I can then loop through (and run said copy routine)
The .Net namespaces...
Get-WMiObject -Class Win32_Volume | Select Name, DriveLetter, Caption, Label, DevideID, DriveType, Capacity
or
Get-CimInstance -ClassName Win32_Volume | Select Name, DriveLetter, Caption, Label, DevideID, DriveType, Capacity
or use the Win32_DiskDrive, Win32_DiskDrivePhysicalMedia, and use the Model property value.
Partitions : 1
DeviceID : \\.\PHYSICALDRIVE6
Model : SDHC Card
Size : 3964584960
Caption : SDHC Card
... and the Get-PSDrive ...
Get-PSDriive
Or
Get-PSDrive -PSProvider FileSystem
# Results
<#
Name Used (GB) Free (GB) Provider Root
---- --------- --------- -------- ----
A A:\
C 202.06 23718.91 FileSystem C:\
D 1211.06 123642.32 FileSystem D:\
G 202.06 710.91 FileSystem \\Music\GratefulDead
#>
... cmdlet will list all connected drives as shown.
Filtering drives are documented here:
Filtering get-psdrive to all Local Drives
DriveType is a property of the Win32_Volume structure which enumerates
the type of drive. The value 3 stands for Local Disk. Below is the
full list of values.
0 - Unknown
1 - No Root Directory
2 - Removable Disk
3 - Local Disk
4 - Network Drive
5 - Compact Disk
6 - RAM Disk
Note, that there is no property/option specifically for SD or CF.
So, for your use case, if your SD/CF has root labeled similar to the above, then you can get to them using the Root property value or use the drive size as your target, since in normal cases, your camera/phone, etc storage media would always be below 32GB total maximum size.

Looking for a Powershell Script to check if Volume Shadow Copy is enabled

Sorry for asking, new in PowerShell. Looking for a Powershell Script to check if Volume Shadow Copy is enabled.
Couldn't find any useful and functional script.
Where did you look?
There are a number samples of these all over the web.
For example, using the script downloadable from here:
Get Shadow Copy Statistics
If you use Shadow Copies of Shared Folders (Previous Versions), this
script may help you keep on eye on how much history you have, the
average snapshot size, whether you are hitting storage area limits or
the 64 shadow copies per volume limit.
https://gallery.technet.microsoft.com/scriptcenter/Get-Shadow-Copy-Statistics-79e05a57
You can use it's example to get stats of such items. Meaning, if you get any results, then of course it's enabled.
#Query the local machine
.\Get-ShadowCopyStats.ps1 -ServerName .
#Query a remote machine
.\Get-ShadowCopyStats.ps1 -ServerName FS01
#Query multiple remote machines by passing an array
.\Get-ShadowCopyStats.ps1 -ServerName FS01,FS02
#Since it's the first parameter, you don't have to include -ServerName in the command:
.\Get-ShadowCopyStats.ps1 FS01,FS02
#Query multiple remote machines by passing them to the script down the pipeline
"FS01","FS02" | .\Get-ShadowCopyStats.ps1
Get-ADComputer -Filter * -SearchBase "OU=Servers,DC=company,DC=tld" | .\Get-ShadowCopyStats.ps1 -ShowAllVolumes | Tee-Object -Variable ShadowCopyStats
$ShadowCopyStats | Select * | Export-Csv -NoTypeInformation .\ShadowCopyStats.csv
Or this one...
Get Remote Shadow Volume Information With Powershell
Gather the remote shadow volume information for one or more systems
using wmi, alternate credentials, and multiple runspaces. Function
supports custom timeout parameters in case of wmi problems and returns
shadow volume information, shadow copies, their providers, and
settings.
https://gallery.technet.microsoft.com/scriptcenter/Get-Remote-Shadow-Volume-e5a72619
RemoteShadowCopyInformation -ComputerName 'Server2' -Credential $cred).ShadowCopyVolumes
when the shadowcopy is enabled, there will be a scheduled task created
$allTasks = Get-ScheduledTask
foreach ($task in $allTasks) {
if ($task.TaskName.Contains("ShadowCopyVolume")) {
#get volumeid & drive letter which shadowcopy is enabled
$allVolumes = Get-Volume
foreach ($volume in $allVolumes) {
if ($volume.ObjectId.Contains(($task.TaskName.Split("{")[1]).Split("}")[0])) {
write-host ($volume.driveletter + ":\ is enabled")
}
}
}
}

How to make a powershell program restart on user input

Ok, so this is my first time posting on here and my first time writing PowerShell. My school computer maintenance and repair class requested from all the students that one of them create a PowerShell script that calculates a computers ram. The one I created calculates total physical ram, total ram usable by the user, and the modules in the computer and how much is on each module. However, after successfully coding it, I need a bit of advice as to tweaking the code so it can be use for my school.
The first part of my program opens up and talks about what each line means, follows by total physical ram, user accessible ram, and then the way the cards are set up. This leads right into a text that says to close the program. What I want to add in (I am a beginner at PowerShell by the way) is a way for the user to rerun the application if any of the variables from the program come up as zero (cause obviously the computer has ram of some sort if the computer is running). Right now its a Read-Host "Rerun memsrch ('y'/'n')?"
The other thing I want to add in is the ability for the user to select if the code is for the local computer or a distant machine. The user then could select the computer via IP or computer name. Below is the code I have now so everyone can see.
# Mesa Public Schools
$mps="Mesa Public Schools Information Technology Services"
$mps
# User Help
$print="The first section calculates your total physical memory,
the second line calculates the ram available to the user,
and the third line shows how the ram is divided up among
the ram cards.`n"
$print
#where I want to put a line of code to allow user to select if its local or remote
$ram = get-wmiobject win32_computersystem | select totalPhysicalMemory
Write-Host "Total usable RAM capacity"
$ramOutput = get-wmiobject win32_computersystem | select totalPhysicalMemory | foreach {$_.totalPhysicalMemory}
"RAM: " + "{0:N2}" -f ($ram.TotalPhysicalMemory/1GB) + "GB"
Get-WMIObject -class win32_physicalmemory | Format-Table devicelocator, capacity -a
Write-Host "Summary of System Memory"
Get-WmiObject -class Win32_PhysicalMemory | Measure-Object -Property Capacity -Sum
# Coded BY
$credits="Coded by Michael Meli"
$credits
#where I want to have the code reloop to the part of the code where
#you first select if the computer is local or remote.
Read-Host "Rerun memsrch (y/n)?"
I also have a bit of experience with HTML 4.01 and HTML 5 code, so I understand the basics of constructs and arguments, but aside from that a large part of powershell at the moment is above my head, so don't get to technical cause I don't want my brain to explode. :P Also note that the code if for computers running windows 8.1, but must be compatible with windows 7 as well. This also is not for a grade in my class either, it's extra credit.
If you wrap your code in a function, you will be able to call it again when you want. For instance, if the user input for the second question is y.
Store user input for the computer name or IP address, so you can use it in the WMI calls you make in the script, with the -ComputerName parameter
Example code:
function Show-MemoryReport {
#...
#where I want to put a line of code to allow user to select if its local or remote
#if computer name is null (first pass)
if($computerName -eq $null) {
#ask the user
$computerName = Read-Host "Enter computer name or IP, or leave blank for local"
#if the string is empty, use the local computer name
if($computerName -eq "") {
$computerName = $env:COMPUTERNAME
}
}
$ram = Get-WmiObject -ComputerName $computerName -Class Win32_Computersystem | Select-Object totalPhysicalMemory
#...
#where I want to have the code reloop to the part of the code where you first select if the computer is local or remote.
$rerun = Read-Host "Rerun report (y/n)?"
if($rerun -eq "y") { Show-MemoryReport }
}
#at first run, make sure computer name will be asked
$computerName = $null
#run report
Show-MemoryReport
After the first pass, $computerName will not be $null anymore.
Tip : you don't need to store a string in a variable to be able to output it. Just write it on a separate line like "print this on the screen" and it will be output.
For more information about PowerShell constructs and functions, you can read this and this

With PowerShell, is there a way to make an external hard disk attached to host available to VM?

I have Hyper-V module installed but don't know what cmdlet to use. I've seen blogs showing how to do this using Hyper-V Manager. I have added a VHDx disk image with following cmdlet:
Add-VMHardDiskDrive -VMName MyWin7PC -ControllerType IDE -ControllerNumber 0 `
-ControllerLocation 0 -Path "C:\Virtual Hard Disks\VDisk.MyWin7PC.Vhdx"
What I now need is a way for VM to have another drive E: which will show files and folders the host has on its G: drive (which is physically connected to a USB hard disk). I need this temporarily to install applications from the USB hard disk. You can do this using the Hyper-V Manager GUI.
I don't use Win8, so this is entirely untested. Judging from the description of Add-VMHardDiskDrive something like this might work, though:
$usbdisk = gwmi Win32_DiskDrive | ? { $_.PNPDeviceID -like 'USBSTOR\*' }
Add-VMHardDiskDrive -VMName MyWin7PC -ControllerType IDE -ControllerNumber 0 `
-ControllerLocation 1 -DiskNumber $usbdisk.Index
You have to make this disk Offliine. Try this:
"select disk 1","offline disk" | diskpart
Where 1 is your USB HD id. And then use Add-VMHardDiskDrive. If you want to do this when VM is online you must use SCSI Controller in VM.

powershell and diskpart

In short I have a volume that I need to assign a drive letter to (using diskpart). The problem now comes in that the volume does not remain the same. You enter disk part a do a "list volume" and the specific volume would be volume 0, then "exit". Enter again and the do a "list volume" again and this time it is volume 4. And so it continues.
Now if this was done by a person it would not be an issue, however this is an automated task, that will "disconnect" the volume on windows 2003 and used on other servers and mounted again on the windows 2003 server.
I'm trying to write a script in powershell that will be able to identify the volume based on a few unique field(s). The problem comes in that I'm getting stuck on interpreting the output of diskpart's "list volume" command with powershell.
The following command provides the output that I need to work with but there after I'm lost.
cls
$dp = "list volume" | diskpart | ? { $_ -match "^ [^-]" }
$dp | format-table -auto
and this is the output it provides and the volume that I'm looking for is Volume 1.
Volume ### Ltr Label Fs Type Size Status Info
Volume 0 F DVD-ROM 0 B Healthy
*Volume 1 Partition 100 GB Healthy*
Volume 2 E DATA NTFS Partition 547 GB Healthy
Volume 3 C OS NTFS Partition 39 GB Healthy System
Volume 4 D APPS NTFS Partition 98 GB Healthy
Can anybody help me in the right direction here please. I'm at my tether's end.
Yes I got it!!
Here is the answer. Using VB Script I managed to create a script that did what I was looking for, this I then translated to Powershell and below is the script.
$drive = gwmi Win32_Volume | where {$_.DeviceID -like "*b0f012f6-82b1-11df-a41c-001f29e8f0be*"}
$drive.AddMountPoint("T:\")
$drive.DriveLetter = "T:"
$drive.Put_
$drive.Mount()
The Device ID I obtained by running the following script:
# get volumes on this system
$volumes = get-wmiobject Win32_Volume
# display volume info
# There are {0} volumes on this system, as follows: " -f ($volumes.length)
# Iterate through volumes and display information
foreach ($vol in $volumes) {
"Volume: {0}" -f ++$i
"============================="
$vol | Format-List Access,Automount,Availability,BlockSize,BootVolume,Capacity,Caption,Compressed,ConfigManagerErrorCode,ConfigManagerUserConfig,CreationClassName,Description,DeviceID,DirtyBitSet,DriveLetter,DriveType,ErrorCleared,ErrorDescription,ErrorMethodology,FileSystem,FreeSpace,IndexingEnabled,InstallDate,Label,LastErrorCode,MaximumFileNameLength,Name,NumberOfBlocks,PageFilePresent,PNPDeviceID,PowerManagementCapabilities,PowerManagementSupported,Purpose,QuotasEnabled,QuotasIncomplete,QuotasRebuilding,SerialNumber,Status,StatusInfo,SupportsDiskQuotas,SupportsFileBasedCompression,SystemCreationClassName,SystemName,SystemVolume
}
from a post on msdn on the class Win32_Volume.
I hope this might help somebody else Thank you to everybody that help!
You can just use Powershell and WMI to set the drive letter. Shoudn't need diskpart unless you are doing something else (I'm unfamiliar with that tool)
So (assuming you are trying to set the drive letter of the one volume that doesn't have a letter) this should work:
$drive = gwmi Win32_Volume | where {$_.DriveLetter -eq ""}
$drive.DriveLetter = "X:"
$drive.Put()
If you aren't sure about the drive, just query it first and make sure you are only getting the one you want:
gwmi Win32_Volume | where {$_.DriveLetter -eq ""}
Yep. This is a "feature" of diskpart.
Suggestions from MS (not very useful in your case)
Keep the Disk Management console
(Diskmgmt.msc) running while you
process scripts. Or, keep an instance
of the Diskpart.exe utility running
in the background while you process
scripts. When you do this, the volume
numbers should not change between
instances of the Diskpart.exe
utility. Use the volume Label
information instead of the volume
number to track particular volumes.
See bug report here.