Our software needs to map a network drive depending on which database the User logs in to.
The software first checks that the drive isn't already mapped, if it is then it skips the mapping step.
If the drive isn't mapped, or it is mapped to a different share (i.e. the User was previously logged in to a different database), then it clears any existing drive mapping, and maps the required drive.
It does this by generating and then running a PowerShell script.
Remove-SmbMapping -LocalPath "R:" -Force -UpdateProfile;
Remove-PSDrive -Name "R" -Force;
net use "R" /delete /y;
$password = ConvertTo-SecureString -String "Password" -AsPlainText -Force;
$credential = New-Object System.Management.Automation.PSCredential -ArgumentList "Username", $password;
New-PSDrive -Name "R" -PSProvider "FileSystem" -Root "\\server\share" -Credential $credential -Persist;
$a = New-Object -ComObject shell.application;
$a.NameSpace( "R:" ).self.name = "FriendlyName";
The first three lines remove any existing mapping on that drive letter. They all theoretically do the same thing, however thanks to Microsoft it's entirely random which line will actually work. It only consistently works if all three lines are run.
The middle three lines map the new drive.
The last two lines change the drive label of the new drive to something more user-friendly than the default \\server\share label
The first time someone logs in after a reboot the above script works perfectly. The new drive is mapped, and the label is changed.
However, if the User then logs out and logs into a different database, the label will not change.
For example, the User first logs in to 'Database A', and the drive is mapped with the label 'DatabaseAFiles'. All well and good.
But if the User then logs out, and logs in to 'Database B', the drive is correctly mapped and points to the correct share, but the label still says 'DatabaseAFiles' and not 'DatabaseBFiles'.
If the User reboots their PC, however, and logs in to 'Database B', then the label will correctly say 'DatabaseBFiles', but any subsequent log ins to other databases again won't change the label.
Reboot
Log in to Database A, label is DatabaseAFiles
Log out and into Database B, label is still DatabaseAFiles
Reboot
Log in to Database B, label is now DatabaseBFiles
This is not dependent on the last two script lines being present (the two that set the label), I actually added those to try to fix this issue. If those two lines are removed, the label is the default \\server\share label, and still doesn't change correctly, i.e.
Reboot
Log in to Database A, label is \\servera\sharea
Log out and into Database B, label is still \\servera\sharea
Reboot
Log in to Database B, label is now \\serverb\shareb
Regardless of the label, the drive is always correctly mapped to the correct share, and using it has all the correct directories and files.
Everything works correctly, it's just the label that is incorrect after the first login per reboot.
The script is run from within a C# program in a created PowerShell instance
using (PowerShell PowerShellInstance = PowerShell.Create())
{
PowerShellInstance.AddScript(script);
IAsyncResult result = PowerShellInstance.BeginInvoke();
while (result.IsCompleted == false)
{
Thread.Sleep(1000);
}
}
As it maps a drive, it cannot be run in Adminstrator mode (the drive won't be mapped for the actual User), it has to be run in normal mode, so there is a check earlier up for that.
If I take a copy of the script and run it in a PowerShell session outside the C# program, I get exactly the same results (everything works but the label is wrong after the first login), so it's not that it's being run from within the C# program.
It's entirely possible that the issue is with either File Explorer or with Windows, either caching the label somewhere and reusing it could be the problem, of course.
Anyone have any suggestions of things I can try please?
A time ago, I have had to rename file shares and therefor I wrote this function. Maybe this is helpful for you.
#--------------------------------------
function Rename-NetworkShare {
#--------------------------------------
param(
[string]$sharePattern,
[string]$value
)
$regPath = Get-ChildItem 'HKCU:\Software\Microsoft\Windows\CurrentVersion\Explorer\MountPoints2'
$propertyName = '_LabelFromReg'
foreach( $child in $regPath ) {
if( $child.PSChildName -like ('*' + $sharePattern + '*') ) {
if( !$child.Property.Contains( $propertyName ) ) {
New-ItemProperty $child.PSPath -Name $propertyName -PropertyType String | Out-Null
}
Set-ItemProperty -Path $child.PSPath -Name $propertyName -Value $value | Out-Null
}
}
}
Rename-NetworkShare -sharePattern 'patternOldName' -value 'NewFriendlyName'
It's not ideal, there's one bit I'm not happy about, but this is the best I've been able to come up with so far. If I come up with something better I'll post that instead.
Firstly, I check if there is already a drive mapped to the letter I want to use:-
// Test if mapping already exists for this database
var wrongMapping = false;
var drives = DriveInfo.GetDrives();
foreach (var drive in drives)
{
var driveLetter = drive.RootDirectory.ToString().Substring(0, 1);
if (driveLetter == mappingDetails.DriveLetter && Directory.Exists(drive.Name))
{
wrongMapping = true; // Assume this is the wrong drive, if not we'll return from the method before it's used anyway
var unc = "Unknown";
using (RegistryKey key = Registry.CurrentUser.OpenSubKey("Network\\" + driveLetter))
{
if (key != null)
{
unc = key.GetValue("RemotePath").ToString();
}
}
if (unc == mappingDetails.Root)
{
View.Status = #"Drive already mapped to " + mappingDetails.DriveLetter + ":";
ASyncDelay(2000, () => View.Close());
return; // Already mapped, carry on with login
}
}
}
If we already have the correct path mapped to the correct drive letter, then we return and skip the rest of the mapping code.
If not, we'll have the variable wrongMapping, which will be true if we have a different path mapped to the drive letter we want. This means that we'll need to unmap that drive first.
This is done via a Powershell script run the by C# program, and contains the bit I'm not happy about:-
Remove-PSDrive mappingDetails.DriveLetter;
Remove-SmbMapping -LocalPath "mappingDetails.DriveLetter:" -Force -UpdateProfile;
Remove-PSDrive -Name "mappingDetails.DriveLetter" -Force;
net use mappingDetails.DriveLetter /delete /y;
Stop-Process -ProcessName explorer;
The first four lines are different ways to unmap a drive, and at least one of them will work. Which one does work seems to be random, but between all four the drives (so far) always get unmapped.
Then we get this bit:
Stop-Process -ProcessName explorer;
This will close and restart the Explorer process, thus forcing Windows to admit that the drive we just unmapped is really gone. Without this, Windows won't fully release the drive, and most annoyingly it will remember the drive label and apply it to the next drive mapped (thus making a mapping to CompanyBShare still say CompanyAShare).
However, in so doing it will close any open File Explorer windows, and also briefly blank the taskbar, which is not good.
But, given that currently no Company sites have more than one share, and it's only the Developers and Support that need to remove existing drives and map new ones, for now we'll put up with it.
Once any old drive is unmapped, we then carry on and map the new drive, which again is done via a PowerShell script run from the C# code.
$password = ConvertTo-SecureString -String "mappingDetails.Password" -AsPlainText -Force;
$credential = New-Object System.Management.Automation.PSCredential -ArgumentList "mappingDetails.Username", $password;
New-PSDrive -Name "mappingDetails.DriveLetter" -PSProvider "FileSystem" -Root "mappingDetails.Root" -Credential $credential -Persist;
$sh=New_Object -com Shell.Application;
$sh.NameSpace('mappingDetails.DriveLetter:').Self.Name = 'friendlyName';
New-Item –Path "HKCU:\Software\Microsoft\Windows\CurrentVersion\Explorer\MountPoints2\" –Name "foldername";
Remove-ItemProperty -Path "HKCU:\Software\Microsoft\Windows\CurrentVersion\Explorer\MountPoints2\foldername" -Name "_LabelFromReg";
New-ItemProperty -Path "HKCU:\Software\Microsoft\Windows\CurrentVersion\Explorer\MountPoints2\foldername" -Name "_LabelFromReg" -Value "friendlyName" -PropertyType "String\";
The first part maps the drive:
$password = ConvertTo-SecureString -String "mappingDetails.Password" -AsPlainText -Force;
$credential = New-Object System.Management.Automation.PSCredential -ArgumentList "mappingDetails.Username", $password;
New-PSDrive -Name "mappingDetails.DriveLetter" -PSProvider "FileSystem" -Root "mappingDetails.Root" -Credential $credential -Persist;
The middle part changes the name directly:
$sh=New_Object -com Shell.Application;
$sh.NameSpace('mappingDetails.DriveLetter:').Self.Name = 'friendlyName';
And the end part changes the name in the Registry:
New-Item –Path "HKCU:\Software\Microsoft\Windows\CurrentVersion\Explorer\MountPoints2\" –Name "foldername";
Remove-ItemProperty -Path "HKCU:\Software\Microsoft\Windows\CurrentVersion\Explorer\MountPoints2\foldername" -Name "_LabelFromReg";
New-ItemProperty -Path "HKCU:\Software\Microsoft\Windows\CurrentVersion\Explorer\MountPoints2\foldername" -Name "_LabelFromReg" -Value "friendlyName" -PropertyType "String\";
Firstly, it creates a key for this path (it the key already exists it'll fail but the script will carry on)
Then it removes the existing property _LabelFromReg (if it doesn't exist it'll fail but the script will carry on)
Then it (re)creates the property _LabelFromReg with the new friendlyname.
So, again doing the same thing two ways, but between the two it works.
I'd like to find some alternative to having to kill and restart the Explorer process, it's really tacky, but it seems to be the only way to get Windows to acknowledge the changes.
And at least I now get the correct labels on the drives when mapped.
Related
I built this open-file function in PowerShell for a GUI I wrote that lets you find and open various files on a server. I mainly use it for opening SolidWorks files as read-only, but also for PDF files and it should work for just about any other file if there is a file association for it.
The problem is that sometimes it doesn't work when opening the sldprt files. SolidWorks will either ignore the open file request or it wont open as read-only. I think this is mostly just a solidworks issue as sometimes it wont open files when double clicked on from windows explorer.
Anyway my solution is to set the file attribute to read-only. start a job that opens the file in SolidWorks, and then waits for the SolidWorks process to go idle before removing the read-only attribute. It does this through an event that watches for the job state to change. Since this is running through a GUI it has to be done in the background to prevent the GUI from locking up.
Is there a simpler way to open files as read-only with PowerShell?
I think it might be possible using the SolidWorks .dll files, but they are meant to be loaded in C# or VB-script and I have no idea what i'm doing in either of those languages.
function open-File{
param(
[parameter(Mandatory=$true)]$file,
[bool]$readOnly = $true,
$processName=$null
)
[scriptblock]$openFileScriptBlock = {
param(
$file,
$readOnly,
$processName=$null
)
#initiate variables
$loaded = $false
$file = get-item $file
$processLastCpu = 0
$timeout = 0
if ($readonly -and !$file.isReadOnly){
$file.isReadOnly = $true
#call file with default application
$attempts = 0
while ($true){
try{$startedProcess = start-process "$($file.fullname)" -PassThru; break}
catch{
$attempts++
if ($attempts -eq 3){return "cannot open file: $file, Error:$_"}
}
}
start-sleep -seconds 2
if ($processName){
$processName = $startedProcess.name
if ($processName -eq "SWSHEL~1"){$processName = "SLDWORKS"}
}
#wait until process shows up in the process manager
while ($loaded -eq $false -and $timeout -lt 25 ){
try {
$process = get-process -name $processName -erroraction 'stop'
if ($?){$loaded = $true; $timeout = 0} else {throw}
}catch{start-sleep -milliseconds 200; $timeout++}
}
start-sleep -seconds 2
#wait for process to go idle
while ($process.cpu -ne $processLastCpu -and $timeout -lt 10){
$processLastCpu = $process.cpu
start-sleep -milliseconds 500
$timeout++
}
$file.isreadonly = $false
} else {start-process "$($file.fullname)"}
return ,$file
}
if (!(test-path -path $file)){update-message "File not found: $file"; return}
$openFileJob = start-job -name 'openfile' -scriptblock $openFileScriptBlock -argumentlist $file, $readOnly, $processName
Register-ObjectEvent $OpenFileJob StateChanged -Action {
$jobResult = $sender | receive-job
$sender | remove-job -Force
unregister-event -sourceIdentifier $event.sourceIdentifier
remove-job -name $event.sourceIdentifier -force
try{update-message "opened file $($jobResult.name)"}
catch{update-message $jobResult}
} | out-null
}
I know its a old question, but i was wondering if you ever managed to get a solution?
If not, there is a few things you could try: first off, if your code is opening any other file just fine, it does not seem to be there the problem is.
File association with all SLD-files are working most of the time; but we do see it going bad from time to time (often related to updates), in that case, double-check that all SLD-file types are set to open with 'Solidworks-Launcher' (and not Solidworks directly).
Using the launcher, will ensure Solidworks does not try to open a file, into an already running instance of Solidworks.
Also, try to check the following: Solidworks Options -> Collaboration ->
'Enable Multi-user environments'... is this set?
whatever state it is in; try changing is to the opposite.
That checkmark is allowing multiple Solidworks-users to open the same file at the same time, and it does so by changing the read-state of the file, back and fourth.
(it could be it is interfering with your code)
Both of these things will be PC-specific, so if you change them on one machine, they might also need to be changed on other machines.
I am in security and want to consume a massive password dump file (3GB) as part of my usual password audits
The file is delimited into two columns, SHA1, and the actual password
For my purposes, because Windows stores password as NTLM hashes at rest (Kerberos only used during transport) I need passwords in NTLM, not SHA1. (You can easily prove it to yourself by doing a password dump, I use DSInternals)
I am currently converting clear-text passwords to NTLM with this script
#Install-Module DSInternals
Import-Module DSInternals
$reader = [System.IO.File]::OpenText("C:\...\68_linkedin_found_hash_plain.txt")
try {
for() {
$line = $reader.ReadLine()
if ($line -eq $null) { break }
$pwd = ConvertTo-SecureString $line.Split(':')[1] -AsPlainText -Force
$hash = ConvertTo-NTHash $pwd;
Add-Content C:\...\68_linkedin_ntlm.txt $hash
}
}
finally {
$reader.Close()
}
Any obvious way of processing this faster? I suppose I can ingest into a DB and process it threaded via a little C# app but maybe there's something quick and dirty?
The file format is (no these are not my passwords, these are passwords from a common password dump file that is publicly available)
8c9fcfbf9ead0d63d04b5d3120c42cb885af899e:16piret
8c9fd045ee531744a4fdc1f52e59c3878e742ee0:louie310
8c9fd070274a0eebecf58f8f50e283bf53cec215:kery62
8c9fd08d1c17266f7c1e42a3f16a1161613c7572:sa81nt
8c9fd1093bd8592bbaea195785f8d1c81589073f:cuchilleros
8c9fd1a963bbf44ea9b531e91e5cb1b591c454cc:198962914685590
8c9fd1d8cc6d4fa8164a2fcb3adc7a45f3409547:sculp1011
8c9fd20540d66831f6f65a39ce1bca0e654fd5e6:ume1431965
8c9fd2b4a9571db21c4226bf9ecaea282ecadd5e:534015629819772
8c9fd2f3e63c20314cc962b624178ba82c6674a7:siegenthaler
8c9fd3713fe9600d2bea05b4e8cd33efe12bddb1:mkenrick
8c9fd3a39cca8fb8cdeeb52999aed7e6e9435fd3:billscot
8c9fd3b96ee1485e0fd7d6c71ffe3efd2e8a4614:ndiyehova
8c9fd43aef9804dab6e0aebc58415543175fea00:662566123
8c9fd481cf8f35edb6ebd683fffb0efce0478f21:371874conv
8c9fd4f37632294093fb057eb0168a05d9396e74:h3aww7w
8c9fd53dce9b046f73c5f298e2f694213f8f90f1:squishy23
8c9fd55206e0525d119f4946d3ae75e347cccb4b:NEH3112
8c9fd555303ac08f9103ff8451f8c05cf48cf120:marco22580
8c9fd5c6a94b1171518d0ba264033d779a075e8c:Nowornever2010
8c9fd613fb632b5bc6ae20a671aa40decdb8609a:MKSmks1976##
8c9fd627a48f9971df5bee874501156e9d3c011d:Steripro5
TIA
EDIT:
By reading into memory and writing to separate files speed up the process a bit. Also used suggestion from TessellatingHeckler
Import-Module DSInternals
$lines = [System.IO.File]::ReadAllLines('C:\...\68_linkedin_found_hash_plain.txt')
foreach($line in $lines) {
try {
$password = $line.Substring($line.IndexOf(':')+1);
if ($password.Length -lt 128)
{
$pwd = ConvertTo-SecureString $line.Substring($line.IndexOf(':')+1) -AsPlainText -Force
$hash = ConvertTo-NTHash $pwd;
Set-Content C:\Temp\Hashes\$hash.txt $hash
}
}
finally {
}
}
The afterwards I can combine the files with
copy *.txt combined.log
If those are typical line lengths, and your file is 3GB, we're talking 50-60 million lines.
Change $line.Split(':')[1] to $line.Substring($line.IndexOf(':')+1), that will save creating and cleaning up 50 million arrays and 50 million strings of the bit you don't want. (Is that right? Your example file format has the hash on the left, your use of [1] will pick the username part?)
PowerShell calling the .Net static methods like [system.io.file] is reasonably fast, but these bits:
$pwd = ConvertTo-SecureString $line.Split(':')[1] -AsPlainText -Force
$hash = ConvertTo-NTHash $pwd;
Add-Content C:\...\68_linkedin_ntlm.txt $hash
have a huge overhead. Starting and initializing cmdlets costs a lot more than function calls in other languages, and having add-content close/open the file 50 million times adds needless file system overhead. Change that so you open the file once, and write to it in the loop:
# before the loop
$outStream = [System.IO.StreamWriter]::new(
[System.IO.FileStream]::new(
'c:\path\output.txt',
[system.io.filemode]::OpenOrCreate))
# in the loop
$outStream.WriteLine($hash)
# after the loop
$outStream.Close()
The next bit would be to see if you can get the code which does ConvertTo-SecureString and ConvertTo-NTHash and inline it. I don't know what the NTHash one is, but ConvertTo-SecureString source is here, it's not going to be trivial to wrap / inline that into PowerShell code.
That's it as far as I can see for "quick and dirty", but it might knock some 20-30% off the runtime.
How do you pin to start special folders using powershell? Like "ThisPC", iexplorer
This will pin to start exe's fine, but what about windows explorer and myComputer? How to pin those items since they have no target?
Given this
<start:DesktopApplicationTile Size="2x2" Column="0" Row="0" DesktopApplicationLinkPath="%APPDATA%\Microsoft\Windows\Start Menu\Programs\Windows System\This PC.lnk" />
It seems to have issues with .lnk's for "This PC", "File Explorer", etc
Function PinLnk
{
Param
(
[Parameter(Mandatory,Position=0)]
[Alias('p')]
[String[]]$Path
)
$Shell = New-Object -ComObject Shell.Application
$Desktop = $Shell.NameSpace(0X0)
$WshShell = New-Object -comObject WScript.Shell
$Flag=0
Foreach($itemPath in $Path)
{
$itemName = Split-Path -Path $itemPath -Leaf
#pin application to windows Start menu
$ItemLnk = $Desktop.ParseName($itemPath)
$ItemVerbs = $ItemLnk.Verbs()
Foreach($ItemVerb in $ItemVerbs)
{
If($ItemVerb.Name.Replace("&","") -match "Pin to Start")
{
$ItemVerb.DoIt()
$Flag=1
}
}
}
}
PinLnk "C:\Program Files (x86)\Microsoft Visual Studio 14.0\Common7\IDE\devenv.exe"
I tried this approach as well still not pinning mycomputer to start
PS C:\WINDOWS\system32> Function PinLnk14
>> {
>>
>> $shell = new-object -com Shell.Application
>> $folder = $shell.NameSpace("shell:::{20D04FE0-3AEA-1069-A2D8-08002B30309D}") # ssfDRIVES
>> $ItemVerbs=$folder.Self.Verbs()
>> Foreach($ItemVerb in $ItemVerbs)
>> {
>> Write-Output $ItemVerb.Name
>> If($ItemVerb.Name.Replace("&","") -match "Pin to Start")
>> {
>> Write-Output "TRYING TO PIN"
>> $ItemVerb.DoIt()
>> }
>> }
>> }
PS C:\WINDOWS\system32>
PS C:\WINDOWS\system32> Pinlnk14
&Open
Pin to Quick access
Mana&ge
&Pin to Start
TRYING TO PIN
Map &network drive...
Dis&connect network drive...
Create &shortcut
&Delete
Rena&me
P&roperties
Most special folders are accessible using special values, documented here: ShellSpecialFolderConstants enumeration
So, if you want to get the My Computer (a.k.a. "This PC") folder, you can do this:
$shell = new-object -com Shell.Application
$folder = $shell.NameSpace(17) # "ssfDRIVES" constant
And this will get you a Folder object.
There is another way wich uses the folder CLSID (a guid). It will allow you to get to any folder in what's called the shell namespace, even the ones that may not be defined in the enumeration above (3rd party shell namespace extensions for example). The syntax is this:
$shell = new-object -com Shell.Application
$folder = $shell.Namespace("shell:::{CLSID}")
In fact, this funny syntax combines the 'shell:' URI moniker with the shell namespace parsing syntax ::{CLSID}.
So for example to get the My Computer folder, you would do use the constant known as CLSID_MyComputer like this:
$shell = new-object -com Shell.Application
$folder = $shell.Namespace("shell:::{20D04FE0-3AEA-1069-A2D8-08002B30309D}")
This will also work:
$shell = new-object -com Shell.Application
$folder = $shell.Namespace("shell:MyComputerFolder") # direct shell: syntax
And it should bring you back the same object as in the previous call. They're all equivalent.
Once you have a Folder object, there is a last trick to get the associated verbs, because the Verbs() method is only defined on the FolderItem object.
To get the FolderItem from the Folder (as a Folder is also an "item" in the namespace, so it has also a FolderItem facade), you can use the Self property, like this:
$shell = new-object -com Shell.Application
$folder = $shell.NameSpace("shell:::{20D04FE0-3AEA-1069-A2D8-08002B30309D}") # ssfDRIVES
$folder.Self.Verbs()
Ok, that was to get verbs for a FolderItem. To pin an item to start however, the "Pin to Start" verb invocation does not always work (for My Computer for example), or the verb isn't even available (for a standard folder for example). In general, it doesn't really work well for folders for some reason.
So, one solution for folders is to first create a shortcut file (.lnk) somewhere to that folder (including My Computer or other special locations), and pin that shortcut file to start. Note: the standard (non language localized) verb for Pin to Start is "PinToStartScreen", it's better to use that than to scan various verbs (all verbs have a canonical name). So the code would look like this to pin My Computer to start:
$wshell = new-object -com WScript.Shell
$shortcut = $wshell.CreateShortcut("c:\temp\mypc.lnk")
$shortcut.TargetPath = "shell:MyComputerFolder" # use the same syntax as described above
$shortcut.Save()
$shell = new-object -com Shell.Application
$folder = $shell.NameSpace("c:\temp")
$lnk = $folder.ParseName("mypc.lnk") # get the shortcut file
$lnk.InvokeVerb("PinToStartScreen") # invoke "Pin To Start" on the shortcut file
The fact is that's exactly what Windows does when we do "Pin to Start" on My Computer, it creates a shortcut in C:\Users\<my user>\AppData\Roaming\Microsoft\Windows\Start Menu\Programs
I've been working on a VERY specific functionality "need" to tie into a custom Provider I'm writing in C#.
Basically I set out to find a way to replicate the
A:
B:
etc functions defined when PowerShell loads so instead of having to type
CD A:
You can just do the aforementioned
A:
I tried first to have my provider inject the functions into the runspace but it seems I'm completely missing the timing of how to get that to work so I went another route.
Basically I have a VERY simple PSM1 file UseColons.psm1
function Use-ColonsForPSDrives
{
[CmdletBinding()] Param()
Write-Verbose "Looping Through Installed PowerShell Providers"
Get-PSProvider | % `
{
Write-Verbose "Found $($_.Name) checking its drives"
$_.Drives | ? { (Get-Command | ? Name -eq "$($_.Name):") -eq $null } | `
{
Write-Verbose "Setting up: `"function $($_.Name):() {Set-Location $($_.Name):}`""
if ($Verbose)
{
. Invoke-Expression -Command "function $($_.Name):() {Set-Location $($_.Name):}"
}
else
{
. Invoke-Expression -Command "function $($_.Name):() {Set-Location $($_.Name):}" -ErrorAction SilentlyContinue
}
Write-Verbose "Finished with drive $($_.Name)"
}
}
# Cert and WSMan do not show up as providers until you try to naviagte to their drives
# As a result we will add their functions manually but we will check if they are already set anyways
if ((Get-Command | ? Name -eq "Cert:") -eq $null) { . Invoke-Expression -Command "function Cert:() {Set-Location Cert:}" }
if ((Get-Command | ? Name -eq "WSMan:") -eq $null) { . Invoke-Expression -Command "function WSMan:() {Set-Location WSMan:}" }
}
. Use-ColonsForPSDrives
In simple terms it loops through all loaded providers, then through all the drives of each provider, then it checks if the Function: drive contains a function matching the {DriveName}: format and if one is not found it creates one.
The psd1 file is nothing more than export all functions
This is stored in the %ProgramFiles%\WindowsPowerShell\Modules path under its own folder
And finally I have profile.ps1 under the %windir%\system32\windowspowershell\v1.0 directory that just does
Remove-Module UseColons -ErrorAction SilentlyContinue
Import-Module UseColons
So when I load PowerShell or the ISE if I want to get to say dir through the variables I can just call
Variable:
Or if I need to switch back to the registry
HKLM:
HKCU:
Which when you are working with multiple providers typing that CD over and over as you switch is just annoying.
Now to the problem I'm still working on developing the actual PowerShell provider this was originally intended for. But when I debug it the UseColons module loads BEFORE visual studio turns around and loads the new provider so if I manually remove and import the module again it does its thing and I have all my drive functions for my provider.
I wanted to know after that LONG explanation how can I either:
Setup my UseColons module to load LAST
Find a way to have my Custom Provider (technically a module since it has the provider AND custom Cmdlets) load the UseColons module when it initializes
I don't want to remove it from my standard profile because it is very helpful when I'm not working on the new provider and just tooling around using powershell for administrative stuff.
Hopefully someone can give me some ideas or point me in the direction of some good deeper dive powershell provider documentations and how-tos.
In your module manifest (.psd1), you have a DLL as the RootModule?
This is a horrible hack, and does not help for drives that get created in the future, but...
In your module manifest, instead of YourProvider.dll as the RootModule, use Dummy.psm1 instead (can be an empty file). Then, for NestedModules, use #( 'YourProvider.dll', 'UseColons' ). This allows the UseColons module to be loaded after YourProvider.dll. (Dummy will be last.)
I am looking to replace a Virtual Box solution with MS Hyper-V since I have had many problems with non-Reproducible issues in my automated test-suite using Virtual Box. I have a Windows 8.1 computer I will be using to run the tests on.
The current Virtual Box flow:
Start a VM
Reset snapshot
Use C# to transfer files to Guest OS through the network
Use Virtual Box to trigger the transferred .exe file to start automated tests.
I see people using Powershell Scripts and WMI to start and stop their Hyper-V VMs, but I don't see any way to trigger the transferred files on the Guest OS.
Am I missing an API that I can use? Otherwise how could I trigger the EXE on the guest OS programmatically?
I ended up using System.Management.Automation.PowerShell. I will share the main code chunk I used to do each step so future users can get help.
The Main Code Chunk
var ps = PowerShell.Create();
//Restore Snapshots
ps.AddCommand("Restore-VMSnapshot");
ps.AddParameter("Name", snapshot);
ps.AddParameter("VMName", vmName);
ps.AddParameter("Confirm", false);
ps.Invoke();
ps.Commands.Clear();
//Start VM
ps.AddCommand("Start-VM");
ps.AddParameter("Name", vmName);
ps.Invoke();
ps.Commands.Clear();
//Get IP
string[] ipValues = null;
do
{
ps.AddCommand("Get-VMNetworkAdapter");
ps.AddParameter("VMName", vmName);
var ips = ps.Invoke();
ps.Commands.Clear();
if (ips.Count > 0)
{
ipValues = (string[])ips[0].Members["IPAddresses"].Value;
}
} while (ipValues.Length ==0);
string ip = ipValues[0];
//Move Exe to VM
File.Copy(#"...", "\\\\" + ip + "\\Users\\Public\\Documents\\...", true);
//Run Program
ps.AddScript("$Username = '...'; $Password = '...' ;$ComputerName = '"+ip+"' ;"+
"$Script = {Start-Process C:\\Users\\Public\\Documents\\....exe} ;$secpasswd = ConvertTo-SecureString $Password -AsPlainText -Force ;"+
"$mycreds = New-Object System.Management.Automation.PSCredential ($Username, $secpasswd) ;"+
" $Session = New-PSSession -ComputerName $ComputerName -credential $mycreds ; Invoke-Command -Session $Session -Scriptblock $Script");
var passwords = ps.Invoke();
ps.Commands.Clear();
Notes
The //GetIP section is a do{}while() cause the IP takes a while to be query-able.
There is alot of pre-work required with the host computer and VMs to make this system function, which I will not get into here as google explains those parts better than me.
The flow is designed to match another system which uses Virtual Box, so it may seems a bit inefficient.
This obviously needs to be modified to fit each situation, but should be a good starting point for Hyper-V Automation.
A very usefull PowerShell CmdLet to transfert files to VM is Copy-VMFile.
Syntax is explained here :
http://technet.microsoft.com/en-us/library/dn464282.aspx
Hope this helps !