JoeG
JoeG

Reputation: 4247

Call a variable from my $profile script at the console

My $profile script starts a transcript whenever it is run. I am piping the output of Start-Transcript to a variable ($log) like so: Start-Transcript -path $logFile -append > $global:log

I would like to be able to read this variable from the console. As you can see I tried explicitly setting the $log variable scope to Global (it didn't work).

For instance I would like to be able to run the following command: notepad $log1

And have the transcript open in notepad.

Is this even possible? I've been running amok in Google for about an hour, and I can't find anything with relevance to this (which probably means it can't be done, but I figured I'd ask anyway).

Alternatively, is there a way to get the path to the current transcript file some other way?

Upvotes: 1

Views: 1131

Answers (2)

mvndaai
mvndaai

Reputation: 3831

You can pipe to Tee-Object to print out the command and save the output to a variable. Then clean up the variable to only include the filename.

Start-Transcript -path $logFile -append | Tee-Object -Variable log
$log = $log -split "is " | select -Last 1

Upvotes: 0

ravikanth
ravikanth

Reputation: 25820

I don't think that redirection works. Why not just do notepad $logFile?

Update: AFAIK, There is no way you can find the Start-Transcript Path value. However, you can find if the session is getting transcribed or not. Check this: http://poshcode.org/1500

If you do not specify a path, Start-Transcript uses the path in the value of the $Transcript global variable. If you have not created this variable, Start-Transcript stores the transcripts in the $Home\My Documents directory as \PowerShell_transcript..txt files.

BTW, as a recommended practice & before you start writing scripts, you should always start at the console. For example, when I run the following at PowerShell console:

PS C:\> $logfile = "C:\Scripts\Scratch\test.log"
PS C:\> Start-Transcript -path $logFile -append > $global:log
PS C:\> Get-Command Get-Help

CommandType     Name                                                Definition
-----------     ----                                                ----------
Cmdlet          Get-Help                                            Get-Help [[-Name] <String>] [-Path <String>] [-C...


PS C:\> Get-Variable -Name log
Get-Variable : Cannot find a variable with name 'log'.
At line:1 char:13
+ Get-Variable <<<<  -Name log
    + CategoryInfo          : ObjectNotFound: (log:String) [Get-Variable], ItemNotFoundException
    + FullyQualifiedErrorId : VariableNotFound,Microsoft.PowerShell.Commands.GetVariableCommand

The above output at the console clearly tells me that the redirection never worked.

Upvotes: 1

Related Questions