示例#1
0
        /// <summary>
        /// Tests that a given connection is valid and can be opened.
        /// </summary>
        /// <param name="connectionInfo">The connection information.</param>
        public bool TestConnection(PSConnectionInfo connectionInfo)
        {
            if (connectionInfo == null)
            {
                throw new ArgumentNullException(nameof(connectionInfo));
            }

            try
            {
                using (var pshell = new PSClient())
                {
                    pshell.Open(connectionInfo);
                    pshell.Close();
                }

                return(true);
            }
            catch (PSRemotingTransportException)
            {
                return(false);
            }
            catch (OperationCanceledException)
            {
                return(false);
            }
        }
示例#2
0
        /// <summary>
        /// Determines if the specified path exists on the remote machine.
        /// </summary>
        /// <param name="path">The path to check for.</param>
        /// <param name="checkFiles"><c>true</c> if you want to check for files that exist.</param>
        /// <param name="checkFolders"><c>true</c> if you want to check for folders that exist.</param>
        public bool PathExists(string path, bool checkFiles = true, bool checkFolders = true)
        {
            if (!checkFiles && !checkFolders)
            {
                return(false);
            }                                                   // how could that exist?

            string testPathType = "Any";

            if (!checkFiles)
            {
                testPathType = "Container";
            }
            if (!checkFolders)
            {
                testPathType = "Leaf";
            }

            return(PSClient.InvokeCommand <bool>
                   (
                       "Test-Path",
                       new
            {
                LiteralPath = path,
                PathType = testPathType
            }
                   )
                   .Single());

            //var cmd = $"Test-Path -LiteralPath {PSUtils.EscapeString(path)} -PathType {testPathType}";
            //var result = PSClient.InvokeScript<bool>(cmd).Single();
            //return result;
        }
示例#3
0
 /// <summary>
 /// Ensures that the given directory exists on the remote machine.
 /// </summary>
 /// <param name="directory">The directory to check for.</param>
 public void EnsureDirectory(string directory)
 {
     if (!PathExists(directory, false, true))
     {
         // Specify return type to prevent console output.
         PSClient.InvokeCommand <PSObject>("md", new { Path = directory });
     }
 }
示例#4
0
        /// <summary>
        /// Gets the hash of a remote file.
        /// </summary>
        /// <param name="remoteFilePath">The remote file path.</param>
        /// <param name="algorithm">The hashing algorithm to use (default is MD5).</param>
        public string GetFileHash(string remoteFilePath, string algorithm = null)
        {
            algorithm = (algorithm ?? string.Empty).Trim();
            bool appendFileLength = false;

            if (algorithm.EndsWith("+LENGTH", StringComparison.InvariantCultureIgnoreCase))
            {
                appendFileLength = true;
                algorithm        = algorithm.Substring(0, algorithm.Length - 7).Trim();
            }

            if (string.IsNullOrWhiteSpace(algorithm))
            {
                algorithm = "MD5";
            }

            var hashResult = PSClient.InvokeCommand <PSObject>
                             (
                "Get-FileHash",
                new
            {
                Path      = remoteFilePath?.Replace("[", "`[")?.Replace("]", "`]"),
                Algorithm = algorithm
            }
                             );

            var    row    = hashResult?.FirstOrDefault();
            string result = null;

            if (row != null)
            {
                result = row.Properties.Where
                         (
                    x => x.Name.StartsWith("Hash", StringComparison.InvariantCultureIgnoreCase)
                         )
                         .Select
                         (
                    x => x?.Value as string
                         )
                         .Where
                         (
                    x => !string.IsNullOrWhiteSpace(x)
                         )
                         .FirstOrDefault();
            }

            if (appendFileLength)
            {
                var length = GetFileSize(remoteFilePath);
                result = (result ?? string.Empty) + "::" + length;
            }

            return(result);
        }
示例#5
0
        /// <summary>
        /// Gets the size of a remote file.
        /// </summary>
        /// <param name="remoteFilePath">The remote file path.</param>
        public long GetFileSize(string remoteFilePath)
        {
            var fileResult = PSClient.InvokeCommand <PSObject>
                             (
                "Get-ChildItem",
                new
            {
                PSPath = remoteFilePath
            }
                             );

            return((long)fileResult.First().Properties["Length"].Value);
        }
示例#6
0
        /// <summary>
        /// Gets raw bytes of a file on the remote file system.
        /// </summary>
        /// <param name="remoteFilePath">The path to the file.</param>
        public byte[] GetFileBytes(string remoteFilePath)
        {
            byte[] results = null;

            if (PathExists(remoteFilePath, true, false))
            {
                remoteFilePath = PSUtils.EscapeString(remoteFilePath);
                var script = $@"[System.Convert]::ToBase64String([System.IO.File]::ReadAllBytes({remoteFilePath}))";

                var data = PSClient.InvokeScript <string>(script).Single();
                results = Convert.FromBase64String(data);
            }

            return(results);
        }
示例#7
0
 /// <summary>
 /// Initializes a new instance of the <see cref="PSFileSystem" /> class.
 /// </summary>
 /// <param name="psClient">The PowerShell Client instance to perform the commands against.</param>
 public PSFileSystem(PSClient psClient)
 {
     this.PSClient = psClient
                     ?? throw new ArgumentNullException(nameof(psClient));
 }