PoshCode Archive  Artifact Content

Artifact 9ee6de9ebd219e248c314245d8df5c2ab5b0257f7a6e9328d234cf323df811ec:

  • File get-ContentFromString.ps1 — part of check-in [a563549641] at 2018-06-10 13:46:29 on branch trunk — Dynamically creates a return of whatever type of file / directory is given. Covers CSV’s txt, log, or other Get-Content related files. (user: internetrush size: 2286)

# encoding: ascii
# api: powershell
# title: get-ContentFromString
# description: Dynamically creates a return of whatever type of file / directory is given. Covers CSV’s txt, log, or other Get-Content related files. 
# version: 0.1
# type: function
# author: internetrush
# license: CC0
# function: get-ContentFromString
# x-poshcode-id: 4833
# x-archived: 2014-01-29T05:09:27
# x-published: 2014-01-23T12:50:00
#
# Pretty basic, can be expanded easily for XML
#
function get-ContentFromString{
	param(
		[Parameter(Mandatory=$True,Position=0)]
		[string]$inputstring, 
		[switch]$recurseDir = $false
	)
	
	$directory = test-path $inputstring -PathType Container
	if($directory){
		try{
			if($recurseDir){
				$returnItem = gci $inputString -ErrorAction 'stop' -Recurse
			}else{
				$returnItem = gci $inputString -ErrorAction 'stop' 	
			}
		}catch{
			$returnItem = Read-Host "Enter valid base directory to your desired items: $inputstring was invalid"
		}finally{
			if([string]::IsNullOrEmpty($returnItem)){
				if($recurseDir){
					$returnItem = gci $inputString -ErrorAction 'stop' -Recurse
				}else{
					$returnItem = gci $inputString -ErrorAction 'stop' 	
				}
			}
			if([string]::IsNullOrEmpty($returnItem)){read-host "Cannot find base Directory, press enter to exit" ; break}
		}
	}else{
		if($inputString -like "*.csv"){
			try{
				$returnItem = Import-Csv $inputString -ErrorAction 'stop'
			}catch{
				$returnItem = Read-Host "Enter valid base directory to your CSV: $inputstring was invalid"
			}finally{
				if([string]::IsNullOrEmpty($returnItem)){
						$returnItem = Import-Csv $inputString -ErrorAction 'stop'
				}
				if([string]::IsNullOrEmpty($returnItem)){read-host "Cannot find base Directory, press enter to exit" ; break}
			}
		}else{
			try{
				$returnItem = gc $inputString -ErrorAction 'stop'
			}catch{
				$returnItem = Read-Host "Enter valid location to the txt or logfile: $inputstring was invalid"
			}finally{
				if([string]::IsNullOrEmpty($returnItem)){
						$returnItem = gc $inputString -ErrorAction 'stop'
				}
				if([string]::IsNullOrEmpty($returnItem)){read-host "Cannot find txt or logfile, press enter to exit" ; break}
			}	
		}
	}
	return $returnItem
}