import jinja2


def ps_filter(val):
    """Jinja2 filter function 'ps' escapes for use in a PowerShell commandline"""
    if isinstance(val, jinja2.Undefined):
        return "[undefined]"
    escaped = []
    for char in str(val):
        if char in "`$#'\"":
            char = "`" + char
        elif char == '\0':
            char = "`0"
        elif char == '\a':
            char = "`a"
        elif char == '\b':
            char = "`b"
        elif char == '\f':
            char = "`f"
        elif char == '\n':
            char = "`n"
        elif char == '\r':
            char = "`r"
        elif char == '\t':
            char = "`t"
        elif char == '\v':
            char = "`v"
        escaped.append(char)
    return ''.join(escaped)