<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Java2Blog</title>
	<atom:link href="https://java2blog.com/feed/" rel="self" type="application/rss+xml" />
	<link>https://java2blog.com</link>
	<description>A blog on Java, Python and C++ programming languages</description>
	<lastBuildDate>Thu, 26 Feb 2026 05:40:17 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	<generator>https://wordpress.org/?v=6.2.9</generator>

<image>
	<url>https://java2blog.com/wp-content/webpc-passthru.php?src=https://java2blog.com/wp-content/uploads/2022/09/cropped-ICON_LOGO_TRANSPARENT-32x32.png&amp;nocache=1</url>
	<title>Java2Blog</title>
	<link>https://java2blog.com</link>
	<width>32</width>
	<height>32</height>
</image> 
	<item>
		<title>About US</title>
		<link>https://java2blog.com/about-us/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=about-us</link>
					<comments>https://java2blog.com/about-us/#respond</comments>
		
		<dc:creator><![CDATA[Java2blog]]></dc:creator>
		<pubDate>Tue, 02 Sep 2025 05:58:49 +0000</pubDate>
				<category><![CDATA[Core java]]></category>
		<guid isPermaLink="false">https://java2blog.com/?p=26469</guid>

					<description><![CDATA[Welcome to Java2Blog – your go-to place for learning, exploring, and solving problems. What started as a passion for sharing my knowledge of Java and Python has now grown into a platform that reaches thousands of readers every month. From in-depth programming tutorials to simple &#34;how-to&#34; guides, Java2Blog is here to help you learn step [&#8230;]]]></description>
										<content:encoded><![CDATA[<p>Welcome to <strong>Java2Blog</strong> – your go-to place for learning, exploring, and solving problems.</p>
<p>What started as a passion for sharing my knowledge of Java and Python has now grown into a platform that reaches thousands of readers every month. From in-depth programming tutorials to simple &quot;how-to&quot; guides, Java2Blog is here to help you learn step by step—whether you&#8217;re a beginner or an experienced developer looking to sharpen your skills.</p>
<p>But Java2Blog isn&#8217;t just about programming. Over time, the blog has expanded into guides, tips, and tutorials across a wide range of topics that make life easier for learners, tech enthusiasts, and problem-solvers alike.</p>
<p>At its core, <strong>Java2Blog</strong> is built on three principles:</p>
<ul>
<li>Clarity : breaking down complex topics into easy-to-understand language.</li>
<li>Practicality : focusing on real-world use cases and solutions.</li>
<li>Community : helping people from all backgrounds gain the confidence to learn and grow.</li>
</ul>
<p>If you&#8217;re ready to start learning, improving, or just exploring something new—you’re in the right place.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://java2blog.com/about-us/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>Bash Replace Space with Newline</title>
		<link>https://java2blog.com/bash-replace-space-with-newline/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=bash-replace-space-with-newline</link>
					<comments>https://java2blog.com/bash-replace-space-with-newline/#respond</comments>
		
		<dc:creator><![CDATA[Mehvish Ashiq]]></dc:creator>
		<pubDate>Fri, 29 Aug 2025 03:37:44 +0000</pubDate>
				<category><![CDATA[Bash]]></category>
		<category><![CDATA[Bash String]]></category>
		<guid isPermaLink="false">https://java2blog.com/?p=25069</guid>

					<description><![CDATA[If you have multiple consecutive spaces in the string, use the last solution, the for loop. You can use any of the following solutions if you have a multiline string. Using tr Command Use the tr command to replace space with newline in bash. [crayon-69d0c2eb604bb432158760/] [crayon-69d0c2eb604c3484951972/] We initialized the text variable with a sample string. [&#8230;]]]></description>
										<content:encoded><![CDATA[<blockquote>
<p>If you have multiple consecutive spaces in the string, use the last solution, the <code>for</code> loop. You can use any of the following solutions if you have a multiline string.</p>
</blockquote>
<h2>Using tr Command</h2>
<p><strong>Use the <code>tr</code> command to replace space with newline in bash.</strong></p>
<pre class="urvanov-syntax-highlighter-plain-tag">text="This is a sample string."
new_text=$(echo "$text" | tr ' ' '\n')
echo "$new_text"</pre>
<pre class="urvanov-syntax-highlighter-plain-tag">This
is
a
sample
string.</pre>
<p>We initialized the <code>text</code> variable with a sample string. Next, we piped the output of the <code>echo</code> command to the <code>tr</code> command, which translated (replaced) space (<code>&#039; &#039;</code>) with newline (<code>\n</code>).</p>
<p>We captured the output of the <code>echo &quot;$text&quot; | tr &#039; &#039; &#039;\n&#039;</code> command using substitution syntax (<code>$(...)</code>) and assigned to the <code>new_text</code> variable. Finally, we used the <code>echo</code> command to print the <code>new_text</code> variable&#8217;s value on the bash console.</p>
<h2>Using awk Command</h2>
<p><strong>Use the <code>awk</code> command to replace space with newline in bash.</strong></p>
<pre class="urvanov-syntax-highlighter-plain-tag">text="This is a sample string."
new_text=$(echo "$text" | awk -v RS=" " '{print}')
echo "$new_text"</pre>
<pre class="urvanov-syntax-highlighter-plain-tag">This
is
a
sample
string.</pre>
<p>This code snippet is similar to the previous example; however, we piped the <code>echo</code> command output to the <code>awk</code> command this time. The <code>awk</code> is used for text processing. It operates per line by default, but we can customize it to work with fields and records (lines) using special actions and patterns.</p>
<p>In the above example, we used the <code>awk</code> command to replace space with a newline. How? For that, we used the <code>-v</code> option to set the record separator variable (<code>RS</code>) to a space character (<code>&quot; &quot;</code>). By default, the <code>awk</code> takes the newline character as the value of the <code>RS</code> variable.</p>
<p>So, modifying the <code>RS</code> to a space character meant that each space-separated word would become a separate record for processing. For each record, the <code>print</code> command was executed to print the current record, followed by a new line. This effectively replaced spaces with newlines in the output.</p>
<p>Alternatively, we can use the following solution:</p>
<pre class="urvanov-syntax-highlighter-plain-tag">text="This is a sample string."
new_text=$(echo "$text" | awk '{gsub(/ /, "\n"); print}')
echo "$new_text"</pre>
<pre class="urvanov-syntax-highlighter-plain-tag">This
is
a
sample
string.</pre>
<p>Here, we used the <a href="https://www.gnu.org/software/gawk/manual/html_node/String-Functions.html" target="_blank" rel="noopener">gsub</a>, an AWK function to globally substitute all occurrences of a space character (<code>/ /</code>) in the <code>text</code> with a newline character (<code>&quot;\n&quot;</code>).</p>
<h2>Using sed Command</h2>
<p><strong>Use the <code>sed</code> command to replace space with newline in bash.</strong></p>
<pre class="urvanov-syntax-highlighter-plain-tag">text="This is a sample string."
new_text=$(echo "$text" | sed 's/ /\n/g')
echo "$new_text"</pre>
<pre class="urvanov-syntax-highlighter-plain-tag">This
is
a
sample
string.</pre>
<p>We used the <code>sed</code> command, which is used to process and transform text, typically used for performing text substitution, deletion, insertion and more.</p>
<p>In the above example, we used the <code>sed</code> command to substitute text. For that, we wrote the <code>sed</code> command sequence enclosed in single quotes; for instance, <code>&#039;s/ /\n/g&#039;</code>. This <code>sed</code> sequence instructed to perform a substitution operation on the input text. </p>
<p>The sequence of the <code>sed</code> command was comprised of various components; let&#8217;s learn them below:</p>
<ul>
<li>
<p><code>s</code> (stands for <em>substitute</em>) &#8211;  It told the <code>sed</code> to find and replace.</p>
</li>
<li>
<p><code>/</code> (delimiter character) &#8211; It separated the different parts of the <code>sed</code> command: pattern to search for, replacement, and any flags.</p>
</li>
<li>
<p><code>space</code> (between first and second <code>/</code>): This was the pattern to search for. In our case, it was a single-space character.</p>
</li>
<li>
<p><code>\n</code> (newline) &#8211; It was the replacement part; when the pattern (space) was found in the input, it would be replaced with a newline.</p>
</li>
<li>
<p><code>g</code> (stands for <em>global</em>) &#8211; This flag told <code>sed</code> to perform the replacement globally, meaning all occurrences of the pattern in a line would be replaced with the newline character, not just the first occurrence.</p>
</li>
</ul>
<p>This effectively split the input text into separate lines wherever there was a space character.</p>
<h2>Using Parameter Expansion</h2>
<p><strong>Use parameter expansion to replace space with newline in bash.</strong></p>
<pre class="urvanov-syntax-highlighter-plain-tag">text="This is a sample string."
new_text="{text// /$'\n'}"
echo "$new_text"</pre>
<pre class="urvanov-syntax-highlighter-plain-tag">This
is
a
sample
string.</pre>
<p>This example is similar to the previous ones, but we used <a href="https://www.gnu.org/software/bash/manual/html_node/Shell-Parameter-Expansion.html" target="_blank" rel="noopener">parameter expansion</a> this time. The parameter expansion (<code>{text// /$&#039;\n&#039;}</code>) took the value of the <code>text</code> variable, found all occurrences of a space character, and replaced them with a newline character. How? Following is a brief explanation of each component:</p>
<ul>
<li>
<p><code>${...}</code> was the basic syntax of parameter expansion; here, <code>...</code> meant anything that you want to accomplish; for instance, <code>text// /$&#039;\n&#039;</code> in our case.</p>
</li>
<li>
<p><code>//</code> was a pattern-matching operator used in parameter expansion. When used as <code>${parameter//pattern/string}</code>, it matched all occurrences of the provided pattern in the parameter (in this case, the variable <code>text</code>) and replaced them with the given string.</p>
</li>
<li>
<p><code>&#039; &#039;</code> was the pattern we searched for in the <code>text</code> variable. It was a single-space character.</p>
</li>
<li>
<p><code>$&#039;\n&#039;</code> was an ANSI-C quoted string representing a newline character (<code>\n</code>). The <code>$&#039;...&#039;</code> syntax interpreted backslash escapes in bash, so <code>$&#039;\n&#039;</code> was replaced with an actual newline character.</p>
</li>
</ul>
<p>This was how we replaced space with newline in the <code>text</code>.</p>
<h2>Using for Loop</h2>
<p><strong>Use the <code>for</code> loop to replace space with newline in bash.</strong></p>
<pre class="urvanov-syntax-highlighter-plain-tag">text="This is a sample string."
new_text=""
for current_word in $text; do
    new_text="$new_text$current_word\n"
done
echo -e "$new_text"</pre>
<pre class="urvanov-syntax-highlighter-plain-tag">This
is
a
sample
string.</pre>
<p>We used a <code>for</code> loop in the above example to iterate over the <code>$text</code>. In each iteration, we concatenated the <code>$new_text</code>, <code>$current_word</code>, and a newline (<code>\n</code>) as <code>&quot;$new_text$current_word\n&quot;</code> and assigned its value to the <code>new_text</code> variable.</p>
<p>Once the loop was over, we used the <code>echo</code> command with the <code>-e</code> option to print the value of the <code>new_text</code> variable on the bash console.</p>
<p>Note that the <code>-e</code> option was used to interpret backslash escapes in the given string (in this case, <code>new_text</code>), allowing us to include special characters with specific meanings; for example, <code>\n</code> means a new line. </p>
]]></content:encoded>
					
					<wfw:commentRss>https://java2blog.com/bash-replace-space-with-newline/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>Check If File Contains String in Bash</title>
		<link>https://java2blog.com/check-if-file-contains-string-in-bash/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=check-if-file-contains-string-in-bash</link>
					<comments>https://java2blog.com/check-if-file-contains-string-in-bash/#respond</comments>
		
		<dc:creator><![CDATA[Java2blog]]></dc:creator>
		<pubDate>Sun, 26 Nov 2023 10:54:42 +0000</pubDate>
				<category><![CDATA[Bash File]]></category>
		<category><![CDATA[Bash]]></category>
		<category><![CDATA[Bash String]]></category>
		<guid isPermaLink="false">https://java2blog.com/?p=24631</guid>

					<description><![CDATA[1. Overview Searching for strings in text files is a common task in bash, used in scenarios like log file analysis and configuration file searches. This article explores various methods to check if file contains String, including both case-sensitive and case-insensitive approaches. 2. Introduction to Problem Statement Let&#8217;s consider a log file named server.log: [crayon-69d0c2eb60935707949549/] [&#8230;]]]></description>
										<content:encoded><![CDATA[<h2>1. Overview</h2>
<p>Searching for strings in text files is a common task in bash, used in scenarios like log file analysis and configuration file searches. This article explores various methods to check if file contains String, including both case-sensitive and case-insensitive approaches.</p>
<h2>2. Introduction to Problem Statement</h2>
<p>Let&#8217;s consider a log file named <code>server.log</code>:</p>
<pre class="urvanov-syntax-highlighter-plain-tag">2023-11-24 10:00:00 INFO Starting server process
2023-11-24 10:00:05 ERROR Failed to bind to port 8080
2023-11-24 10:00:10 INFO Server listening on port 9090
2023-11-24 10:01:00 WARN Database connection timeout</pre>
<p><strong>Our goal is to check if file <code>server.log</code> contains string <code>Error</code> in it.</strong> </p>
<p>The expected output is something like this: </p>
<pre class="urvanov-syntax-highlighter-plain-tag">Error found in server.log.</pre>
<h2>3. Using grep</h2>
<p>The <code>grep</code> is a command-line utility optimized for searching text data for lines matching a regular expression.</p>
<pre class="urvanov-syntax-highlighter-plain-tag">if grep -q "Error" server.log; then
  echo "Error found in server.log."
else
  echo "Error not found in server.log."
fi</pre>
<p><strong>Explanation:</strong></p>
<ul>
<li><code>grep -q &quot;Error&quot; server.log</code>: This command searches for string <code>Error</code> in <code>server.log</code>. Here, <code>-q</code> stands for <code>&quot;quiet&quot;</code>. It causes grep to not output anything but to exit with status <code>0</code> if the pattern is found, and <code>1</code> otherwise.</li>
<li>The if statement then checks the exit status of grep. If grep finds the string, the first block (<code>&quot;Error found in server.log.&quot;</code>) is executed; if not, the else block executes.</li>
</ul>
<p><strong>Case-Insensitive Search:</strong></p>
<p>By default, grep search is case-sensitive. To perform a case-insensitive search, use the -i flag: <code>grep -iq &quot;Error&quot; server.log</code>.</p>
<p><strong>Performance:</strong><br />
<strong><code>grep</code> is highly optimized for searching text, making it fast and efficient for this task.</strong></p>
<h2>4. Using awk</h2>
<p>The <code>awk</code> is a versatile programming language designed for pattern scanning and processing.</p>
<p>Let&#8217;s use <code>awk</code> with <code>if</code> to achieve our goal:</p>
<pre class="urvanov-syntax-highlighter-plain-tag">if awk '/Error/ {found=1; exit} END {if (!found) exit 1}' server.log; then
  echo "Error found in server.log."
else
  echo "Error not found in server.log."
fi</pre>
<p><strong>Explanation:</strong></p>
<ul>
<li>This awk command scans <code>server.log</code> for the pattern <code>Error</code>.</li>
<li>When <code>Error</code> is found, <code>awk</code> sets a flag found to <code>1</code> and exits immediately.</li>
<li>In the <code>END</code> block, <code>awk</code> exits with status <code>1</code> if the flag found is not set, indicating that the pattern was not found.</li>
</ul>
<p><strong>Case-Insensitive Search:</strong></p>
<p>To make the search case-insensitive in <code>awk</code>, we can use the <code>tolower</code> function: </p>
<pre class="urvanov-syntax-highlighter-plain-tag">if awk 'tolower($0) ~ /Error/ {found=1; exit} END {if (!found) exit 1}' server.log; then
  echo "Error found in server.log."
else
  echo "Error not found in server.log."
fi</pre>
<p><strong>Performance:</strong><br />
The <code>awk</code> is powerful for text processing but might be slightly slower than <code>grep</code> for simple string searches. However, it offers more flexibility for complex data manipulations.</p>
<h2>3. Using Bash Conditional Expressions</h2>
<p>Bash conditional expressions are a powerful feature in shell scripting, allowing for decision-making based on the evaluation of conditions within a script.</p>
<p>Let&#8217;s use conditional expression to check if file contains string:</p>
<pre class="urvanov-syntax-highlighter-plain-tag">if [[ $(cat server.log) == *"Error"* ]]; then
  echo "Error found in server.log."
else
  echo "Error not found in server.log."
fi</pre>
<p>Here, <code>cat filename.txt</code> outputs the content of the file <code>server.log</code>, and the conditional <code>[[ ... == *&quot;Error&quot;* ]]</code> checks if the content contains &quot;Error&quot;.<br />
<strong>Case-Insensitive Search:</strong><br />
Bash does not directly support case-insensitive matching in this context. However, you can convert the file content and the search string to the same case: </p>
<pre class="urvanov-syntax-highlighter-plain-tag">if [[ $(cat server.log | tr '[:upper:]' '[:lower:]') == *"error"* ]]; then
  echo "Error (case-insensitive) found in server.log."
else
  echo "Error (case-insensitive) not found in server.log."
fi</pre>
<p><strong>Performance:</strong><br />
For smaller files, this method is quick and efficient. However, for larger files, its performance can degrade due to the need to read the entire file content.</p>
<h2>6. Using sed with grep Command</h2>
<p>The <code>sed</code> (Stream Editor) is a powerful and versatile text processing tool that performs text transformations on an input stream (a file or input from a pipeline).</p>
<p>Here, we will use <code>sed</code> for preprocessing and <code>grep</code> for final check. Let&#8217;s see with the help of example:</p>
<pre class="urvanov-syntax-highlighter-plain-tag">if sed -n '/Error/p' server.log | grep -q .; then
  echo "Error found in server.log."
else
  echo "Error not found in server.log."
fi</pre>
<p><strong>Explanation</strong>:</p>
<ul>
<li>The sed command searches <code>server.log</code> for lines containing the string <code>Error</code> and prints them.</li>
<li>The output of sed (the matched lines) is passed to grep.</li>
<li><code>grep -q .</code> checks if there is any output from sed. If there is at least one line (meaning at least one line in server.log contained &quot;Error&quot;), grep exits with a status of zero.</li>
<li>If grep exits with a status of zero, indicating that sed found at least one line containing &quot;Error&quot;, the condition in the if statement is considered true, and the commands following then are executed. If no lines are found, the condition is false, and the commands after then are not executed.</li>
</ul>
<p>Let&#8217;s understand more about sed expression <code>sed -n &#039;/Error/p&#039; server.log</code> used in above command:</p>
<ul>
<li><code>sed</code>: This is a stream editor for filtering and transforming text.</li>
<li><code>-n</code>: This option suppresses automatic printing of pattern space. It means <code>sed</code> will not print anything unless explicitly told to do so.</li>
<li><code>&#039;/Error/p&#039;</code>: This is a <code>sed</code> command enclosed in single quotes. It tells <code>sed</code> to search for lines containing the string <code>Error</code> and print those lines (<code>p</code> stands for print). The <code>/Error/</code> is a pattern that <code>sed</code> looks for in each line of the input.<br />
<code>server.log</code>: This is the file <code>sed</code> reads from. <code>sed</code> will process each line of this file, looking for the pattern <code>Error</code>.</li>
</ul>
<h2>7. Using Bash Loops</h2>
<p>This method involves iterating over each line of a file to search for a string. This approach is very slow and should be only used while searching in smaller files.</p>
<pre class="urvanov-syntax-highlighter-plain-tag">found=0
while IFS= read -r line; do
  if [[ $line == *"Error"* ]]; then
    found=1
    break
  fi
done &lt; server.log

if [[ $found -eq 1 ]]; then
  echo "Error found in server.log."
else
  echo "Error not found in server.log."
fi</pre>
<p><strong>Performance:</strong><br />
Bash loops are straightforward but<strong> can be slower, especially for larger files.</strong></p>
<h2>8. Searching for Multiple Strings in File</h2>
<p>While working on script, there are often situations where we need to search based on multiples patterns rather than single pattern.</p>
<p>There are multiple ways to do it. Let&#8217;s see with the help of examples:</p>
<p><strong> Using grep Command:</strong></p>
<pre class="urvanov-syntax-highlighter-plain-tag">if grep -Eq 'Error|Warn' server.log; then
  echo "Error or warn found in server.log."
else
  echo "Error or warn not found in server.log."
fi</pre>
<p>This command uses the pipe <code>|</code> as a logical OR to search for &quot;Error&quot; or &quot;Warn&quot;.</p>
<p><strong>Using awk Command</strong></p>
<pre class="urvanov-syntax-highlighter-plain-tag">if awk '/Error/ || /Warning/' server.log; then
  echo "Error or Warning found in server.log."
else
  echo "Error or Warning not found in server.log."
fi</pre>
<p>This <code>awk</code> command checks if either <code>Error</code> or <code>Warn</code> is present in <code>server.log</code>.</p>
<p><strong>Using Bash Loops</strong></p>
<pre class="urvanov-syntax-highlighter-plain-tag">found=0
while IFS= read -r line; do
  if [[ $line == *"Error"* ]] || [[ $line == *"Warning"* ]]; then
    found=1
    break
  fi
done &lt; server.log

if [[ $found -eq 1 ]]; then
  echo "Error or Warning found in server.log."
else
  echo "Error or Warning not found in server.log."
fi</pre>
<p>This Bash loop manually iterates through each line of <code>server.log</code>, checking for <code>Error</code> or <code>Warn</code>.</p>
<h2>9. Searching for String in Multiple Files</h2>
<p>To search across multiple files, use grep with a file pattern.</p>
<pre class="urvanov-syntax-highlighter-plain-tag">if grep -q "Error" *.log; then
  echo "Error found in log files."
else
  echo "Error not found in log files."
fi</pre>
<p>We can also provide filenames separated by space.</p>
<pre class="urvanov-syntax-highlighter-plain-tag">if grep -q "Error" server1.log server2.log; then
  echo "Error found in log files."
else
  echo "Error not found in log files."
fi</pre>
<h2>10. Performance Comparison</h2>
<p>It&#8217;s important to test how fast each method works so we can choose the best one.</p>
<p><strong>We&#8217;ll create a big input <code>server.log</code> with 1 million lines, and test each solution on it to search pattern &quot;Error&quot; in the file.</strong><br />
To Benchmark their performance, here is the script:</p>
<pre class="urvanov-syntax-highlighter-plain-tag">#!/bin/bash

# Sample file and string
file="server.log"
string="Error"

# Function to measure using grep
measure_grep() {
    time if grep -q "$string" "$file"; then
        echo "grep: String found."
    else
        echo "grep: String not found."
    fi
}

# Function to measure using awk
measure_awk() {
    time if awk "/$string/ {found=1; exit} END {if (!found) exit 1}" "$file"; then
        echo "awk: String found."
    else
        echo "awk: String not found."
    fi
}

# Function to measure using sed
measure_sed() {
    time if sed -n "/$string/p" "$file" | grep -q .; then
        echo "sed: String found."
    else
        echo "sed: String not found."
    fi
}

# Function to measure using Bash loop
measure_bash_loop() {
    time {
        found=0
        while IFS= read -r line; do
            if [[ $line == *"$string"* ]]; then
                found=1
                break
            fi
        done &lt; "$file"

        if [[ $found -eq 1 ]]; then
            echo "Bash loop: String found."
        else
            echo "Bash loop: String not found."
        fi
    }
}

# Function to measure using Bash Conditional Expressions
measure_bash_conditional() {
    time {
        if [[ $(cat "$file") == *"$string"* ]]; then
            echo "Bash conditional: String found."
        else
            echo "Bash conditional: String not found."
        fi
    }
}

# Execute the functions
echo "Measuring grep..."
measure_grep

echo "Measuring awk..."
measure_awk

echo "Measuring sed..."
measure_sed

echo "Measuring Bash loop..."
measure_bash_loop

echo "Measuring Bash Conditional Expressions..."
measure_bash_conditional</pre>
<pre class="urvanov-syntax-highlighter-plain-tag">Measuring grep...
grep: String found.

real    0m0.073s
user    0m0.015s
sys     0m0.000s

Measuring awk...
awk: String found.

real    0m0.209s
user    0m0.125s
sys     0m0.015s
Measuring sed...
sed: String found.

real    0m0.252s
user    0m0.187s
sys     0m0.000s

Measuring Bash loop...

Bash loop: String found.

real    1m39.973s
user    0m50.156s
sys     0m34.875s
Measuring Bash Conditional Expressions...

Bash conditional: String found.

real    0m6.878s
user    0m0.687s
sys     0m2.796s</pre>
<p>The <code>grep</code> command is fastest of all as it is meant for searching text data.</p>
<h2>11. Conclusion</h2>
<p>In this article, we have different ways for checking if file contains a String. Let&#8217;s highlight important points:</p>
<ul>
<li><strong>For simple string searching tasks in a file, grep proves to be the most efficient tool in terms of speed and CPU usage.</strong></li>
<li>While <code>awk</code> and <code>sed</code> offer more versatility for complex text processing, they are less efficient for straightforward string searches. For example: Once it&#8217;s confirmed that the file includes the string, substitute &#8216;Error&#8217; with &#8216;Exception&#8217; and proceed with similar replacements.etc.</li>
<li>Bash loops and conditional expressions are significantly slower and less efficient for this task, and their use should be limited to cases where command-line tools like <code>grep</code>, <code>awk</code>, or <code>sed</code> are not viable.</li>
</ul>
]]></content:encoded>
					
					<wfw:commentRss>https://java2blog.com/check-if-file-contains-string-in-bash/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>Get Password Policy for User in Active Directory in PowerShell</title>
		<link>https://java2blog.com/powershell-get-password-policy-for-user-in-active-directory/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=powershell-get-password-policy-for-user-in-active-directory</link>
					<comments>https://java2blog.com/powershell-get-password-policy-for-user-in-active-directory/#respond</comments>
		
		<dc:creator><![CDATA[Java2blog]]></dc:creator>
		<pubDate>Sun, 20 Aug 2023 10:41:00 +0000</pubDate>
				<category><![CDATA[PowerShell AD]]></category>
		<category><![CDATA[PowerShell]]></category>
		<guid isPermaLink="false">https://java2blog.com/?p=24709</guid>

					<description><![CDATA[Using Get-ADDefaultDomainPasswordPolicy Cmdlet The Get-ADDefaultDomainPasswordPolicy is used to get the default password policy for the specified domain. We can use it differently in different use cases; let&#8217;s learn a few of them below. Use the Get-ADDefaultDomainPasswordPolicy cmdlet with the -Current parameter to get the default password policy for the currently logged-on user in an active [&#8230;]]]></description>
										<content:encoded><![CDATA[<h2>Using <code>Get-ADDefaultDomainPasswordPolicy</code> Cmdlet</h2>
<p>The <code>Get-ADDefaultDomainPasswordPolicy</code> is used to get the default password policy for the specified domain. We can use it differently in different use cases; let&#8217;s learn a few of them below. </p>
<p><strong>Use the <code>Get-ADDefaultDomainPasswordPolicy</code> cmdlet with the <code>-Current</code> parameter to get the default password policy for the currently logged-on user in an active directory. Here, the user can be an <code>Administrator</code> or any XYZ name.</strong></p>
<pre class="urvanov-syntax-highlighter-plain-tag">Get-ADDefualtDomainPasswordPolicy -Current LoggedOnUser</pre>
<pre class="urvanov-syntax-highlighter-plain-tag">ComplexityEnabled           : True
DistuniguishedName          : DC=maslab,DC=com
LockoutDuration             : 00:30:00
LockoutObservationWindow    : 00:30:00
LockoutThreshold            : 0
MaxPasswordAge              : 42.00:00:00
MinPasswordAge              : 1.00:00:00
MinPasswordLength           : 7
objectClass                 : {domainDNS}
objectGuid                  : 574e7bd0-a042-45d2-8fdd-00ca4cb0a769
PasswordHistoryCount        : 24
ReversibleEncryptionEnabled : False</pre>
<p>Alternatively, we can use the <code>Get-ADDefualtDomainPasswordPolicy</code> cmdlet alone to retrieve the default password policy from the currently logged-on user domain.</p>
<p><strong>Use the <code>Get-ADDefaultDomainPasswordPolicy</code> cmdlet with the <code>-Identity</code> parameter to get the default password policy for the specified domain in an active directory; in our case, it is <code>maslab.com</code>.</strong></p>
<pre class="urvanov-syntax-highlighter-plain-tag">Get-ADDefaultDomainPasswordPolicy -Identity maslab.com</pre>
<pre class="urvanov-syntax-highlighter-plain-tag">ComplexityEnabled           : True
DistuniguishedName          : DC=maslab,DC=com
LockoutDuration             : 00:30:00
LockoutObservationWindow    : 00:30:00
LockoutThreshold            : 0
MaxPasswordAge              : 42.00:00:00
MinPasswordAge              : 1.00:00:00
MinPasswordLength           : 7
objectClass                 : {domainDNS}
objectGuid                  : 574e7bd0-a042-45d2-8fdd-00ca4cb0a769
PasswordHistoryCount        : 24
ReversibleEncryptionEnabled : False</pre>
<h3>Use <code>Get-ADForest</code> with <code>Get-ADDefaultDomainPasswordPolicy</code></h3>
<p><strong>Use the <code>Get-ADForest</code> cmdlet along with the <code>Get-ADDefaultDomainPasswordPolicy</code> cmdlet to retrieve default password policy objects from all domains in the specified forest.</strong></p>
<pre class="urvanov-syntax-highlighter-plain-tag">(Get-ADForest -Current LoggedOnUser).Domains |
ForEach-Object{ 
    Get-ADDefaultDomainPasswordPolicy -Identity $_
}</pre>
<pre class="urvanov-syntax-highlighter-plain-tag">ComplexityEnabled           : True
DistuniguishedName          : DC=maslab,DC=com
LockoutDuration             : 00:30:00
LockoutObservationWindow    : 00:30:00
LockoutThreshold            : 0
MaxPasswordAge              : 42.00:00:00
MinPasswordAge              : 1.00:00:00
MinPasswordLength           : 7
objectClass                 : {domainDNS}
objectGuid                  : 574e7bd0-a042-45d2-8fdd-00ca4cb0a769
PasswordHistoryCount        : 24
ReversibleEncryptionEnabled : False</pre>
<p>First, we used the <a href="https://learn.microsoft.com/en-us/powershell/module/activedirectory/get-adforest?view=windowsserver2022-ps" target="_blank" rel="noopener">Get-ADForest</a> cmdlet to retrieve details about a current Active Directory forest using the domain of a currently logged-on user. You might be thinking that how this cmdlet would know about logged-on users. It was because we specified the <code>-Current</code> parameter and set its value to the <code>LoggedOnUser</code>. This cmdlet got the forest object containing the forest name, forest functional level, domain names, etc.</p>
<p>Then, we used the <code>.Domain</code> property to get all domains in the current Active Directory forest, which was then piped to the <code>ForEach-Object</code> cmdlet. The <code>ForEach-Object</code> cmdlet iterated over all the objects. In each iteration, we used the <code>Get-ADDefaultDomainPasswordPolicy</code> cmdlet with the <code>-Identity</code> parameter to get the password policy for the current object (<code>$_</code>).</p>
<blockquote>
<p>We got the same output because we have one domain forest (maslab.com) in our case.</p>
</blockquote>
<h3>Use <code>Get-ADUser</code> with <code>Get-ADDefaultDomainPasswordPolicy</code></h3>
<p><strong>Use the <code>Get-ADUser</code> cmdlet with the <code>Get-ADDefaultDomainPasswordPolicy</code> cmdlet to retrieve the detailed password policy for the specified user in the active directory. </strong></p>
<pre class="urvanov-syntax-highlighter-plain-tag">$user_name = "Administrator"
$user = Get-ADUser -Identity $user_name -Properties *
$domain_policy = Get-ADDefaultDomainPasswordPolicy
$password_policy_for_one_user = @{
    "Password Never Expires" = $user.PasswordNeverExpires
    "Password Last Set" = $user.PasswordLastSet
    "Password Expired" = $user.PasswordExpired
    "Minimum Password Length" = $domain_policy.MinPasswordLength
    "Minimum Password Age" = $domain_policy.MinPasswordAge
    "Maximum Password Age" = $domain_policy.MaxPasswordAge
    "Password Complexity" = $domain_policy.ComplexityEnabled
    "Password HistoryCount" = $domain_policy.HistoryLength
    "Lockout Threshold" = $domain_policy.LockoutThreshold
    "Lockout Duration" = $domain_policy.LockoutDuration
}
$password_policy_for_one_user</pre>
<pre class="urvanov-syntax-highlighter-plain-tag">Name                            Value
----                            -----
"Lockout Duration"              00:30:00
"Password Last Set"             7/16/2023 4:35:46 PM
"Minimum Password Length"       7
"Password Expired"              False
"Password Complexity"           True
"Lockout Threshold"             0
"Minimum Password Age"          1.00:00:00
"Maximum Password Age"          42.00:00:00
"Password History Count"        {}  
"Password Never Expires"        False</pre>
<p>First, we initialized the <code>$user_name</code> variable with the <code>Administrator</code>; don&#8217;t forget to replace the <code>Administrator</code> with your username. Then, we used the <a href="https://learn.microsoft.com/en-us/powershell/module/activedirectory/get-aduser?view=windowsserver2022-ps" target="_blank" rel="noopener">Get-ADUser</a> cmdlet with <code>-Identity</code> parameter to retrieve the user from the active directory and stored it in the <code>$user</code> variable; this <code>$user</code> would have all the properties because we set the <code>-Properties</code> parameter to the wildcard character (<code>*</code>) to retrieve all properties.</p>
<p>Next, we used the <code>Get-ADDefaultDomainPasswordPolicy</code> cmdlet to get the default password policy and assigned it to the <code>$domain_policy</code> variable. After that, we create a <a href="https://java2blog.com/check-if-hashtable-contains-key-powershell/">HashTable</a> to set the keys with corresponding values. We stored this HashTable in the <code>$password_policy_for_one_user</code> variable to further display it on the PowerShell console.</p>
<p>Do we have any option to use calculated properties to meet the project needs; for instance, if we want to know the password age meaning the time since the last password was changed? Yes, of course! See the following example.</p>
<p><strong>Use the <code>Get-ADUser</code> cmdlet with the <code>Get-ADDefaultDomainPasswordPolicy</code> cmdlet to display calculated properties for the mentioned user in the active directory.</strong></p>
<pre class="urvanov-syntax-highlighter-plain-tag">$user_name = "Administrator"
$user = Get-ADUser -Identity $user_name -Properties *
$domain_policy = Get-ADDefaultDomainPasswordPolicy
$password_age = (Get-Date) - $user.PasswordLastSet
$password_age_days = $password_age.TotalDays
$password_policy_for_one_user = @{
    "Password Never Expires" = $user.PasswordNeverExpires
    "Password Last Set" = $user.PasswordLastSet
    "Password Age Days" = $password_age_days
    "Password Expired" = $user.PasswordExpired
    "Minimum Password Length" = $domain_policy.MinPasswordLength
    "Minimum Password Age" = $domain_policy.MinPasswordAge
    "Maximum Password Age" = $domain_policy.MaxPasswordAge
    "Password Complexity" = $domain_policy.ComplexityEnabled
    "Password HistoryCount" = $domain_policy.HistoryLength
    "Lockout Threshold" = $domain_policy.LockoutThreshold
    "Lockout Duration" = $domain_policy.LockoutDuration
}
$password_policy_for_one_user</pre>
<pre class="urvanov-syntax-highlighter-plain-tag">Name                            Value
----                            -----
"Lockout Duration"              00:30:00
"Password Last Set"             7/16/2023 4:35:46 PM
"Minimum Password Length"       7
"Password Expired"              False
"Password Complexity"           True
"Lockout Threshold"             0
"Password Age Days"             0.293340765600694
"Minimum Password Age"          1.00:00:00
"Maximum Password Age"          42.00:00:00
"Password History Count"        {}  
"Password Never Expires"        False</pre>
<h2>Using <code>net accounts</code> Command</h2>
<p><strong>Use the <code>net accounts</code> command to get password policy details on the local computer.</strong></p>
<pre class="urvanov-syntax-highlighter-plain-tag">net accounts</pre>
<pre class="urvanov-syntax-highlighter-plain-tag">Force user logoff how long after time expires?:     Never
Minimum password age (days):                        1
Maximum password age (days):                        42
Minimum password length:                            7
Length of password history maintained:              24
Lockout threshold:                                  Never
Lockout duration (minutes):                         30
Lockout observation window (minutes):               30
Computer role:                                      PRIMARY
The command completed successfully.</pre>
<section class="read-more-posts">
<div class="rm-header">
<h2>Further reading:</h2>
</div>
<div class="rm-wrap">
<div class="rm-item">
<h5><a href="https://java2blog.com/powershell-get-password-expiration-date/" target="_blank" rel="noopener">PowerShell Get Password Expiration Date</a></h5>
<div class="ex">
            <a href="https://java2blog.com/powershell-get-password-expiration-date/" target="_blank" rel="noopener">Read more →</a>
        </div>
</div>
<div class="rm-item">
<h5><a href="https://java2blog.com/powershell-get-ad-user-account-expiration-date/" target="_blank" rel="noopener">PowerShell Get Ad User Account Expiration Date</a></h5>
<div class="ex">
            <a href="https://java2blog.com/powershell-get-ad-user-account-expiration-date/" target="_blank" rel="noopener">Read more →</a>
        </div>
</p></div>
</div>
</section>
<h2>Using Group Policy Management Editor</h2>
<p>To use the group policy management editor, follow the given steps:</p>
<p><strong>Step 1:</strong> Open group policy management editor.</p>
<p><strong>Step 2:</strong> Navigate to the <code>Default Domain Policy</code>. Right-click on it and select <code>Edit</code>.</p>
<p><img decoding="async" src="https://java2blog.com/wp-content/webpc-passthru.php?src=https://java2blog.com/wp-content/uploads/2023/07/powershell-get-password-policy-for-user-in-active-directory-edit-group-policy-management.png&amp;nocache=1" alt="powershell get password policy for user in active directory - edit group policy management" title="powershell get password policy for user in active directory - edit group policy management" /></p>
<p><strong>Step 3: </strong> Navigate to the <code>Password Policy</code> as shown in the following screenshot. You will find the password policy on the left hand (see box number 2). Double-click on any property in the box-2 to edit the details (if you want).</p>
<p><img decoding="async" src="https://java2blog.com/wp-content/webpc-passthru.php?src=https://java2blog.com/wp-content/uploads/2023/07/powershell-get-password-policy-for-user-in-active-directory-password-policy.png&amp;nocache=1" alt="powershell get password policy for user in active directory - password policy" title="powershell get password policy for user in active directory - password policy" /></p>
<p>That&#8217;s all about how to get password policy for user in active directory in PowerShell.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://java2blog.com/powershell-get-password-policy-for-user-in-active-directory/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>Get Proxy Settings in PowerShell</title>
		<link>https://java2blog.com/powershell-get-proxy-settings/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=powershell-get-proxy-settings</link>
					<comments>https://java2blog.com/powershell-get-proxy-settings/#respond</comments>
		
		<dc:creator><![CDATA[Java2blog]]></dc:creator>
		<pubDate>Sun, 20 Aug 2023 10:24:24 +0000</pubDate>
				<category><![CDATA[PowerShell]]></category>
		<guid isPermaLink="false">https://java2blog.com/?p=24785</guid>

					<description><![CDATA[1. Introduction In environments where internet access is controlled through a proxy, PowerShell scripts often need to be aware of these settings to function correctly. This article will guide you through different methods to get proxy settings using PowerShell, focusing on the proxy address, port, and its operational status. 2. Using Net.WebProxy Class The Net.WebProxy [&#8230;]]]></description>
										<content:encoded><![CDATA[<h2>1. Introduction</h2>
<p>In environments where internet access is controlled through a proxy, PowerShell scripts often need to be aware of these settings to function correctly. This article will guide you through different methods to <strong>get proxy settings using PowerShell</strong>, focusing on the proxy address, port, and its operational status.</p>
<h2>2. Using Net.WebProxy Class</h2>
<p>The <code>Net.WebProxy</code> class from the .NET Framework is a straightforward approach to obtain the system&#8217;s default proxy settings.</p>
<pre class="urvanov-syntax-highlighter-plain-tag">$proxy = [System.Net.WebProxy]::GetDefaultProxy()
"Address: " + $proxy.Address
"Bypass On Local: " + $proxy.BypassProxyOnLocal</pre>
<p>Here,<br />
<strong>[System.Net.WebProxy]::GetDefaultProxy()</strong>: Retrieves the default proxy settings.<br />
<strong>$proxy.Address</strong>: Shows the proxy server&#8217;s URI.<br />
<strong>$proxy.BypassProxyOnLocal</strong>: Indicates if local addresses bypass the proxy.</p>
<p>The settings and information obtained through Net.WebProxy are relevant to applications using the .NET framework. They may not reflect proxy configurations used by non-.NET applications or services.</p>
<h2>3. Using netsh Command</h2>
<p>The <a href="https://learn.microsoft.com/en-us/windows-server/networking/technologies/netsh/netsh" target="_blank" rel="noopener">netsh</a> (Network Shell) is the command-line tool in Windows, utilized to communicate with different network-related settings.</p>
<p>Let&#8217;s use <code>netsh</code> command to get proxy settings:</p>
<pre class="urvanov-syntax-highlighter-plain-tag">netsh winhttp show proxy</pre>
<pre class="urvanov-syntax-highlighter-plain-tag">Current WinHTTP proxy settings:
    Proxy Server(s) : 10.0.0.21:8080
    Bypass List     : (none)</pre>
<p>On Windows machines, the above command is useful for checking the current proxy settings and it is beneficial for verifying proxy settings and troubleshooting network connectivity.</p>
<p>The <code>winhttp</code> specified the context for the <code>netsh</code>, which indicates that we desire to work with the Windows HTTP services settings (<code>WinHTTP</code> settings). The <code>show proxy</code> is the particular command within the <code>WinHTTP</code> context, which displays the current proxy settings on the PowerShell console.</p>
<p>After executing this command, we got the current proxy server, port number, and any bypass list that had been configured (see the above output).</p>
<blockquote>
<p>It&#8217;s important to note that <strong>netsh winhttp show proxy does not display the proxy settings configured for a user in their web browser (like Internet Explorer, Chrome, or Firefox)</strong>. Those settings are user-specific and are stored separately from the WinHTTP settings.</p>
</blockquote>
<h2>4. Accessing Internet Explorer Proxy Settings</h2>
<p><strong>Accessing Internet Explorer Proxy Settings involves querying the Windows Registry to find out the proxy configuration specifically set for Internet Explorer (IE)</strong>. This approach is based on the fact that many Windows applications, including some older or legacy systems, use the proxy settings defined in Internet Explorer.</p>
<pre class="urvanov-syntax-highlighter-plain-tag">Get-ItemProperty -Path "HKCU:\Software\Microsoft\Windows\CurrentVersion\Internet Settings" | 
Select ProxyEnable, ProxyServer</pre>
<pre class="urvanov-syntax-highlighter-plain-tag">ProxyEnable         ProxyServer
-----------         -----------
         1          10.0.0.21:8080</pre>
<p>The above code got the proxy settings from the Windows registry. How? In this example, we used the <a href="https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.management/get-itemproperty?view=powershell-7.3" target="_blank" rel="noopener">Get-ItemProperty</a> cmdlet to get the properties of the specified item. In our case, it was the registry key specified using the <code>-Path</code> parameter. </p>
<p>In the registry key path, the <code>HKCU</code> denotes the <code>HKEY_CURRENT_USER</code> hive in the Windows registry. This registry key contains <code>Internet Settings</code>, particularly the proxy settings for the current user. We piped the output of the <code>Get-ItemProperty</code> cmdlet to the <code>Select</code> cmdlet to choose the <code>ProxyEnable</code> and <code>ProxyServer</code> properties with corresponding values.</p>
<p>The <code>ProxyEnable</code> shows the status of the proxy whether it is enabled or not. If the value of the <code>ProxyEnable</code> property is <code>1</code>, it meant the proxy is enabled. Whereas, the value of <code>0</code> for this property represents that the proxy is not enabled. The <code>ProxyServer</code> property contains the proxy-server related details as <code>Server_IP:Port</code>.</p>
<blockquote>
<p>The <code>Select</code> cmdlet is an alias of the <code>Select-Object</code> cmdlet in PowerShell.</p>
</blockquote>
<h2>5. Using WebRequest Class</h2>
<p>This method involves <strong>creating a web request to extract proxy settings using <code>WebRequest</code> class</strong>.</p>
<pre class="urvanov-syntax-highlighter-plain-tag">$request = [System.Net.WebRequest]::Create("http://www.example.com")
$proxy = $request.Proxy
if ($null -ne $proxy) {
    "Proxy URI: " + $proxy.GetProxy($request.RequestUri).ToString()
} else {
    "No proxy"
}</pre>
<p><strong>WebRequest</strong>: creates an object for a specific URL.<br />
<strong>$request.Proxy</strong>: Retrieves the proxy used by this request.<br />
<strong>GetProxy($request.RequestUri).ToString()</strong>: Outputs the proxy&#8217;s URI.</p>
<h2>6. Using Windows Settings</h2>
<p><strong>Navigate to the <code>Windows Settings &gt; Network &amp; Internet &gt; Proxy</code> and see the details about the proxy server; check the following screenshot.</strong></p>
<p><img decoding="async" src="https://java2blog.com/wp-content/webpc-passthru.php?src=https://java2blog.com/wp-content/uploads/2023/07/powershell-get-proxy-settings-proxy-server-details.png&amp;nocache=1" alt="powershell get proxy settings - proxy server details" title="powershell get proxy settings - proxy server details" /></p>
<blockquote>
<p>We can also use <code>chrome://net-internals/#proxy</code> in Google address bar and click <kbd>Enter</kbd>.</p>
</blockquote>
<h2>7. Conclusion</h2>
<p>We explored four methods to <strong>obtain proxy settings in PowerShell</strong>, catering to various network configurations and requirements. </p>
<p>These methods range from using .NET Framework classes, querying the Windows Registry, to executing system commands like netsh. Each technique offers a reliable way to ensure that PowerShell scripts can correctly identify and utilize proxy settings in a networked environment.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://java2blog.com/powershell-get-proxy-settings/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>Get Memory Usage Percentage in PowerShell</title>
		<link>https://java2blog.com/powershell-get-memory-usage-percentage/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=powershell-get-memory-usage-percentage</link>
					<comments>https://java2blog.com/powershell-get-memory-usage-percentage/#respond</comments>
		
		<dc:creator><![CDATA[Java2blog]]></dc:creator>
		<pubDate>Sun, 20 Aug 2023 10:04:42 +0000</pubDate>
				<category><![CDATA[PowerShell]]></category>
		<guid isPermaLink="false">https://java2blog.com/?p=24675</guid>

					<description><![CDATA[We can have multiple use cases for getting memory usage percentages. For example: Getting overall memory usage percentage Getting overall memory usage percentage history Getting memory usage percentage for one/all processes Let&#8217;s learn them one by one. Overcall Memory Usage Percentage We can use Get-Counter and Get-WmiObject cmdlets to retrieve the overall memory usage percentage. [&#8230;]]]></description>
										<content:encoded><![CDATA[<blockquote>
<p>We can have multiple use cases for getting memory usage percentages. For example:</p>
<ul>
<li>Getting overall memory usage percentage</li>
<li>Getting overall memory usage percentage history</li>
<li>Getting memory usage percentage for one/all processes</li>
</ul>
<p>Let&#8217;s learn them one by one.</p>
</blockquote>
<h2>Overcall Memory Usage Percentage</h2>
<p>We can use <code>Get-Counter</code> and <code>Get-WmiObject</code> cmdlets to retrieve the overall memory usage percentage. Let&#8217;s explore them below in detail.</p>
<h3>Use <code>Get-Counter</code> Cmdlet</h3>
<p><strong>Use the <code>Get-Counter</code> cmdlet to get total memory usage in percentage.</strong></p>
<pre class="urvanov-syntax-highlighter-plain-tag">$performance_counter = Get-Counter '\Memory\% Committed Bytes In Use'
$usedMemoryPercentage = $performance_counter.CounterSamples[0].CookedValue
Write-Host "Used Memory Percentage: $usedMemoryPercentage%"</pre>
<pre class="urvanov-syntax-highlighter-plain-tag">Used Memory Percentage: 57.7237514214878%</pre>
<p>We used the <a href="https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.diagnostics/get-counter?view=powershell-7.3" target="_blank" rel="noopener">Get-Counter</a> cmdlet to get the performance counter for the percentage of used memory bytes on the system and stored it in the <code>$performance_counter</code> variable. The counter path <code>&#039;\Memory\% Committed Bytes In Use&#039;</code> specified the memory counter that measured the proportion of committed memory bytes compared to the total physical memory available.</p>
<p>Then, we retrieved the performance counter&#8217;s value from <code>$performance_counter</code> and assigned it to the <code>$usedMemoryPercentage</code> variable. Now, how did we get the value of the performance counter? For that, we used the <code>CounterSamples</code> property of the <code>$performance_counter</code> variable, which contained an array of performance counter samples.</p>
<p>Since we intended to retrieve the first counter sample, we used <code>[0]</code> to access it. Then, we used the <code>CookedValue</code> property of the counter sample to get the message usage percentage. Finally, we used the <code>Write-Host</code> to display it on the PowerShell console.</p>
<h3>Use <code>Get-WmiObject</code> Cmdlet</h3>
<p><strong>Use the <code>Get-WmiObject</code> cmdlet to get the memory usage percentage if you use PowerShell version 3.0 or earlier.</strong></p>
<pre class="urvanov-syntax-highlighter-plain-tag">$usedMemory = Get-WmiObject -Class Win32_OperatingSystem
$totalMemory = $usedMemory.TotalVisibleMemorySize
$freeMemory = $usedMemory.FreePhysicalMemory
$usedMemoryPercentage = ($totalMemory - $freeMemory) / $totalMemory * 100
Write-Host "Used Memory Percentage: $usedMemoryPercentage%"</pre>
<pre class="urvanov-syntax-highlighter-plain-tag">Used Memory Percentage: 54.8795984097428%</pre>
<p>We used the <a href="https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.management/get-wmiobject?view=powershell-5.1" target="_blank" rel="noopener">Get-WmiObject</a> cmdlet to get details about the OS, particularly the <code>Win32_OperatingSystem</code>, which we specified using <code>-Class</code> parameter. We stored the retrieved details in the <code>$usedMemory</code> variable.</p>
<p>Then, we used the <code>TotalVisibleMemorySize</code> and <code>FreePhysicalMemory</code> properties of the <code>$usedMemory</code> variable to get the visible memory size and free physical memory, respectively. We stored them in two separate variables named <code>$totalMemory</code> and <code>$freeMemory</code>.</p>
<p>After that, we calculated the percentage of the memory usage by subtracting the amount of <code>$freeMemory</code> from the <code>$totalMemory</code>, dividing the output by the <code>$totalMemory</code>, then multiplying it by <code>100</code>. Finally, we stored this calculated percentage in the <code>$usedMemoryPercentage</code> variable, which we further used with the <code>Write-Host</code> cmdlet to print on the PowerShell console.</p>
<p><strong>Prefer using <a href="https://learn.microsoft.com/en-us/powershell/module/cimcmdlets/get-ciminstance?view=powershell-5.1" target="_blank" rel="noopener">Get-CimInstance</a> cmdlet if you are using PowerShell version 3.0 or higher because the <code>Get-WmiObject</code> has been superseded by <code>Get-CimInstance</code> since PowerShell 3.0.</strong></p>
<pre class="urvanov-syntax-highlighter-plain-tag">$usedMemory = Get-CimInstance -Class Win32_OperatingSystem
$totalMemory = $usedMemory.TotalVisibleMemorySize
$freeMemory = $usedMemory.FreePhysicalMemory
$usedMemoryPercentage = ($totalMemory - $freeMemory) / $totalMemory * 100
Write-Host "Used Memory Percentage: $usedMemoryPercentage%"</pre>
<pre class="urvanov-syntax-highlighter-plain-tag">Used Memory Percentage: 54.8795984097428%</pre>
<p>Until now, we have learned how to get the overall memory usage percentage; what if you only want to know how much memory percentage has been consumed by the current process on your machine? Let&#8217;s see how we can do it.</p>
<h2>Overcall Memory Usage Percentage History</h2>
<p><strong>Use the <code>Get-Counter</code> cmdlet to get the overall memory usage percentage history.</strong></p>
<pre class="urvanov-syntax-highlighter-plain-tag">Get-Counter '\Memory\% Committed Bytes In Use' -Continuous -SampleInterval 5</pre>
<pre class="urvanov-syntax-highlighter-plain-tag">Timestamp                  CounterSamples
---------                  --------------
7/15/2023 11:38:12 AM      \\desktop-nkk10jm\memory\% committed bytes in use :
                           57.3812244593588

7/15/2023 11:38:17 AM      \\desktop-nkk10jm\memory\% committed bytes in use :
                           57.3770478035736

7/15/2023 11:38:22 AM      \\desktop-nkk10jm\memory\% committed bytes in use :
                           57.3751683014853

7/15/2023 11:38:27 AM      \\desktop-nkk10jm\memory\% committed bytes in use :
                           57.3706575337263</pre>
<p>We already learned the <code>Get-Counter</code> cmdlet and counter path in the first example code. Here, we set the <code>-SampleInterval</code> parameter to <code>5</code> to get performance counter data for the percentage of the committed memory bytes in use, with the sample interval of <code>5</code> seconds. However, the <code>-Continous</code> parameter was used to continuously update the data until the user entered <kbd>Ctrl</kbd>+<kbd>C</kbd> from the keyboard to stop it.</p>
<section class="read-more-posts">
<div class="rm-header">
<h2>Further reading:</h2>
</div>
<div class="rm-wrap">
<div class="rm-item">
<h5><a href="https://java2blog.com/get-file-size-in-kb-mb-gb-powershell/" target="_blank" rel="noopener">Get File Size in KB, MB, GB in PowerShell</a></h5>
<div class="ex">
            <a href="https://java2blog.com/get-file-size-in-kb-mb-gb-powershell/" target="_blank" rel="noopener">Read more →</a>
        </div>
</div>
<div class="rm-item">
<h5><a href="https://java2blog.com/convert-array-to-arraylist-powershell/" target="_blank" rel="noopener">Convert Array to ArrayList in PowerShell</a></h5>
<div class="ex">
            <a href="https://java2blog.com/convert-array-to-arraylist-powershell/" target="_blank" rel="noopener">Read more →</a>
        </div>
</p></div>
</div>
</section>
<h2>Memory Usage Percentage for One/More Processes</h2>
<p>We can use the <code>Get-Process</code> and <code>Get-WmiObject</code> cmdlets to find the memory usage percentage for one or all processes.</p>
<h3>Use <code>Get-Process</code> Cmdlet</h3>
<p><strong>Use the <code>Get-Process</code> cmdlet to get the memory usage percentage for the current process on the local machine.</strong></p>
<pre class="urvanov-syntax-highlighter-plain-tag">$current_process = Get-Process -Id $PID
$usedMemoryPercentage = ($current_process.WorkingSet / (Get-WmiObject -Class Win32_ComputerSystem).TotalPhysicalMemory) * 100
Write-Host "Used Memory Percentage: $usedMemoryPercentage%"</pre>
<pre class="urvanov-syntax-highlighter-plain-tag">Used Memory Percentage: 0.918036721468859%</pre>
<p>We used the <code>Get-Process</code> cmdlet with the <code>-Id</code> parameter to get the information about the current process. We specified the current process using the <code>$PID</code> variable, which contained the process ID (a.k.a PID) of the current PowerShell process.</p>
<p>By setting the <code>-Id</code> with <code>$PID</code>, we got the process details for the current PowerShell session, which we assigned to the <code>$current_process</code> variable.</p>
<p>Then, we calculated the memory usage percentage and assigned it to the <code>$usedMemoryPercentage</code> variable, which was used with <code>Write-Host</code> to display on the console. But how did we calculate the memory usage percentage?</p>
<p>For that, we divided the <code>WorkingSet</code> property of the <code>$current_process</code> object (which contained the amount of memory the process was using) by the <code>TotalPhysicalMemory</code> property of the <code>Win32_ComputerSystem</code> WMI class (which contained the total amount of physical memory installed on the computer), and then multiplying the result by <code>100</code>.</p>
<p>This way, the above code retrieved the process object of the current process, calculated the memory usage percentage of that process, and then displayed the output on the PowerShell console.</p>
<h3>Use <code>Get-WmiObject</code> Cmdlet</h3>
<p><strong>Use the <code>Get-WmiObject</code> cmdlet to get the memory usage percentage for all the processes on the local machine.</strong></p>
<pre class="urvanov-syntax-highlighter-plain-tag">Get-WmiObject -Class Win32_PerfFormattedData_PerfProc_Process |
Select-Object Name, IDProcess, 
@{Name="Memory Usage %";Expression={($_.WorkingSetPrivate / (Get-WmiObject Win32_ComputerSystem).TotalPhysicalMemory) * 100}}</pre>
<pre class="urvanov-syntax-highlighter-plain-tag">Name                           IDProcess       Memory Usage %
----                           ---------       --------------
ApplicationFrameHost                8556   0.0132102058275879
CalculatorApp                      15368  0.00387112258683896
CompPkgSrv                         14692  0.00532279355690357
CxMonSvc                            3224   0.0582120058995908
CxUtilSvc                           3248  0.00503245936289065
Greenshot                          10684   0.0124359813102202
HPHotkeyNotification               15640  0.00832291356170376
HotKeyServiceUWP                    3740    0.011323033566504
HxAccounts                         10436   0.0434533510372673
HxOutlook                            480 0.000435501291019383
HxTsr                               5836   0.0515343194372936
Idle                                   0 9.67780646709739E-05
IntelCpHDCPSvc                      1264                    0
IntelCpHeciSvc                      1384  0.00508084839522613
LanWlanWwanSwitchingServiceUWP      3104   0.0180007200288012
Locator                             3504                    0
Memory Compression                  1888     3.33555277694979
MicTray64                           2348  0.00479051420121321
...                                 ...   ...
...                                 ...   ...
...                                 ...   ...</pre>
<p>The above code retrieved information about the currently running processes on the machine and calculated the memory usage percentage by each process. How?</p>
<p>First, we used the <code>Get-WmiObject</code> cmdlet with <a href="https://wutils.com/wmi/root/cimv2/win32_perfformatteddata_perfproc_process/" target="_blank" rel="nofollow noopener noreferrer">Win32_PerfFormattedData_PerfProc_Process</a> class to get performance counter date for all the processes running on the machine. Note that we used the <code>-Class</code> parameter to specify the <code>Win32_PerfFormattedData_PerfProc_Process</code> class; however, we can also omit this parameter.</p>
<p>Then, we piped the output, produced by the <code>Get-WmiObject</code>, to the <code>Select-Object</code> cmdlet to select the <code>Name</code>, <code>IDProcess</code>, and corresponding memory usage percentage. We calculated the memory percentage by dividing the process&#8217;s private working set by the computer&#8217;s total physical memory and then multiplying it by <code>100</code>.</p>
<p>Note that we used a HashTable to create a calculated property named <code>Memory Usage %</code>.</p>
<p>That&#8217;s all about how to get memory usage percentage in PowerShell. </p>
]]></content:encoded>
					
					<wfw:commentRss>https://java2blog.com/powershell-get-memory-usage-percentage/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>Get Fully Qualified Domain Name in PowerShell</title>
		<link>https://java2blog.com/powershell-get-fully-qualified-domain-name/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=powershell-get-fully-qualified-domain-name</link>
					<comments>https://java2blog.com/powershell-get-fully-qualified-domain-name/#respond</comments>
		
		<dc:creator><![CDATA[Java2blog]]></dc:creator>
		<pubDate>Sun, 20 Aug 2023 09:39:06 +0000</pubDate>
				<category><![CDATA[PowerShell AD]]></category>
		<category><![CDATA[PowerShell]]></category>
		<guid isPermaLink="false">https://java2blog.com/?p=24684</guid>

					<description><![CDATA[Using Environment Variable Use an environment variable to get a fully qualified domain name. [crayon-69d0c2eb61f06735584066/] [crayon-69d0c2eb61f0b139908822/] First, we assigned the value of the environment variable ($evn:COMPUTERNAME) to the $computer_name variable. The environment variable COMPUTERNAME stored the current computer&#8217;s name or you can say the current host&#8217;s name; both meaning the same. Then, we assigned the [&#8230;]]]></description>
										<content:encoded><![CDATA[<h2>Using Environment Variable</h2>
<p><strong>Use an environment variable to get a fully qualified domain name.</strong></p>
<pre class="urvanov-syntax-highlighter-plain-tag">$computer_name = $env:COMPUTERNAME
$fqdn = $env:USERDNSDOMAIN
Write-Output "Fully Qualified Domain Name: $computer_name.$fqdn"</pre>
<pre class="urvanov-syntax-highlighter-plain-tag">Fully Qualified Domain Name: MAS-DC-01.MASLAB.COM</pre>
<p>First, we assigned the value of the environment variable (<code>$evn:COMPUTERNAME</code>) to the <code>$computer_name</code> variable. The environment variable <code>COMPUTERNAME</code> stored the current computer&#8217;s name or you can say the current host&#8217;s name; both meaning the same.</p>
<p>Then, we assigned the <code>$fqdn</code> variable with the value of the <code>$env:USERDNSDOMAIN</code> environment variable. Here, the <code>USERDNSDOMAIN</code> stored the DNS domain name, which was associated with the current user. This meant it indicated the domain name in which the user account was registered.</p>
<p>Finally, we joined the value of the <code>$computer_name</code> and <code>$fqdn</code> by separating them with a dot. We used the <code>Write-Output</code> cmdlet to display it on the PowerShell console. </p>
<h2>Using <code>System.Net.Dns</code> Class</h2>
<p><strong>Use the <code>System.Net.Dns</code> class to get a fully qualified domain name.</strong></p>
<pre class="urvanov-syntax-highlighter-plain-tag">$host_name = [System.Net.Dns]::GetHostName()
$ip_addresses = [System.Net.Dns]::GetHostAddresses($host_name)
foreach ($current_ip in $ip_addresses) {
    if ($current_ip.AddressFamily -eq 'InterNetwork') {
        $fqdn = [System.Net.Dns]::GetHostEntry($current_ip).HostName
        break
    }
}
Write-Output "Fully Qualified Domain Name: $fqdn"</pre>
<pre class="urvanov-syntax-highlighter-plain-tag">Fully Qualified Domain Name: MAS-DC-01.maslab.com</pre>
<p>The <code>GetHostName()</code> method was called using the <a href="https://learn.microsoft.com/en-us/dotnet/api/system.net.dns?view=net-7.0" target="_blank" rel="noopener">Dns</a> class. We used it to retrieve the local machine name, which was further assigned to the <code>$host_name</code> variable.</p>
<p>We used another method called <code>GetHostAddresses()</code>, providing it with the <code>$host_name</code> as a parameter to get an array of all IP addresses associated with the <code>$host_name</code>. We stored this array in the <code>$ip_addresses</code> variable.</p>
<p>Then, we used the <code>foreach</code> loop to loop the <code>$ip_addresses</code> array. In each iteration, we used the <code>if</code> statement with the <code>-eq</code> (equal to) operator to determine whether the address family (<code>AddressFamily</code>) of a current IP address (<code>$current_ip</code>) was equal to the <code>InterNetwork</code>, which resembled the IPv4 addresses.</p>
<p>The <code>GetHostEntry()</code> method, which required the <code>$current_ip</code> parameter to create a <code>System.Net.IPHostEntry</code> object, was utilized if the requirement was met. We used the <code>HostName</code> property of the <code>System.Net.IPHostEntry</code> object to get the FQDN, which was stored in the <code>$fqdn</code> variable. Next, we exit the loop using the <code>break</code> statement. </p>
<p>Why did we exit the <code>for</code> loop? Because we only wanted to use the first IPv4 address to get the FQDN. Lastly, we used the <code>Write-Output</code> cmdlet to print <code>$fqdn</code> on the console.</p>
<p>The following are the one-line solution:</p>
<pre class="urvanov-syntax-highlighter-plain-tag">[System.Net.Dns]::GetHostEntry($env:COMPUTERNAME).HostName
#OR
[System.Net.Dns]::GetHostEntry([string]"localhost").HostName</pre>
<pre class="urvanov-syntax-highlighter-plain-tag">MAS-DC-01.maslab.com
MAS-DC-01.maslab.com</pre>
<blockquote>
<p>According to the <a href="https://learn.microsoft.com/en-us/dotnet/api/system.net.dns?view=net-7.0" target="_blank" rel="noopener">documentation</a>, the <code>GetHostByName()</code> and <code>Resolve()</code> methods are deprecated ..</p>
</blockquote>
<h2>Using <code>ping</code> Command</h2>
<p><strong>Use the <code>ping</code> command to get a fully qualified domain name.</strong></p>
<pre class="urvanov-syntax-highlighter-plain-tag">$fqdn= $(ping localhost -n 1)[1].split(" ")[1]
Write-Output "Fully Qualified Domain Name: $fqdn"</pre>
<pre class="urvanov-syntax-highlighter-plain-tag">Fully Qualified Domain Name: MAS-DC-01.maslab.com</pre>
<p>We used the <code>ping</code> command, which is a PowerShell command to get the local computer&#8217;s FQDN by pinging the hostname and parsing the result. How did the <code>ping</code> work in the above example? The <code>ping localhost -n 1</code> was used to ping the local computer once to retrieve the hostname and IP address.</p>
<p>Then, we used the command substitution (<code>$(...)</code>) to capture the output of the <code>ping localhost -n 1</code> command; however, the <code>[1]</code> got the captured output&#8217;s second line containing the hostname. Moreover, we chained the <code>split(&quot; &quot;)</code> method to split this second line into the array of words using a space as a delimiter and retrieved the second word (a hostname) by accessing the <code>1</code> index as <code>[1]</code>.</p>
<p>We stored the final output in the <code>$fqdn</code> variable, which was further used with the <code>Write-Output</code> cmdlet to print its value on the PowerShell console.</p>
<blockquote>
<p>If you do not access the index <code>1</code> twice as demonstrated in the above example, you will get more detailed output including the information about packets (sent, received, lost), round trip times (minimum, maximum, average), etc.</p>
</blockquote>
<h2>Using <code>Get-WmiObject</code> Cmdlet</h2>
<p><strong>Use the <code>Get-WmiObject</code> cmdlet to get a fully qualified domain name.</strong></p>
<pre class="urvanov-syntax-highlighter-plain-tag">$computer_name = $env:COMPUTERNAME
$wmi_obj = Get-WmiObject -Class Win32_ComputerSystem -Namespace 'root\CIMv2'
$domain_name = $wmi_obj.Domain
Write-Output "Fully Qualified Domain Name: $computer_name.$domain_name"</pre>
<pre class="urvanov-syntax-highlighter-plain-tag">Fully Qualified Domain Name: MAS-DC-01.maslab.com</pre>
<p>We started by using the <code>$env:COMPUTERNAME</code> environment variable to get the computer name of a local machine and saved it in the <code>$computer_name</code> variable. Remember, the <code>$env:COMPUTERNAME</code> contained the current computer&#8217;s name.</p>
<p>Then, we used the <a href="https://ss64.com/ps/get-wmiobject.html" target="_blank" rel="noopener">Get-WmiObject</a> cmdlet to query the Windows Management Instrumentation to get details about a computer system; particularly, we targeted the <code>Win32_ComputerSystem</code> class of <code>root\CIMv2</code> namespace, which contained different properties about computer&#8217;s operating system and hardware. We stored the details in the <code>$wmi_obj</code> variable. Here, the <code>$wmi_obj</code> represented the WMI object.</p>
<blockquote>
<p>We specified the <code>Win32_ComputerName</code> class and <code>&#039;root\CIMv2&#039;</code> namespace using <code>-Class</code> and <code>-NameSpace</code> parameters, respectively. </p>
</blockquote>
<p>Further, we used this variable to access the value of its <code>Domain</code> property representing the name of an Active Directory domain to which a computer was joined. The resulting value was stored in the <code>$domain_name</code> variable. Finally, we used the <code>Write-Output</code> cmdlet to print the fully qualified domain name on the PowerShell console.</p>
<p>Alternatively, we can use the alias of the <code>Get-WmiObject</code> cmdlet as demonstrated below:</p>
<pre class="urvanov-syntax-highlighter-plain-tag">(gwmi -Class Win32_ComputerSystem).DNSHostName+"."+(gwmi -Class Win32_ComputerSystem).Domain</pre>
<pre class="urvanov-syntax-highlighter-plain-tag">MAS-DC-01.maslab.com</pre>
<p>Here, we used the <code>.DNSHostName</code> and <code>.Domain</code> properties to get the local machine&#8217;s computer name and the domain to which the local computer was joined. We concatenated the both using concatenation operator (<code>+</code>) by separating them with a dot (<code>.</code>).</p>
<h2>Using <code>Get-CimInstance</code> Cmdlet</h2>
<p><strong>Use the <code>Get-CimInstance</code> cmdlet to get a fully qualified domain name. Go ahead with the below solution if you&#8217;re using PowerShell 3.0+. Why? As of PowerShell 3.0, the <code>Get-WmiObject</code> has been superseded by <code>Get-CimInstance</code>. Remember, you can use <code>Get-CimInstance</code> on Windows platforms only.</strong></p>
<pre class="urvanov-syntax-highlighter-plain-tag">(Get-CimInstance -Class Win32_ComputerSystem).Name+"."+(Get-CimInstance -ClassWin32_ComputerSystem).Domain</pre>
<pre class="urvanov-syntax-highlighter-plain-tag">MAS-DC-01.maslab.com</pre>
<p>This snippet resembles the last example learned in the previous section but we used <a href="https://learn.microsoft.com/en-us/powershell/module/cimcmdlets/get-ciminstance?view=powershell-7.3" target="_blank" rel="noopener">GetCimInstance</a> cmdlet to retrieve information about the <code>Win32_ComputerSystem</code> class. We used the <code>.Name</code> and <code>.Domain</code> properties to get the name of a local computer and the domain to which this computer was joined.</p>
<h2>Using <code>Get-ADComputer</code> Cmdlet</h2>
<p><strong>Use the <code>Get-ADComputer</code> cmdlet to get a fully qualified domain name. You must install the Active Directory on your machine to use this cmdlet.</strong></p>
<pre class="urvanov-syntax-highlighter-plain-tag">$fqdn = (Get-ADComputer $(hostname)).DNSHostName
Write-Output "Fully Qualified Domain Name: $fqdn"</pre>
<pre class="urvanov-syntax-highlighter-plain-tag">Fully Qualified Domain Name: MAS-DC-01.maslab.com</pre>
<p>The above command retrieved the local computer&#8217;s DNS hostname using the Active Directory module. How did it work? We used the <code>hostname</code> command as <code>$(hostname)</code> to get the hostname of a local computer, which was specified as an argument to the <a href="https://learn.microsoft.com/en-us/powershell/module/activedirectory/get-adcomputer?view=windowsserver2022-ps" target="_blank" rel="noopener">Get-ADComputer</a> cmdlet.</p>
<p>Then, the <code>Get-ADComputer</code> cmdlet accessed the information regarding a computer object in the Active Directory. Finally, we used the <code>DNSHostName</code> property to have the DNS hostname of the computer object. We assigned the resulting value to the <code>$fqdn</code> variable to further display it on the console using the <code>Write-Output</code> cmdlet.</p>
<section class="read-more-posts">
<div class="rm-header">
<h2>Further reading:</h2>
</div>
<div class="rm-wrap">
<div class="rm-item">
<h5><a href="https://java2blog.com/get-hostname-from-ip-address-powershell/" target="_blank" rel="noopener">Get Hostname from IP Address in PowerShell</a></h5>
<div class="ex">
            <a href="https://java2blog.com/get-hostname-from-ip-address-powershell/" target="_blank" rel="noopener">Read more →</a>
        </div>
</div>
<div class="rm-item">
<h5><a href="https://java2blog.com/check-if-ad-user-exists-powershell/" target="_blank" rel="noopener">Check if AD User Exists in PowerShell</a></h5>
<div class="ex">
            <a href="https://java2blog.com/check-if-ad-user-exists-powershell/" target="_blank" rel="noopener">Read more →</a>
        </div>
</p></div>
</div>
</section>
<h2>Using Registry</h2>
<p><strong>Use the registry to get a fully qualified domain name. You can use this solution if you have installed Active Directory on your computer.</strong></p>
<pre class="urvanov-syntax-highlighter-plain-tag">$domain_name = (Get-ItemProperty -Path 'HKLM:\SYSTEM\CurrentControlSet\Services\Tcpip\Parameters').Domain
$computer_name = $env:COMPUTERNAME
$fqdn = "$computer_name.$domain_name"
Write-Output "Fully Qualified Domain Name: $fqdn"</pre>
<pre class="urvanov-syntax-highlighter-plain-tag">Fully Qualified Domain Name: MAS-DC-01.maslab.com</pre>
<p>We used the <a href="https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.management/get-itemproperty?view=powershell-7.3" target="_blank" rel="noopener">Get-ItemProperty</a> cmdlet to access the <strong>&#8216;HKLM:\SYSTEM\CurrentControlSet\Services\Tcpip\Parameters&#8217;</strong> registry key to retrieve its properties. The registry key we used for this code contained network-related configuration settings.</p>
<p>We used the <code>.Domain</code> property to retrieve the domain name of the computer. This domain name is often set in the registry when a computer connects to the Active Directory domain. We stored the value of the <code>.Domain</code> property in the <code>$domain_name</code> variable.</p>
<p>After that, we used the <code>$env:COMPUTERNAME</code> to get the local computer&#8217;s name and stored it in the <code>$computer_name</code> variable. Next, we joined the <code>$computer_name</code> and <code>$domain_name</code> by separating them using a dot (<code>.</code>), and assigned the concatenated value to the <code>$fqdn</code> variable, which was further used with <code>Write-Output</code> to display it on the PowerShell console.</p>
<p>That&#8217;s all about how to get fully qualified domain name in PowerShell.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://java2blog.com/powershell-get-fully-qualified-domain-name/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>Loop Through JSON File in PowerShell</title>
		<link>https://java2blog.com/powershell-loop-through-json-file/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=powershell-loop-through-json-file</link>
					<comments>https://java2blog.com/powershell-loop-through-json-file/#respond</comments>
		
		<dc:creator><![CDATA[Java2blog]]></dc:creator>
		<pubDate>Sun, 20 Aug 2023 09:07:03 +0000</pubDate>
				<category><![CDATA[PowerShell File]]></category>
		<category><![CDATA[PowerShell]]></category>
		<guid isPermaLink="false">https://java2blog.com/?p=24668</guid>

					<description><![CDATA[Using ConvertFrom-Json Cmdlet We can use the ConvertFrom-Json cmdlet to traverse the JSON file with first and nested-level keys; Let&#8217;s explore them below. Traverse JSON File Containing First-Level Keys Use ConvertFrom-Json with the foreach loop to traverse the JSON file having first-level keys only. [crayon-69d0c2eb62426328536561/] [crayon-69d0c2eb6242a446866545/] [crayon-69d0c2eb6242b563545794/] We used the Get-Content cmdlet to read the [&#8230;]]]></description>
										<content:encoded><![CDATA[<h2>Using <code>ConvertFrom-Json</code> Cmdlet</h2>
<p>We can use the <code>ConvertFrom-Json</code> cmdlet to traverse the JSON file with first and nested-level keys; Let&#8217;s explore them below.</p>
<h3>Traverse JSON File Containing First-Level Keys</h3>
<p><strong>Use <code>ConvertFrom-Json</code> with the <code>foreach</code> loop to traverse the JSON file having first-level keys only.</strong></p>
<pre class="urvanov-syntax-highlighter-plain-tag">{
    "name": "John Christoper",
    "age": 40,
    "city": "Washington"
}</pre>
<pre class="urvanov-syntax-highlighter-plain-tag">$jsonData = Get-Content -Path "./file.json" -Raw | ConvertFrom-Json
foreach ($current_property in $jsonData.PSObject.Properties) {
    Write-Host "$($current_property.Name): $($current_property.Value)"
}</pre>
<pre class="urvanov-syntax-highlighter-plain-tag">name: John Christoper
age: 40
city: Washington</pre>
<p>We used the <code>Get-Content</code> cmdlet to read the contents of a JSON file located at <strong>./file.json</strong> path, which we specified using the <code>-Path</code> parameter. The <code>-Raw</code> parameter ensured the file&#8217;s entire content was read as a single string before passing to the <code>ConvertFrom-Json</code> cmdlet.</p>
<p>We used the <a href="https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.utility/convertfrom-json?view=powershell-7.3" target="_blank" rel="noopener">ConvertFrom-Json</a> cmdlet to convert the JSON string into a PowerShell object (<code>PSObject</code>), which we stored in the <code>$jsonData</code> variable. Then, we used the <code>for</code> loop to iterate over all properties in the <code>$jsonData</code>.</p>
<p>How did we retrieve all properties? This expression <code>$json.PSObject.Properties</code> retrieved the properties of the <code>$jsonData</code> object as a collection.</p>
<p>For each property (<code>$current_property</code>), we used <code>$current_property.Name</code> and <code>$current_property.Value</code> to retrieve the current property name and its corresponding value, respectively.</p>
<p>After that, we constructed a string by combining the property name and its value as <code>&quot;$($current_property.Name): $($current_property.Value)&quot;</code> to further display on the PowerShell console using the <code>Write-Host</code> cmdlet.</p>
<p>Let&#8217;s take another example, but we will take the key from the user this time; see the following example.</p>
<pre class="urvanov-syntax-highlighter-plain-tag">{
    "name": "John Christoper",
    "age": 40,
    "city": "Washington"
}</pre>
<pre class="urvanov-syntax-highlighter-plain-tag">$jsonData = Get-Content -Path "./file.json" -Raw | ConvertFrom-Json
$key = Read-Host -Prompt "Enter key"

foreach ($record in $jsonData) {
   if ($record |
       Select-Object -ExpandProperty $key -ErrorAction SilentlyContinue){
           Write-Host "$($record.$key)"
    }else{
           Write-Host "The given key was not found."
    }
}</pre>
<pre class="urvanov-syntax-highlighter-plain-tag">Enter key: name
John Christopher</pre>
<pre class="urvanov-syntax-highlighter-plain-tag">Enter key: random
The given key was not found.</pre>
<p>Again, we used the <code>Get-Content</code> and <code>ConvertFrom-Json</code> to read the JSON file&#8217;s content and assign it to the <code>$jsonData</code> variable. After that, we used the <code>Read-Host</code> cmdlet with the <code>-Prompt</code> parameter to prompt the user and enter the desired key. We stored this key in the <code>$key</code> variable.</p>
<p>Next, we used the <code>foreach</code> loop (a.k.a. <code>foreach</code> statement) to iterate over the <code>$jsonData</code>. In each iteration, we piped the <code>$record</code> to the <a href="https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.utility/select-object?view=powershell-7.3" target="_blank" rel="noopener">Select-Object</a> cmdlet with the <code>-ExpandProperty</code> parameter to select and expand the property given by the <code>$key</code>. </p>
<p>We set the <code>-ErrorAction</code> to the <code>SilentlyContinue</code> to suppress the error message because we wanted to show our custom message rather than the error generated by the PowerShell.</p>
<p>So, if the <code>$key</code> was present in the JSON file, the <code>Write-Host</code> cmdlet from the <code>if</code> block would be executed to print the corresponding value; otherwise, the <code>else</code> block would be executed to display a message on the console saying the given know not found.</p>
<p>Let&#8217;s dive deeper and work with the JSON file with nested keys.</p>
<h3>Traverse JSON File Containing First-Level Keys</h3>
<p><strong>Use <code>ConvertFrom-Json</code> with the <code>foreach</code> loop to traverse the JSON file having nested keys.</strong></p>
<pre class="urvanov-syntax-highlighter-plain-tag">{
    "student1": {
        "name": {
            "firstName": "John",
            "lastName": "Doe"
        },
        "age": 30,
        "Courses": {
            "CS123": "Introduction to Computer Science",
            "DS234": "Introduction to DataScience"
        }
    },
    "student2": {
        "name": {
            "firstName": "Thomas",
            "lastName": "Nelsan"
        },
        "age": 28,
        "Courses": {
            "CS123": "Java Programming",
            "Ph234": "Introduction to Psychology"
        }
    }
}</pre>
<pre class="urvanov-syntax-highlighter-plain-tag">#Define a function named TraverseJson that takes a JSON object ($json)
#and an optional prefix ($prefix)
function TraverseJson($json, $prefix = '') {

    # Iterate over each property in the JSON object
    foreach ($property in $json.PSObject.Properties) {

        # Get the name and value of the property
        $propertyName = $property.Name
        $propertyValue = $property.Value

        # Check if the property value is a nested object
        if ($propertyValue -is [System.Management.Automation.PSCustomObject]) {

            # Check if it's the first level of keys
            if ($prefix -eq '') {
                # Display the available first-level keys
                Write-Host "First level keys:"
                foreach ($firstLevelKey in $json.PSObject.Properties.Name) {
                    Write-Host "- $firstLevelKey"
                }

                # Prompt the user to choose a first-level key
                $firstLevelKey = Read-Host "Choose a first level key (enter 'exit' to exit)"

                # If 'exit' is entered, return and exit the recursion
                if ($firstLevelKey -eq "exit") {
                    return
                }

                # If the chosen first-level key is valid
                elseif ($json.PSObject.Properties.Name -contains $firstLevelKey) {
                    # Get the available second-level keys for the chosen first-level key
                    $secondLevelKeys = $json.$firstLevelKey.PSObject.Properties.Name
                    Write-Host "Second level keys under '$firstLevelKey':"
                    foreach ($secondLevelKey in $secondLevelKeys) {
                        Write-Host "- $secondLevelKey"
                    }

                    # Prompt the user to choose a second-level key
                    $secondLevelKey = Read-Host "Choose a second level key (enter 'exit' to exit)"

                    # If 'exit' is entered, return and exit the recursion
                    if ($secondLevelKey -eq "exit") {
                        return
                    }

                    # If the chosen second-level key is valid
                    elseif ($secondLevelKeys -contains $secondLevelKey) {
                        # Get the nested value corresponding to the chosen keys
                        $nestedValue = $json.$firstLevelKey.$secondLevelKey
                        Write-Host "Value of '$firstLevelKey.$secondLevelKey': $nestedValue"
                    }

                    else {
                        Write-Host "Invalid second level key. Please try again."
                    }

                    # Recursively call the TraverseJson function with the
                    #nested value and an updated prefix
                    TraverseJson $json.$firstLevelKey.$secondLevelKey ($firstLevelKey + '.' + $secondLevelKey + '.')
                }
                else {
                    Write-Host "Invalid first level key. Please try again."
                }

                # Return to exit the recursion
                return
            }

            # If it's not the first level of keys
            else {
                # Recursively call the TraverseJson function with the
                #nested object and an updated prefix
                TraverseJson $propertyValue ($prefix + $propertyName + '.')
            }
        }

        # If the property value is an ArrayList
        elseif ($propertyValue -is [System.Collections.ArrayList]) {
            # Iterate over each item in the ArrayList
            $index = 0
            foreach ($item in $propertyValue) {
                #Recursively call the TraverseJson function with the item
                #and an updated prefix, including the array index
                TraverseJson $item ($prefix + $propertyName + "[$index].")
                $index++
            }
        }

        # If it's a regular property (not a nested object or ArrayList)
        else {
            # Display the key and value
            Write-Host "${prefix}${propertyName}: ${propertyValue}"
        }
    }
}

#Read the content of the JSON file and convert it to a JSON object
$json = Get-Content -Path "./file.json" -Raw | ConvertFrom-Json

#Call the TraverseJson function with the JSON object
TraverseJson $json</pre>
<pre class="urvanov-syntax-highlighter-plain-tag">First level keys:
- student1
- student2
Choose a first level key from the options above (or enter 'exit' to exit): student1
Second level keys under 'student1':
- name
- age
- Courses
Choose a second level key from the options above (or enter 'exit' to exit): age
Value of 'student1.age': 30</pre>
<pre class="urvanov-syntax-highlighter-plain-tag">First level keys:
- student1
- student2
Choose a first level key from the options above (or enter 'exit' to exit): student2
Second level keys under 'student2':
- name
- age
- Courses
Choose a second level key from the options above (or enter 'exit' to exit): Courses
Value of 'student2.Courses': @{CS123=Java Programming; Ph234=Introduction to Psychology}
student2.Courses.CS123: Java Programming
student2.Courses.Ph234: Introduction to Psychology</pre>
<p>Don&#8217;t be afraid to look at the code; it is very simple and straightforward; Let&#8217;s learn it step by step below:</p>
<ul>
<li>First, we defined the <code>TraverseJson</code> function, which took two parameters: <code>$json</code> represented the JSON object, and <code>$prefiex</code> stored the prefix for nested keys. This function recursively traversed the JSON object and displayed the key-value pairs.</li>
<li>The <code>TraverseJson</code> function began with the <code>foreach</code> loop, which iterated over the properties of the <code>$json</code> object using <code>$json.PSObject.Properties</code>.</li>
<li>Inside the <code>foreach</code> loop, the name and value for every property are assigned to the  <code>$propertyName</code> and <code>$propertyValue</code> variables, respectively.</li>
<li>Then, the above code checked if the <code>$propertyValue</code> was a nested object using the <code>-is</code> operator and the type <code>[System.Management.Automation.PSCustomObject]</code>. If it was, the code entered the <code>if</code> block.</li>
<li>There was an additional check for the <code>$prefix</code> variable within the <code>if</code> block. We were at the first level of keys if it was an empty string. In this case, the code displayed the available first-level keys by iterating over <code>$json.PSObject.Properties.Name</code> and prompted the user to choose a first-level key.</li>
<li>If the user entered <code>exit</code>, the function returned and exited the recursion. Otherwise, if the chosen first-level key was valid (<code>$json.PSObject.Properties.Name -contains $firstLevelKey</code>), the code displayed the available second-level keys for the chosen first-level key.</li>
<li>The second-level keys were obtained from <code>$json.$firstLevelKey.PSObject.Properties.Name</code> and displayed to the user.</li>
<li>The user was prompted to choose a second-level key. If <code>exit</code> was entered, the function returned and exited the recursion. If the chosen second-level key was valid (<code>$secondLevelKeys -contains $secondLevelKey</code>), the code retrieved the corresponding nested value using <code>$json.$firstLevelKey.$secondLevelKey</code> and displayed it.</li>
<li>If the chosen second-level key was invalid, an error message was displayed, and the user was prompted to try again.</li>
<li>Finally, the <code>TraverseJson</code> function called itself recursively with the selected nested value (<code>$json.$firstLevelKey.$secondLevelKey</code>) and an updated prefix (<code>$firstLevelKey + &#039;.&#039; + $secondLevelKey + &#039;.&#039;</code>).</li>
<li>If the <code>$prefix</code> was not empty (indicating nested keys), the function recursively called <code>TraverseJson</code> on the nested object (<code>$propertyValue</code>) with an updated prefix (<code>$prefix + $propertyName + &#039;.&#039;</code>).</li>
<li>If the <code>$propertyValue</code> was an ArrayList, the code entered an <code>elseif</code> block and iterated over each item in the ArrayList using a <code>foreach</code> loop. It recursively called <code>TraverseJson</code> on every item with an updated prefix that included the array index.</li>
<li>If the <code>$propertyValue</code> was neither a nested object nor an ArrayList, it entered the <code>else</code> block and displayed the full key path along with the corresponding value using the <code>Write-Host</code> cmdlet.</li>
<li>Finally, outside the function, the code read the JSON file content using the <code>Get-Content</code> cmdlet, converted it to a JSON object using <code>ConvertFrom-Json</code>, and called the <code>TraverseJson</code> function with the JSON object.</li>
</ul>
<p>So, the above code allowed the user to interactively traverse a JSON object, select keys at different levels, and view their corresponding values. This code is limited to second-level keys; you can add value to it to fit your requirements.</p>
<p>What is the importance of using <code>ConvertFrom-Json</code>, which compels us to use it in every above solution? Because PowerShell can&#8217;t iterate over the JSON objects directly, we used the <code>ConvertFrom-Json</code> to convert the JSON string to a PSCustomObject, where each property represents a JSON field.</p>
<blockquote>
<p>The above solutions will work if you use PowerShell version 3.0+; run the <code>$PSVersionTable.PSVersion</code> to check your PowerShell version. If you are using PowerShell version 2.0 or looking for an alternative, the following solution is for you.</p>
</blockquote>
<h2>Using <code>JavaScriptSerializer</code> Class</h2>
<p><strong>Use the <code>JavaScriptSerializer</code> class to loop through the JSON if you are using PowerShell version 2.0.</strong></p>
<pre class="urvanov-syntax-highlighter-plain-tag">Add-Type -AssemblyName System.Web.Extensions
$JS = New-Object System.Web.Script.Serialization.JavaScriptSerializer
$json = @'
[{"id":1,"firstName":"John","lastName":"Doe","age":32},
{"id":2,"firstName":"Thomas","lastName":"Christoper","age":30},{"id":3,"firstName":"Johny","lastName":"Daniel","age":29}]
'@
$data = $JS.DeserializeObject($json)
$data.GetEnumerator() | foreach-Object {
    foreach ($key in $_.Keys){
        Write-Host "$key : $($_[$key])"
    }
}</pre>
<pre class="urvanov-syntax-highlighter-plain-tag">id : 1
firstName : John
lastName : Doe
age : 32
id : 2
firstName : Thomas
lastName : Christoper
age : 30
id : 3
firstName : Johny
lastName : Daniel
age : 29</pre>
<p>First, we used the <code>Add-Type</code> command to load the <code>System.Web.Extensions</code> assembly into the current session. This assembly provides classes for working with JSON data in .NET applications.</p>
<p>Then, we used the <code>New-Object</code> cmdlet to create an object of the <a href="https://renenyffenegger.ch/notes/Microsoft/dot-net/namespaces-classes/System/Web/Script/Serialization/JavaScriptSerializer" target="_blank" rel="nofollow noopener noreferrer">JavaScriptSerializer</a> class from the <code>System.Web.Script.Serialization</code> namespace, which we stored in the <code>$JS</code> variable.</p>
<p>After that, we used the <code>DeserializeObject()</code> method of the <code>$JS</code> object. This method took JSON string (<code>$json</code>) as a parameter to deserialize it into the PowerShell object. We stored the resulting object in the <code>$data</code> variable.</p>
<p>Next, we loop through each item in the <code>$data</code> using the <code>GetEnumerator()</code> method and <code>foreach-Object</code> cmdlet. Inside the <code>foreach-Object</code>, we used the <code>foreach</code> loop with the <code>Keys</code> property of the current item to iterate over each key in the current item. We displayed the corresponding key-value pair using the <code>Write-Host</code> cmdlet.</p>
<p>That&#8217;s all about how to Loop through JSON File in PowerShell.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://java2blog.com/powershell-loop-through-json-file/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>Get History of Commands in PowerShell</title>
		<link>https://java2blog.com/powershell-get-history-of-commands/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=powershell-get-history-of-commands</link>
					<comments>https://java2blog.com/powershell-get-history-of-commands/#respond</comments>
		
		<dc:creator><![CDATA[Java2blog]]></dc:creator>
		<pubDate>Sun, 20 Aug 2023 08:56:11 +0000</pubDate>
				<category><![CDATA[PowerShell]]></category>
		<guid isPermaLink="false">https://java2blog.com/?p=24773</guid>

					<description><![CDATA[Using Get-History Cmdlet Using Get-History to get the complete history of the executed commands in PowerShell. [crayon-69d0c2eb62820309655431/] [crayon-69d0c2eb62825554897666/] In this example, the history of the commands is obtained using the Get-History cmdlet. On execution of the above code, we can see the list of executed commands is returned and displayed on the screen with their [&#8230;]]]></description>
										<content:encoded><![CDATA[<h2>Using <code>Get-History</code> Cmdlet</h2>
<p><strong>Using <code>Get-History</code> to get the complete history of the executed commands in PowerShell.</strong></p>
<pre class="urvanov-syntax-highlighter-plain-tag">Get-History</pre>
<pre class="urvanov-syntax-highlighter-plain-tag">Id CommandLine
  -- -----------
   1 Get-History
   2 ls
   3 ping example.com
   4 Get-History
   5 Get-History
   6 Get-Process
   7 Get-Service</pre>
<p>In this example, the history of the commands is obtained using the <code>Get-History</code> cmdlet. On execution of the above code, we can see the list of executed commands is returned and displayed on the screen with their respective <code>Id</code> (showing the sequence of the execution of the commands) and the <code>CommandLine</code> (showing the text or command we entered). From the above output, we can see <code>7</code> commands were executed in PowerShell. </p>
<p>By default, <code>Get-History</code> does not display all the object properties on execution. To display all the object properties on the console consider the below example:</p>
<pre class="urvanov-syntax-highlighter-plain-tag">Get-History | Select-Object -Property *</pre>
<pre class="urvanov-syntax-highlighter-plain-tag">Id                 : 1
CommandLine        : Get-History
ExecutionStatus    : Completed
StartExecutionTime : 7/19/2023 3:37:00 PM
EndExecutionTime   : 7/19/2023 3:37:00 PM

Id                 : 2
CommandLine        : ls
ExecutionStatus    : Completed
StartExecutionTime : 7/19/2023 3:37:04 PM
EndExecutionTime   : 7/19/2023 3:37:05 PM

Id                 : 3
CommandLine        : ping example.com
ExecutionStatus    : Completed
StartExecutionTime : 7/19/2023 3:37:58 PM
EndExecutionTime   : 7/19/2023 3:38:02 PM

Id                 : 4
CommandLine        : Get-History
ExecutionStatus    : Completed
StartExecutionTime : 7/19/2023 3:38:13 PM
EndExecutionTime   : 7/19/2023 3:38:13 PM

Id                 : 5
CommandLine        : Get-History
ExecutionStatus    : Completed
StartExecutionTime : 7/19/2023 3:52:33 PM
EndExecutionTime   : 7/19/2023 3:52:33 PM

Id                 : 6
CommandLine        : Get-Process
ExecutionStatus    : Completed
StartExecutionTime : 7/19/2023 3:53:13 PM
EndExecutionTime   : 7/19/2023 3:53:14 PM

Id                 : 7
CommandLine        : Get-Service
ExecutionStatus    : Completed
StartExecutionTime : 7/19/2023 3:53:25 PM
StartExecutionTime : 7/19/2023 3:53:25 PM</pre>
<p>In this code, the output of <code>Get-History </code> is passed to the <code>Select-Object</code> cmdlet using the pipe operator (<code>|</code>) with the <code>-property *</code> option to get all the object properties on the console. We can observe, the given command returned <code>Id</code>, <code>CommandLine</code>, <code> ExecutionStatus</code> and the duration of the command. </p>
<h3>Get Specific Commands from the History</h3>
<p><strong>If you want to get the last three executed commands from the history check the below example</strong></p>
<pre class="urvanov-syntax-highlighter-plain-tag">Get-History -Count 3</pre>
<pre class="urvanov-syntax-highlighter-plain-tag">Id CommandLine
  -- -----------
   5 Get-History
   6 Get-Process
   7 Get-Service</pre>
<p>In the above example, the <code>-Count</code> option is used with the <code>Get-History</code> cmdlet to get the last <code>3</code> executed commands from the history. Consider the below example if you want to get the range of commands.</p>
<p><strong>Note:</strong> You can change the value of <code>-Count</code> according to your requirement. For example, if you want to get the list of the last 20 executed commands run set count as <code>-Count 20</code>.</p>
<h3>Re-execute Commands from History</h3>
<p><strong>If you want to run a specific command again from the history that you have executed. Consider the below example.</strong></p>
<pre class="urvanov-syntax-highlighter-plain-tag">Invoke-History -Id 6</pre>
<pre class="urvanov-syntax-highlighter-plain-tag">Get-Process

Handles  NPM(K)    PM(K)      WS(K)     CPU(s)     Id  SI ProcessName
-------  ------    -----      -----     ------     --  -- -----------
    336      19     9204      24588       0.14  11012   5 ApplicationFrameHost
    624      44    29696       1492       1.11  16968   5 CalculatorApp
    285      19    21348      43392       0.50   2152   5 chrome
    387      24   227000     202836      65.38   2772   5 chrome
    445      23    92284     130664      10.91   3184   5 chrome
    283      19    21556      38792       0.28   3564   5 chrome
    325      22    64852     108200      15.77   6476   5 chrome
    370      24   110008     134700       7.47   7424   5 chrome
    246      16    15172      19488       0.56   7628   5 chrome
   1001      44   152880     139736     172.61   7644   5 chrome
    293      20   101448      71412      10.50   7800   5 chrome
    292      20    39724      62776       1.64   8096   5 chrome
    438      23   139896     165516      48.23   8832   5 chrome
    279      19    21992      41580       0.38   9356   5 chrome</pre>
<p>In this code snippet, the <code>Invoke-History</code> cmdlet is used to invoke the History command and execute the command with the given id. In the above case, the command id <code>6</code> is executed which is the <code>Get-Process</code> cmdlet. Another way to write the same command is as follows:</p>
<pre class="urvanov-syntax-highlighter-plain-tag">!6</pre>
<p>In this way, you can re-execute the command from the history using the exclamation mark (<code>!</code>) followed by the command <code>id</code>. On execution of this command, you will get the same output as above.</p>
<h3>Save the Command History to a File</h3>
<p><strong>If you want to save the history of executed commands for the current session in the form of a CSV file for future use check the following example.</strong></p>
<pre class="urvanov-syntax-highlighter-plain-tag">Get-History | Export-CSV -Path 'C:\History\CommandHistory.Csv'</pre>
<p>In this PowerShell script, the output of <code>Get-History</code> is passed to the <code>Export-CSV</code> cmdlet as input using the <code>|</code> pipe operator. Here, the <code>-Path</code> option is used to specify the path where we want to save the history commands in the form of CSV. </p>
<p>On execution of the above command, no output is displayed on the screen. However, the list of executed commands is stored at path <strong>C:\History\CommandHistory.Csv</strong> with all the object properties.</p>
<blockquote>
<p><strong>Note:</strong> The history of executed commands in the current session is stored in memory by default. Once the PowerShell window is closed the history will be lost. To store the history between sessions by default configure the PowerShell to save the history to a file. </p>
</blockquote>
<section class="read-more-posts">
<div class="rm-header">
<h2>Further reading:</h2>
</div>
<div class="rm-wrap">
<div class="rm-item">
<h5><a href="https://java2blog.com/run-string-as-command-powershell/" target="_blank" rel="noopener">Run String as Command in PowerShell</a></h5>
<div class="ex">
            <a href="https://java2blog.com/run-string-as-command-powershell/" target="_blank" rel="noopener">Read more →</a>
        </div>
</div>
<div class="rm-item">
<h5><a href="https://java2blog.com/powershell-script-to-keep-screen-active/" target="_blank" rel="noopener">PowerShell Script to Keep Screen Active</a></h5>
<div class="ex">
            <a href="https://java2blog.com/powershell-script-to-keep-screen-active/" target="_blank" rel="noopener">Read more →</a>
        </div>
</p></div>
</div>
</section>
<h3>Clear History</h3>
<p><strong>Use <code>Clear-History </code> to clear the command history in PowerShell.</strong></p>
<pre class="urvanov-syntax-highlighter-plain-tag">Clear-History</pre>
<p>By executing the above command the history of the current PowerShell session is removed.</p>
<p>That&#8217;s all about how to get history of Commands in PowerShell.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://java2blog.com/powershell-get-history-of-commands/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
	</channel>
</rss>
