private void checkForCorruptedAndDynamicallySizedVhd()
        {
            // checking for corrupted vhd
            PathIntrinsics currentPath = SessionState.Path;
            var            filePath    = new FileInfo(currentPath.GetUnresolvedProviderPathFromPSPath(LocalFilePath.ToString()));

            using (var vds = new VirtualDiskStream(filePath.FullName))
            {
                if (vds.DiskType == DiskType.Fixed)
                {
                    long divisor = Convert.ToInt64(Math.Pow(2, 9));
                    long rem     = 0;
                    Math.DivRem(filePath.Length, divisor, out rem);
                    if (rem != 0)
                    {
                        throw new ArgumentOutOfRangeException("LocalFilePath", "Given vhd file is a corrupted fixed vhd");
                    }
                }
                else
                {
                    convertDynamicVhdToStatic();
                }
            }
            return;
        }
示例#2
0
        internal override void SetSessionStateItem(string path, object value, bool writeItem)
        {
            Path name = PathIntrinsics.RemoveDriveName(path);

            path = name.TrimStartSlash();

            if (value == null)
            {
                Environment.SetEnvironmentVariable(path, null);
            }
            else
            {
                if (value is DictionaryEntry)
                {
                    value = ((DictionaryEntry)value).Value;
                }
                string str = value as string;
                if (str == null)
                {
                    str = PSObject.AsPSObject(value).ToString();
                }
                Environment.SetEnvironmentVariable(path, str);
                DictionaryEntry item = new DictionaryEntry(path, str);
                if (writeItem)
                {
                    WriteItemObject(item, path, false);
                }
            }
        }
        public override void ExecuteCmdlet()
        {
            base.ExecuteCmdlet();
            ExecuteClientAction(() =>
            {
                if (ShouldProcess(this.VMScaleSetName, VerbsLifecycle.Invoke))
                {
                    string resourceGroupName;
                    string vmScaleSetName;
                    string instanceId;
                    switch (this.ParameterSetName)
                    {
                    case "ResourceIdParameter":
                        resourceGroupName = GetResourceGroupName(this.ResourceId);
                        vmScaleSetName    = GetResourceName(this.ResourceId, "Microsoft.Compute/virtualMachineScaleSets", "virtualMachines");
                        instanceId        = GetInstanceId(this.ResourceId, "Microsoft.Compute/virtualMachineScaleSets", "virtualMachines");
                        break;

                    case "ObjectParameter":
                        resourceGroupName = GetResourceGroupName(this.VirtualMachineScaleSetVM.Id);
                        vmScaleSetName    = GetResourceName(this.VirtualMachineScaleSetVM.Id, "Microsoft.Compute/virtualMachineScaleSets", "virtualMachines");
                        instanceId        = GetInstanceId(this.VirtualMachineScaleSetVM.Id, "Microsoft.Compute/virtualMachineScaleSets", "virtualMachines");
                        break;

                    default:
                        resourceGroupName = this.ResourceGroupName;
                        vmScaleSetName    = this.VMScaleSetName;
                        instanceId        = this.InstanceId;
                        break;
                    }
                    RunCommandInput parameters = new RunCommandInput();
                    parameters.CommandId       = this.CommandId;
                    if (this.ScriptPath != null)
                    {
                        parameters.Script          = new List <string>();
                        PathIntrinsics currentPath = SessionState.Path;
                        var filePath       = new System.IO.FileInfo(currentPath.GetUnresolvedProviderPathFromPSPath(this.ScriptPath));
                        string fileContent = Commands.Common.Authentication.Abstractions.FileUtilities.DataStore.ReadFileAsText(filePath.FullName);
                        parameters.Script  = fileContent.Split(new string[] { "\r\n", "\n", "\r" }, StringSplitOptions.RemoveEmptyEntries);
                    }
                    if (this.Parameter != null)
                    {
                        var vParameter = new List <RunCommandInputParameter>();
                        foreach (var key in this.Parameter.Keys)
                        {
                            RunCommandInputParameter p = new RunCommandInputParameter();
                            p.Name  = key.ToString();
                            p.Value = this.Parameter[key].ToString();
                            vParameter.Add(p);
                        }
                        parameters.Parameters = vParameter;
                    }

                    var result   = VirtualMachineScaleSetVMsClient.RunCommand(resourceGroupName, vmScaleSetName, instanceId, parameters);
                    var psObject = new PSRunCommandResult();
                    ComputeAutomationAutoMapperProfile.Mapper.Map <RunCommandResult, PSRunCommandResult>(result, psObject);
                    WriteObject(psObject);
                }
            });
        }
示例#4
0
        internal override object GetSessionStateItem(string name)
        {
            Path path = PathIntrinsics.RemoveDriveName(name);

            path = path.TrimStartSlash();
            return(SessionState.Alias.Get(path));
        }
示例#5
0
        internal override void SetSessionStateItem(string name, object value, bool writeItem)
        {
            Path path = PathIntrinsics.RemoveDriveName(name);

            name = path.TrimStartSlash();

            PSVariable variable = null;

            if (value != null)
            {
                variable = value as PSVariable;
                if (variable == null)
                {
                    variable = new PSVariable(name, value);
                }
                else if (String.Compare(name, variable.Name, true, System.Globalization.CultureInfo.CurrentCulture) != 0)
                {
                    PSVariable var = new PSVariable(name, variable.Value, variable.Options, variable.Attributes);
                    var.Description = variable.Description;
                    variable        = var;
                }
            }
            else
            {
                variable = new PSVariable(name, null);
            }
            // TODO: can be Force'ed
            SessionState.PSVariable.Set(variable);
            PSVariable item = SessionState.PSVariable.Get(variable.Name);

            if (writeItem && (item != null))
            {
                WriteItemObject(item, item.Name, false);
            }
        }
示例#6
0
        /// <summary>
        /// Returns an unresolved qualified path from a component key path.
        /// </summary>
        /// <param name="source">A <see cref="PathIntrinsics"/> object.</param>
        /// <param name="path">The path to convert.</param>
        /// <returns>An unresolved qualified path.</returns>
        internal static string GetUnresolvedPSPathFromKeyPath(this PathIntrinsics source, string path)
        {
            if (null == source)
            {
                throw new ArgumentNullException("source");
            }
            else if (string.IsNullOrEmpty(path))
            {
                // Probably no key path.
                return null;
            }

            // Treat UNC paths as normal FileSystem paths.
            if (path.StartsWith(DirectorySeparator, StringComparison.Ordinal))
            {
                return source.GetUnresolvedPSPathFromProviderPath(path);
            }

            // Get the path prefix to determine the path type.
            // Windows Installer will sometimes use a ? instead of : so search for both.
            var pos = path.IndexOfAny(DriveSeparators);

            // File system key paths.
            if (1 == pos)
            {
                // Translate a ? to a :.
                if ('?' == path[pos])
                {
                    path = path.Substring(0, pos) + DriveSeparator + path.Substring(1 + pos);
                }

                return source.GetUnresolvedPSPathFromProviderPath(path);
            }

            // Registry key paths.
            else if (2 == pos)
            {
                // Map the key path based on the current process's bitness.
                var view = RegistryView.GetInstance();
                path = view.MapKeyPath(path);

                if (!string.IsNullOrEmpty(path))
                {
                    // Strip the trailing backslash (for registry keys) or full registry value
                    // since the Registry provider cannot represent registry values in a PSPath.
                    pos = path.LastIndexOf(DirectorySeparator, StringComparison.Ordinal);
                    path = path.Substring(0, pos);

                    // Not all the roots have drives, so we have to hard code the provider-qualified root.
                    return RegistryProvider + path;
                }
            }

            // Fallback: not an error, but not valid either.
            return null;
        }
        public static EntityDrive GetEntityDriveFromPSPath(PathIntrinsics pathIntrinsics, string path)
        {
            var paths = pathIntrinsics.GetResolvedPSPathFromPSPath(path);
            var drive = (from p in paths
                         let e = p.Drive as EntityDrive
                                 where null != e
                                 select e).Distinct().FirstOrDefault();

            return(drive);
        }
示例#8
0
        public UploadParameters ValidateParameters()
        {
            BlobUri destinationUri;

            if (!BlobUri.TryParseUri(Destination, out destinationUri))
            {
                throw new ArgumentOutOfRangeException("Destination", this.Destination.ToString());
            }

            BlobUri baseImageUri = null;

            if (this.BaseImageUriToPatch != null)
            {
                if (!BlobUri.TryParseUri(BaseImageUriToPatch, out baseImageUri))
                {
                    throw new ArgumentOutOfRangeException("BaseImageUriToPatch", this.BaseImageUriToPatch.ToString());
                }

                if (!String.IsNullOrEmpty(destinationUri.Uri.Query))
                {
                    var message = String.Format(Rsrc.AddAzureVhdCommandSASUriNotSupportedInPatchMode, destinationUri.Uri);
                    throw new ArgumentOutOfRangeException("Destination", message);
                }
            }

            var storageCredentialsFactory = CreateStorageCredentialsFactory();

            PathIntrinsics currentPath = SessionState.Path;
            var            filePath    = new FileInfo(currentPath.GetUnresolvedProviderPathFromPSPath(LocalFilePath.ToString()));

            using (var vds = new VirtualDiskStream(filePath.FullName))
            {
                if (vds.DiskType == DiskType.Fixed)
                {
                    long divisor = Convert.ToInt64(Math.Pow(2, 9));
                    long rem     = 0;
                    Math.DivRem(filePath.Length, divisor, out rem);
                    if (rem != 0)
                    {
                        throw new ArgumentOutOfRangeException("LocalFilePath", "Given vhd file is a corrupted fixed vhd");
                    }
                }
            }

            var parameters = new UploadParameters(
                destinationUri, baseImageUri, filePath, OverWrite.IsPresent,
                (NumberOfUploaderThreads) ?? DefaultNumberOfUploaderThreads)
            {
                Cmdlet            = this,
                BlobObjectFactory = new CloudPageBlobObjectFactory(storageCredentialsFactory, TimeSpan.FromMinutes(1))
            };

            return(parameters);
        }
示例#9
0
        internal override object GetSessionStateItem(string name)
        {
            Path path = PathIntrinsics.RemoveDriveName(name);

            path = path.TrimStartSlash();
            string environmentVariable = Environment.GetEnvironmentVariable(path);

            if (environmentVariable != null)
            {
                return(new DictionaryEntry(path, environmentVariable));
            }
            return(null);
        }
示例#10
0
        protected override void GetItem(Path name)
        {
            // HACK: should it be this way?

            if (string.Equals("variable:\\", name, StringComparison.CurrentCultureIgnoreCase))
            {
                name = PathIntrinsics.RemoveDriveName(name);
                GetChildItems(name, false);
            }
            else
            {
                GetItem(PathIntrinsics.RemoveDriveName(name));
            }
        }
示例#11
0
 public ExternalCommand(PathIntrinsics pathIntrinsics, string commandName, string workingDirectory = null)
 {
     PathInfo         = pathIntrinsics;
     Name             = commandName;
     WorkingDirectory = PathInfo.CurrentFileSystemLocation.Path;
     if (workingDirectory != null)
     {
         WorkingDirectory = PathInfo.GetUnresolvedProviderPathFromPSPath(workingDirectory);
         if (!Directory.Exists(WorkingDirectory))
         {
             throw new ArgumentOutOfRangeException(nameof(workingDirectory), string.Format(Microsoft.Azure.Commands.WebApps.Properties.Resources.GitDirectoryDoesNotExist, workingDirectory));
         }
     }
 }
示例#12
0
        /// <summary>
        /// Returns a <see cref="PSObject"/> wrapper for a <see cref="PatchInstallation"/> object and attaches special properties.
        /// </summary>
        /// <param name="source">The <see cref="PatchInstallation"/> object to convert.</param>
        /// <param name="provider">A <see cref="PathIntrinsics"/> provider used to convert paths.</param>
        /// <returns>A <see cref="PSObject"/> wrapper with attached special properties.</returns>
        internal static PSObject ToPSObject(this PatchInstallation source, PathIntrinsics provider = null)
        {
            if (null == source)
            {
                throw new ArgumentNullException("source");
            }

            var obj = PSObject.AsPSObject(source);

            // Add path information if possible.
            if (null != provider)
            {
                var path = provider.GetUnresolvedPSPathFromProviderPath(source.LocalPackage);
                obj.SetPropertyValue<string>("PSPath", path);
            }

            return obj;
        }
示例#13
0
        /// <summary>
        /// Returns an unresolved, provider-qualified path string.
        /// </summary>
        /// <param name="source">A <see cref="PathIntrinsics"/> object.</param>
        /// <param name="path">The path to resolve and format.</param>
        /// <returns>A resolved, provider-qualified path string.</returns>
        internal static string GetUnresolvedPSPathFromProviderPath(this PathIntrinsics source, string path)
        {
            if (null == source)
            {
                throw new ArgumentNullException("source");
            }
            else if (string.IsNullOrEmpty(path))
            {
                // Pass through.
                return null;
            }

            ProviderInfo provider;
            PSDriveInfo drive;

            path = source.GetUnresolvedProviderPathFromPSPath(path, out provider, out drive);
            return provider.ModuleName + DirectorySeparator + provider.Name + ProviderSeparator + path;
        }
示例#14
0
        /// <summary>
        /// Creates an instance of an <see cref="InstallCommandActionData"/> class from the given file path.
        /// </summary>
        /// <typeparam name="T">The specific type of <see cref="InstallCommandActionData"/> to create.</typeparam>
        /// <param name="resolver">A <see cref="PathIntrinsics"/> object to resolve the file path.</param>
        /// <param name="file">A <see cref="PSObject"/> wrapping a file path.</param>
        /// <returns>An instance of an <see cref="InstallCommandActionData"/> class.</returns>
        public static T CreateActionData <T>(PathIntrinsics resolver, PSObject file) where T : InstallCommandActionData, new()
        {
            if (null == resolver)
            {
                throw new ArgumentNullException("resolver");
            }
            else if (null == file)
            {
                throw new ArgumentNullException("file");
            }

            var data = new T()
            {
                Path = resolver.GetUnresolvedProviderPathFromPSPath(file.Properties["PSPath"].Value as string),
            };

            return(data);
        }
示例#15
0
        /// <summary>
        /// Converts a (possibly) relative path into an absolute one
        /// </summary>
        /// <param name="path">Current path</param>
        /// <param name="relativeOrAbsolutePath">Path to convert</param>
        /// <returns>Absolute path</returns>
        public static string PSPathToAbsolute(PathIntrinsics path, string relativeOrAbsolutePath)
        {
            if (string.IsNullOrEmpty(relativeOrAbsolutePath))
            {
                return(relativeOrAbsolutePath);
            }

            string driveName;

            if (path.IsPSAbsolute(relativeOrAbsolutePath, out driveName))
            {
                return(relativeOrAbsolutePath);
            }
            else
            {
                return(path.GetUnresolvedProviderPathFromPSPath(relativeOrAbsolutePath));
            }
        }
示例#16
0
        protected override string GetChildName(string path)
        {
            if (string.IsNullOrEmpty(path))
            {
                throw new NullReferenceException("Path can't be null");
            }

            path = PathIntrinsics.NormalizePath(path);
            path = path.TrimEnd('\\');

            int num = path.LastIndexOf('\\');

            if (num == -1)
            {
                return(MakeSlashedPath(path));
            }
            return(path.Substring(num + 1));
        }
示例#17
0
        protected override void ProcessRecord()
        {
            AutoMapper.Mapper.AddProfile <ComputeAutomationAutoMapperProfile>();
            ExecuteClientAction(() =>
            {
                if (ShouldProcess(this.VMName, VerbsLifecycle.Invoke))
                {
                    string resourceGroupName   = this.ResourceGroupName;
                    string vmName              = this.VMName;
                    RunCommandInput parameters = new RunCommandInput();
                    parameters.CommandId       = this.CommandId;
                    if (this.ScriptPath != null)
                    {
                        parameters.Script          = new List <string>();
                        PathIntrinsics currentPath = SessionState.Path;
                        var filePath       = new System.IO.FileInfo(currentPath.GetUnresolvedProviderPathFromPSPath(this.ScriptPath));
                        string fileContent = WindowsAzure.Commands.Common.FileUtilities.DataStore.ReadFileAsText(filePath.FullName);
                        parameters.Script  = fileContent.Split(new string[] { "\r\n", "\n", "\r" }, StringSplitOptions.RemoveEmptyEntries);
                    }
                    if (this.Parameter != null)
                    {
                        var vParameter = new List <RunCommandInputParameter>();
                        foreach (var key in this.Parameter.Keys)
                        {
                            RunCommandInputParameter p = new RunCommandInputParameter();
                            p.Name  = key.ToString();
                            p.Value = this.Parameter[key].ToString();
                            vParameter.Add(p);
                        }
                        parameters.Parameters = vParameter;
                    }
                    if (this.VM != null)
                    {
                        vmName            = VM.Name;
                        resourceGroupName = VM.ResourceGroupName;
                    }

                    var result   = VirtualMachinesClient.RunCommand(resourceGroupName, vmName, parameters);
                    var psObject = new PSRunCommandResult();
                    Mapper.Map <RunCommandResult, PSRunCommandResult>(result, psObject);
                    WriteObject(psObject);
                }
            });
        }
        protected virtual string GetChildName(string path)
        {
            if (string.IsNullOrEmpty(path))
            {
                throw new NullReferenceException("Path can't be null");
            }

            path = PathIntrinsics.NormalizePath(path);
            path = path.TrimEnd(PathIntrinsics.CorrectSlash);

            int iLastSlash = path.LastIndexOf('\\');

            if (iLastSlash == -1)
            {
                return(path);
            }

            return(path.Substring(iLastSlash + 1));
        }
示例#19
0
        protected override void ProcessRecord()
        {
            if (ParameterSetName == "Stack")
            {
                // TODO: implement the location stack manipulations
                return;
            }
            else
            {
                if ((PSDrive != null) && (PSDrive.Length > 0))
                {
                    // If location is requested for a specific drive
                    foreach (string str in PSDrive)
                    {
                        List <PSDriveInfo> list = GetDrivesByName(str, PSProvider);

                        foreach (PSDriveInfo pdi in list)
                        {
                            WriteObject(new PathInfo(pdi, pdi.Provider, PathIntrinsics.MakePath(pdi.CurrentLocation, pdi), SessionState));
                        }
                    }
                }
                else if ((PSProvider != null) && (PSProvider.Length > 0))
                {
                    // If location was requested for a specific provider
                    foreach (string proverName in PSProvider)
                    {
                        foreach (ProviderInfo pi in SessionState.Provider.GetAll())
                        {
                            if (pi.IsNameMatch(proverName))
                            {
                                WriteObject(SessionState.Path.CurrentProviderLocation(pi.FullName));
                            }
                        }
                    }
                }
                else
                {
                    // If nothing specific was requested - return the current location
                    WriteObject(SessionState.Path.CurrentLocation);
                }
            }
        }
示例#20
0
        private CmdletProvider GetProviderByPath(string path)
        {
            // MUST: implement for "dir"
            if (string.IsNullOrEmpty(path))
            {
                path = CurrentLocation.Path;
            }

            string driveName = PathIntrinsics.GetDriveFromPath(path);

            PSDriveInfo drive = GetDrive(driveName, null);

            if (drive == null)
            {
                return(null);
            }

            return(GetProviderInstance(drive.Provider.Name));
        }
示例#21
0
        internal PathInfo SetLocation(string path, ProviderRuntime providerRuntime)
        {
            // TODO: deal with paths starting with ".\"

            if (path == null)
            {
                throw new NullReferenceException("Path can't be null");
            }

            path = PathIntrinsics.NormalizePath(path);

            ProviderInfo provider  = null;
            string       driveName = null;

            string      str          = path;
            string      providerId   = null;
            PSDriveInfo currentDrive = CurrentDrive;

            // If path doesn't start with a drive name
            if (path.StartsWith(PathIntrinsics.CorrectSlash.ToString()))
            {
                provider = CurrentLocation.Provider;
            }
            else if (PathIntrinsics.IsAbsolutePath(path, out driveName))
            {
                _currentDrive = GetDrive(driveName, null);

                path = PathIntrinsics.NormalizePath(PathIntrinsics.RemoveDriveName(path));
            }

            _currentDrive.CurrentLocation = path;

            _providersCurrentDrive[CurrentDrive.Provider] = CurrentDrive;

            SetVariable("PWD", CurrentLocation);
            return(CurrentLocation);


            PSDriveInfo drive = CurrentDrive;

            SetLocation(path);
        }
示例#22
0
        private void CheckForInvalidVhd()
        {
            PathIntrinsics currentPath = SessionState.Path;
            FileInfo       filePath    = new FileInfo(currentPath.GetUnresolvedProviderPathFromPSPath(LocalFilePath.ToString()));

            try
            {
                bool resizeNeeded = false;
                long resizeTo     = 0;
                using (VirtualDiskStream vds = new VirtualDiskStream(filePath.FullName))
                {
                    if (vds.Length < 20971520 || vds.Length > 4396972769280)
                    {
                        throw new InvalidOperationException("The VHD must be between 20 MB and 4095 GB.");
                    }

                    if (!this.SkipResizing.IsPresent && (vds.Length - 512) % 1048576 != 0)
                    {
                        resizeNeeded = true;
                        resizeTo     = Convert.ToInt64(1048576 * Math.Ceiling((vds.Length - 512) / 1048576.0));
                    }
                    else if (this.SkipResizing.IsPresent)
                    {
                        WriteVerbose("Skipping VHD resizing.");
                    }

                    FixedSize = vds.Length;
                }

                if (resizeNeeded)
                {
                    resizeVhdFile(resizeTo);
                }
            }
            catch (VhdParsingException)
            {
                throw new InvalidOperationException("The VHD file is corrupted.");
            }

            return;
        }
        public UploadParameters ValidateParameters()
        {
            BlobUri destinationUri;

            if (!BlobUri.TryParseUri(Destination, out destinationUri))
            {
                throw new ArgumentOutOfRangeException("Destination", this.Destination.ToString());
            }

            BlobUri baseImageUri = null;

            if (this.BaseImageUriToPatch != null)
            {
                if (!BlobUri.TryParseUri(BaseImageUriToPatch, out baseImageUri))
                {
                    throw new ArgumentOutOfRangeException("BaseImageUriToPatch", this.BaseImageUriToPatch.ToString());
                }

                if (!String.IsNullOrEmpty(destinationUri.Uri.Query))
                {
                    var message = String.Format(Rsrc.AddAzureVhdCommandSASUriNotSupportedInPatchMode, destinationUri.Uri);
                    throw new ArgumentOutOfRangeException("Destination", message);
                }
            }

            var storageCredentialsFactory = CreateStorageCredentialsFactory();

            PathIntrinsics currentPath = SessionState.Path;
            var            filePath    = new FileInfo(currentPath.GetUnresolvedProviderPathFromPSPath(LocalFilePath.ToString()));

            var parameters = new UploadParameters(
                destinationUri, baseImageUri, filePath, OverWrite.IsPresent,
                (NumberOfUploaderThreads) ?? DefaultNumberOfUploaderThreads)
            {
                Cmdlet            = this,
                BlobObjectFactory = new CloudPageBlobObjectFactory(storageCredentialsFactory, TimeSpan.FromMinutes(1))
            };

            return(parameters);
        }
        protected virtual string GetParentPath(string path, string root)
        {
            if (string.IsNullOrEmpty(path))
            {
                throw new NullReferenceException("Path can't be empty");
            }

            if ((root == null) && (PSDriveInfo != null))
            {
                root = PSDriveInfo.Root;
            }

            path = PathIntrinsics.NormalizePath(path);
            path = path.TrimEnd(PathIntrinsics.CorrectSlash);

            if (root != null)
            {
                if (string.Equals(path, root, StringComparison.CurrentCultureIgnoreCase))
                {
                    return(string.Empty);
                }
            }

            int iLastSlash = path.LastIndexOf(PathIntrinsics.CorrectSlash);

            if (iLastSlash > 0)
            {
                return(path.Substring(0, iLastSlash));
            }

            if (iLastSlash == 1)
            {
                return(PathIntrinsics.CorrectSlash.ToString());
            }

            return(string.Empty);
        }
示例#25
0
        internal override void SetSessionStateItem(string name, object value, bool writeItem)
        {
            Path path = PathIntrinsics.RemoveDriveName(name);

            path = path.TrimStartSlash();

            if (value is Array)
            {
                var array = (Array)value;
                if (array.Length > 1)
                {
                    throw new PSArgumentException("value");
                }
                value = array.GetValue(0);
            }

            var aliasInfo = new AliasInfo(path, value.ToString(), null);

            SessionState.Alias.Set(aliasInfo, "global");

            var a = SessionState.Alias.Get(path);

            Console.WriteLine(a.Definition);
        }
        // internals
        //internal string GetChildName(string path, System.Management.Automation.CmdletProviderContext context);
        //internal string GetParentPath(string path, string root, System.Management.Automation.CmdletProviderContext context);
        //internal bool IsItemContainer(string path, System.Management.Automation.CmdletProviderContext context);
        //internal string MakePath(string parent, string child, System.Management.Automation.CmdletProviderContext context);
        //internal void MoveItem(string path, string destination, System.Management.Automation.CmdletProviderContext context);
        //internal object MoveItemDynamicParameters(string path, string destination, System.Management.Automation.CmdletProviderContext context);
        //internal string NormalizeRelativePath(string path, string basePath, System.Management.Automation.CmdletProviderContext context);

        internal static string NormalizePath(string path)
        {
            return(PathIntrinsics.NormalizePath(path));
        }
示例#27
0
        public override void ExecuteCmdlet()
        {
            base.ExecuteCmdlet();
            ExecuteClientAction(() =>
            {
                if (ShouldProcess(this.VMScaleSetName, "Add"))
                {
                    string resourceGroupName;
                    string vmScaleSetName;
                    switch (this.ParameterSetName)
                    {
                    case "ObjectParameter":
                        resourceGroupName = GetResourceGroupName(this.VirtualMachineScaleSetVM.Id);
                        vmScaleSetName    = GetResourceName(this.VirtualMachineScaleSetVM.Id, "Microsoft.Compute/virtualMachineScaleSets", "virtualMachines");
                        break;

                    default:
                        resourceGroupName = this.ResourceGroupName;
                        vmScaleSetName    = this.VMScaleSetName;
                        break;
                    }
                    VirtualMachineRunCommand vmruncommand;

                    vmruncommand = new VirtualMachineRunCommand
                    {
                        OutputBlobUri    = this.IsParameterBound(c => c.OutputBlobUri) ? this.OutputBlobUri : null,
                        ErrorBlobUri     = this.IsParameterBound(c => c.ErrorBlobUri) ? this.ErrorBlobUri : null,
                        RunAsPassword    = this.IsParameterBound(c => c.RunAsPassword) ? this.RunAsPassword.ToString() : null,
                        RunAsUser        = this.IsParameterBound(c => c.RunAsUser) ? this.RunAsUser : null,
                        TimeoutInSeconds = this.IsParameterBound(c => c.TimeOutInSeconds) ? Convert.ToInt32(this.TimeOutInSeconds) : (int?)null,
                        Location         = this.IsParameterBound(c => c.Location) ? this.Location : null,
                        AsyncExecution   = this.IsParameterBound(c => c.AsyncExecution) ? this.AsyncExecution : null
                    };


                    if (this.IsParameterBound(c => c.ScriptUri))
                    {
                        vmruncommand.Source = new VirtualMachineRunCommandScriptSource
                        {
                            Script    = this.IsParameterBound(c => c.Script) ? this.Script : null,
                            ScriptUri = this.IsParameterBound(c => c.ScriptUri) ? this.ScriptUri : null,
                            CommandId = this.IsParameterBound(c => c.CommandId) ? this.CommandId : null
                        };
                    }
                    else if (this.ScriptPath != null && this.IsParameterBound(c => c.ScriptPath))
                    {
                        List <string> Script       = new List <string>();
                        PathIntrinsics currentPath = SessionState.Path;
                        var filePath       = new System.IO.FileInfo(currentPath.GetUnresolvedProviderPathFromPSPath(this.ScriptPath));
                        string fileContent = Commands.Common.Authentication.Abstractions.FileUtilities.DataStore.ReadFileAsText(filePath.FullName);
                        Script             = fileContent.Split(new string[] { "\r\n", "\n", "\r" }, StringSplitOptions.RemoveEmptyEntries).ToList();

                        vmruncommand.Source = new VirtualMachineRunCommandScriptSource(this.Script, this.ScriptPath, this.CommandId);
                    }

                    if (this.Parameter != null)
                    {
                        var vParameter = new List <RunCommandInputParameter>();
                        foreach (var key in this.Parameter.Keys)
                        {
                            RunCommandInputParameter p = new RunCommandInputParameter();

                            p.Name  = key.ToString();
                            p.Value = this.Parameter[key].ToString();
                            vParameter.Add(p);
                        }
                        vmruncommand.Parameters = vParameter;
                    }
                    else if (this.ProtectedParameter != null)
                    {
                        var vParameter = new List <RunCommandInputParameter>();
                        foreach (var key in this.ProtectedParameter.Keys)
                        {
                            RunCommandInputParameter p = new RunCommandInputParameter();

                            p.Name  = key.ToString();
                            p.Value = this.ProtectedParameter[key].ToString();
                            vParameter.Add(p);
                        }
                        vmruncommand.ProtectedParameters = vParameter;
                    }

                    var expand       = new Microsoft.Rest.Azure.OData.ODataQuery <VirtualMachineScaleSetVM>();
                    expand.Expand    = "instanceView";
                    var vmList       = VirtualMachineScaleSetVMsClient.List(resourceGroupName, vmScaleSetName, expand);
                    var resultList   = vmList.ToList();
                    var nextPageLink = vmList.NextPageLink;
                    while (!string.IsNullOrEmpty(nextPageLink))
                    {
                        var pageResult = VirtualMachineScaleSetVMsClient.ListNext(nextPageLink);
                        foreach (var pageItem in pageResult)
                        {
                            resultList.Add(pageItem);
                        }
                        nextPageLink = pageResult.NextPageLink;
                    }
                    List <VirtualMachineScaleSetVM> listOfVms = new List <VirtualMachineScaleSetVM>(resultList);
                    List <PSVirtualMachineRunCommand> output  = new List <PSVirtualMachineRunCommand>();


                    foreach (VirtualMachineScaleSetVM vm in listOfVms)
                    {
                        var resultOfRunCmd = VirtualMachineScaleSetVMRunCommandsClient.BeginCreateOrUpdateAsync(resourceGroupName, vmScaleSetName, vm.InstanceId, this.Name, vmruncommand);
                        var Pstemp         = new PSVirtualMachineRunCommand();
                        ComputeAutomationAutoMapperProfile.Mapper.Map <VirtualMachineRunCommand, PSVirtualMachineRunCommand>(resultOfRunCmd.Result, Pstemp);
                        output.Add(Pstemp);
                    }

                    WriteObject(output);
                }
            });
        }
示例#28
0
        private PSObject GetItemAsPSObject(object item, Path path)
        {
            if (item == null)
            {
                throw new Exception("Item can't be null");
            }

            PSObject psObject = PSObject.AsPSObject(item);

            PSObject obj3 = item as PSObject;

            if (obj3 != null)
            {
                psObject.TypeNames.Clear();
                foreach (string str in obj3.TypeNames)
                {
                    psObject.TypeNames.Add(str);
                }
            }

            // Add full path as a property
            string providerFullPath = PathIntrinsics.GetFullProviderPath(ProviderInfo, path);

            psObject.Properties.Add(new PSNoteProperty("PSPath", providerFullPath));

            NavigationCmdletProvider provider = this as NavigationCmdletProvider;

            if ((provider != null) && (path != null))
            {
                string parentPath = null;
                if (PSDriveInfo == null)
                {
                    parentPath = provider.GetParentPath(path, string.Empty, ProviderRuntime);
                }
                else
                {
                    parentPath = provider.GetParentPath(path, PSDriveInfo.Root, ProviderRuntime);
                }

                if (!string.IsNullOrEmpty(parentPath))
                {
                    parentPath = PathIntrinsics.GetFullProviderPath(ProviderInfo, parentPath);
                }
                else
                {
                    parentPath = string.Empty;
                }
                psObject.Properties.Add(new PSNoteProperty("PSParentPath", parentPath));

                string childName = provider.GetChildName(path, ProviderRuntime);
                psObject.Properties.Add(new PSNoteProperty("PSChildName", childName));
            }

            if (PSDriveInfo != null)
            {
                psObject.Properties.Add(new PSNoteProperty("PSDrive", PSDriveInfo));
            }

            psObject.Properties.Add(new PSNoteProperty("PSProvider", ProviderInfo));
            return(psObject);
        }
        public override void ExecuteCmdlet()
        {
            base.ExecuteCmdlet();
            ExecuteClientAction(() =>
            {
                try
                {
                    WriteVerbose("To be compatible with Azure, Add-AzVhd will automatically try to convert VHDX files to VHD and resize VHD files to N * Mib using Hyper-V Platform, a Windows native virtualization product. During the process, the cmdlet will temporarily create a converted/resized file in the same directory as the provided VHD/VHDX file. \nFor more information visit https://aka.ms/usingAdd-AzVhd \n");

                    Program.SyncOutput         = new PSSyncOutputEvents(this);
                    PathIntrinsics currentPath = SessionState.Path;
                    vhdFileToBeUploaded        = new FileInfo(currentPath.GetUnresolvedProviderPathFromPSPath(LocalFilePath.ToString()));

                    // 1.              CONVERT VHDX TO VHD
                    if (vhdFileToBeUploaded.Extension == ".vhdx")
                    {
                        vhdFileToBeUploaded = ConvertVhd();
                    }

                    // 2.              RESIZE VHD
                    long vdsLength = GetVirtualDiskStreamLength();
                    if (!this.SkipResizing.IsPresent && (vdsLength - 512) % 1048576 != 0)
                    {
                        long resizeTo       = Convert.ToInt64(1048576 * Math.Ceiling((vdsLength - 512) / 1048576.0));
                        vhdFileToBeUploaded = ResizeVhdFile(vdsLength, resizeTo);
                        vdsLength           = resizeTo + 512;
                    }
                    else if (this.SkipResizing.IsPresent)
                    {
                        WriteVerbose("Skipping VHD resizing.");
                    }


                    if (this.ParameterSetName == DirectUploadToManagedDiskSet)
                    {
                        // 3. DIRECT UPLOAD TO MANAGED DISK


                        // 3-1. CREATE DISK CONFIG
                        CheckForExistingDisk(this.ResourceGroupName, this.DiskName);
                        var diskConfig = CreateDiskConfig(vdsLength);

                        // 3-2: CREATE DISK
                        CreateManagedDisk(this.ResourceGroupName, this.DiskName, diskConfig);

                        // 3-3: GENERATE SAS
                        WriteVerbose("Generating SAS");
                        var accessUri = GenerateSAS();
                        Uri sasUri    = new Uri(accessUri.AccessSAS);
                        WriteVerbose("SAS generated: " + accessUri.AccessSAS);


                        // 3-4: UPLOAD
                        WriteVerbose("Preparing for Upload");
                        ComputeTokenCredential tokenCredential = null;
                        if (this.DataAccessAuthMode == "AzureActiveDirectory")
                        {
                            // get token
                            tokenCredential = new ComputeTokenCredential(DefaultContext, "https://disk.azure.com/");
                        }
                        PSPageBlobClient managedDisk        = new PSPageBlobClient(sasUri, tokenCredential);
                        DiskUploadCreator diskUploadCreator = new DiskUploadCreator();
                        var uploadContext = diskUploadCreator.Create(vhdFileToBeUploaded, managedDisk, false);
                        var synchronizer  = new DiskSynchronizer(uploadContext, this.NumberOfUploaderThreads ?? DefaultNumberOfUploaderThreads);

                        WriteVerbose("Uploading");
                        if (synchronizer.Synchronize(tokenCredential))
                        {
                            var result = new VhdUploadContext {
                                LocalFilePath = vhdFileToBeUploaded, DestinationUri = sasUri
                            };
                            WriteObject(result);
                        }
                        else
                        {
                            RevokeSAS();
                            this.ComputeClient.ComputeManagementClient.Disks.Delete(this.ResourceGroupName, this.DiskName);
                            Exception outputEx = new Exception("Upload failed. Please try again later.");
                            ThrowTerminatingError(new ErrorRecord(
                                                      outputEx,
                                                      "Error uploading data.",
                                                      ErrorCategory.NotSpecified,
                                                      null));
                        }

                        // 3-5: REVOKE SAS
                        WriteVerbose("Revoking SAS");
                        RevokeSAS();
                        WriteVerbose("SAS revoked.");

                        WriteVerbose("\nUpload complete.");
                    }
                    else
                    {
                        var parameters       = ValidateParameters();
                        var vhdUploadContext = VhdUploaderModel.Upload(parameters);
                        WriteObject(vhdUploadContext);
                    }
                }
                finally
                {
                    if (temporaryFileCreated)
                    {
                        WriteVerbose("Deleting file: " + vhdFileToBeUploaded.FullName);
                        File.Delete(vhdFileToBeUploaded.FullName);
                    }
                }
            });
        }
示例#30
0
 public GitCommand(PathIntrinsics currentPath, string workingDirectory = null) : base(currentPath, "git.exe", workingDirectory)
 {
 }